blob: 11641b4a1484993b565a40f7ce4bd3ddde5e5bac [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
Glenn Kastenfc7992b2012-08-29 11:10:32 -070079#include <media/nbaio/AudioStreamOutSink.h>
80#include <media/nbaio/MonoPipe.h>
81#include <media/nbaio/MonoPipeReader.h>
82#include <media/nbaio/Pipe.h>
83#include <media/nbaio/PipeReader.h>
84#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070085
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Glenn Kasten3ed29202012-08-07 15:24:44 -0700168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
170// Currently the client uses double-buffering by default, but doesn't tell us about that.
171// So for now we just assume that client is double-buffered.
Glenn Kasten2662ac92012-07-30 10:59:30 -0700172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
173// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700174// See the client's minBufCount and mNotificationFramesAct calculations for details.
175static const int kFastTrackMultiplier = 2;
176
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177// ----------------------------------------------------------------------------
178
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700179#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800180// To collect the amplifier usage
181static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800182 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
183 if (service == NULL) {
184 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800185 return;
186 }
187
188 service->addBatteryData(params);
189}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700190#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800191
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700193{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700194 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 int rc;
196
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700197 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
198 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
199 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
200 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202 }
203 rc = audio_hw_device_open(mod, dev);
204 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
205 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
206 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700208 }
209 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
210 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
211 rc = BAD_VALUE;
212 goto out;
213 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700214 return 0;
215
216out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 *dev = NULL;
218 return rc;
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221// ----------------------------------------------------------------------------
222
223AudioFlinger::AudioFlinger()
224 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800225 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700226 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 mMasterMute(false),
229 mNextUniqueId(1),
230 mMode(AUDIO_MODE_INVALID),
231 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700233}
234
235void AudioFlinger::onFirstRef()
236{
Dima Zavin799a70e2011-04-18 16:57:27 -0700237 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700238
Eric Laurent93575202011-01-18 18:39:02 -0800239 Mutex::Autolock _l(mLock);
240
Dima Zavin799a70e2011-04-18 16:57:27 -0700241 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800242 char val_str[PROPERTY_VALUE_MAX] = { 0 };
243 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
244 uint32_t int_val;
245 if (1 == sscanf(val_str, "%u", &int_val)) {
246 mStandbyTimeInNsecs = milliseconds(int_val);
247 ALOGI("Using %u mSec as standby time.", int_val);
248 } else {
249 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
250 ALOGI("Using default %u mSec as standby time.",
251 (uint32_t)(mStandbyTimeInNsecs / 1000000));
252 }
253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254
Eric Laurenta4c5a552012-03-29 10:12:40 -0700255 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256}
257
258AudioFlinger::~AudioFlinger()
259{
260 while (!mRecordThreads.isEmpty()) {
Glenn Kasten2662ac92012-07-30 10:59:30 -0700261 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700262 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
264 while (!mPlaybackThreads.isEmpty()) {
Glenn Kasten2662ac92012-07-30 10:59:30 -0700265 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700266 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700268
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800269 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
270 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
272 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274}
275
Eric Laurenta4c5a552012-03-29 10:12:40 -0700276static const char * const audio_interfaces[] = {
277 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278 AUDIO_HARDWARE_MODULE_ID_A2DP,
279 AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
John Grossmanee578c02012-07-23 17:05:46 -0700283AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
284 audio_module_handle_t module,
285 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700286{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700287 // if module is 0, the request comes from an old policy manager and we should load
288 // well known modules
289 if (module == 0) {
290 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292 loadHwModule_l(audio_interfaces[i]);
293 }
Eric Laurent88959252012-08-28 14:26:53 -0700294 // then try to find a module supporting the requested device.
295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
297 audio_hw_device_t *dev = audioHwDevice->hwDevice();
298 if ((dev->get_supported_devices != NULL) &&
299 (dev->get_supported_devices(dev) & devices) == devices)
300 return audioHwDevice;
301 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700302 } else {
303 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700304 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
305 if (audioHwDevice != NULL) {
306 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700307 }
308 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700309
Dima Zavin799a70e2011-04-18 16:57:27 -0700310 return NULL;
311}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314{
315 const size_t SIZE = 256;
316 char buffer[SIZE];
317 String8 result;
318
319 result.append("Clients:\n");
320 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800321 sp<Client> client = mClients.valueAt(i).promote();
322 if (client != 0) {
323 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
324 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 }
326 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327
328 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800329 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700330 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
331 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800332 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700333 result.append(buffer);
334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336}
337
338
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700339void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340{
341 const size_t SIZE = 256;
342 char buffer[SIZE];
343 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800344 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345
John Grossman4ff14ba2012-02-08 16:37:41 -0800346 snprintf(buffer, SIZE, "Hardware status: %d\n"
347 "Standby Time mSec: %u\n",
348 hardwareStatus,
349 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 result.append(buffer);
351 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700354void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355{
356 const size_t SIZE = 256;
357 char buffer[SIZE];
358 String8 result;
359 snprintf(buffer, SIZE, "Permission Denial: "
360 "can't dump AudioFlinger from pid=%d, uid=%d\n",
361 IPCThreadState::self()->getCallingPid(),
362 IPCThreadState::self()->getCallingUid());
363 result.append(buffer);
364 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365}
366
367static bool tryLock(Mutex& mutex)
368{
369 bool locked = false;
370 for (int i = 0; i < kDumpLockRetries; ++i) {
371 if (mutex.tryLock() == NO_ERROR) {
372 locked = true;
373 break;
374 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800375 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 }
377 return locked;
378}
379
380status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
381{
Glenn Kasten44deb052012-02-05 18:09:08 -0800382 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 dumpPermissionDenial(fd, args);
384 } else {
385 // get state of hardware lock
386 bool hardwareLocked = tryLock(mHardwareLock);
387 if (!hardwareLocked) {
388 String8 result(kHardwareLockedString);
389 write(fd, result.string(), result.size());
390 } else {
391 mHardwareLock.unlock();
392 }
393
394 bool locked = tryLock(mLock);
395
396 // failed to lock - AudioFlinger is probably deadlocked
397 if (!locked) {
398 String8 result(kDeadlockedString);
399 write(fd, result.string(), result.size());
400 }
401
402 dumpClients(fd, args);
403 dumpInternals(fd, args);
404
405 // dump playback threads
406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
407 mPlaybackThreads.valueAt(i)->dump(fd, args);
408 }
409
410 // dump record threads
411 for (size_t i = 0; i < mRecordThreads.size(); i++) {
412 mRecordThreads.valueAt(i)->dump(fd, args);
413 }
414
Dima Zavin799a70e2011-04-18 16:57:27 -0700415 // dump all hardware devs
416 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700417 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700418 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 }
Glenn Kasten8c327342012-09-30 12:29:28 -0700420
421 // dump the serially shared record tee sink
422 if (mRecordTeeSource != 0) {
423 dumpTee(fd, mRecordTeeSource);
424 }
425
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 if (locked) mLock.unlock();
427 }
428 return NO_ERROR;
429}
430
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800431sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
432{
433 // If pid is already in the mClients wp<> map, then use that entry
434 // (for which promote() is always != 0), otherwise create a new entry and Client.
435 sp<Client> client = mClients.valueFor(pid).promote();
436 if (client == 0) {
437 client = new Client(this, pid);
438 mClients.add(pid, client);
439 }
440
441 return client;
442}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443
444// IAudioFlinger interface
445
446
447sp<IAudioTrack> AudioFlinger::createTrack(
448 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800449 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800451 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700452 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -0800453 size_t frameCount,
Glenn Kastenc2674152012-11-06 15:03:34 -0800454 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800456 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800457 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458 int *sessionId,
459 status_t *status)
460{
461 sp<PlaybackThread::Track> track;
462 sp<TrackHandle> trackHandle;
463 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 status_t lStatus;
465 int lSessionId;
466
Glenn Kasten263709e2012-01-06 08:40:01 -0800467 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
468 // but if someone uses binder directly they could bypass that and cause us to crash
469 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000470 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 lStatus = BAD_VALUE;
472 goto Exit;
473 }
474
Glenn Kasten520a9af2012-06-21 12:56:37 -0700475 // client is responsible for conversion of 8-bit PCM to 16-bit PCM,
476 // and we don't yet support 8.24 or 32-bit PCM
477 if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) {
478 ALOGE("createTrack() invalid format %d", format);
479 lStatus = BAD_VALUE;
480 goto Exit;
481 }
482
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 {
484 Mutex::Autolock _l(mLock);
485 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700486 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000488 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 lStatus = BAD_VALUE;
490 goto Exit;
491 }
492
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800493 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494
Steve Block3856b092011-10-20 11:56:00 +0100495 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700496 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700497 // check if an effect chain with the same session ID is present on another
498 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700499 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700500 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
501 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700502 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700503 if (sessions & PlaybackThread::EFFECT_SESSION) {
504 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700505 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700506 }
Eric Laurentde070132010-07-13 04:45:46 -0700507 }
508 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509 lSessionId = *sessionId;
510 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700511 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700512 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513 if (sessionId != NULL) {
514 *sessionId = lSessionId;
515 }
516 }
Steve Block3856b092011-10-20 11:56:00 +0100517 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700518
519 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800520 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700521
522 // move effect chain to this output thread if an effect on same session was waiting
523 // for a track to be created
524 if (lStatus == NO_ERROR && effectThread != NULL) {
525 Mutex::Autolock _dl(thread->mLock);
526 Mutex::Autolock _sl(effectThread->mLock);
527 moveEffectChain_l(lSessionId, effectThread, thread, true);
528 }
Eric Laurenta011e352012-03-29 15:51:43 -0700529
530 // Look for sync events awaiting for a session to be used.
531 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
532 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
533 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700534 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700535 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700536 } else {
537 mPendingSyncEvents[i]->cancel();
538 }
Eric Laurenta011e352012-03-29 15:51:43 -0700539 mPendingSyncEvents.removeAt(i);
540 i--;
541 }
542 }
543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 }
545 if (lStatus == NO_ERROR) {
546 trackHandle = new TrackHandle(track);
547 } else {
548 // remove local strong reference to Client before deleting the Track so that the Client
549 // destructor is called by the TrackBase destructor with mLock held
550 client.clear();
551 track.clear();
552 }
553
554Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700555 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 *status = lStatus;
557 }
558 return trackHandle;
559}
560
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800561uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562{
563 Mutex::Autolock _l(mLock);
564 PlaybackThread *thread = checkPlaybackThread_l(output);
565 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000566 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 return 0;
568 }
569 return thread->sampleRate();
570}
571
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800572int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573{
574 Mutex::Autolock _l(mLock);
575 PlaybackThread *thread = checkPlaybackThread_l(output);
576 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000577 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return 0;
579 }
580 return thread->channelCount();
581}
582
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800583audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584{
585 Mutex::Autolock _l(mLock);
586 PlaybackThread *thread = checkPlaybackThread_l(output);
587 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000588 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800589 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 }
591 return thread->format();
592}
593
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800594size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595{
596 Mutex::Autolock _l(mLock);
597 PlaybackThread *thread = checkPlaybackThread_l(output);
598 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000599 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 return 0;
601 }
Glenn Kasten58912562012-04-03 10:45:00 -0700602 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
603 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604 return thread->frameCount();
605}
606
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800607uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608{
609 Mutex::Autolock _l(mLock);
610 PlaybackThread *thread = checkPlaybackThread_l(output);
611 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000612 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 return 0;
614 }
615 return thread->latency();
616}
617
618status_t AudioFlinger::setMasterVolume(float value)
619{
Eric Laurenta1884f92011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return ret;
623 }
624
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 // check calling permissions
626 if (!settingsAllowed()) {
627 return PERMISSION_DENIED;
628 }
629
Eric Laurenta4c5a552012-03-29 10:12:40 -0700630 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700631 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700632
John Grossmanee578c02012-07-23 17:05:46 -0700633 // Set master volume in the HALs which support it.
634 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
635 AutoMutex lock(mHardwareLock);
636 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800637
John Grossmanee578c02012-07-23 17:05:46 -0700638 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
639 if (dev->canSetMasterVolume()) {
640 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800641 }
John Grossmanee578c02012-07-23 17:05:46 -0700642 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644
John Grossmanee578c02012-07-23 17:05:46 -0700645 // Now set the master volume in each playback thread. Playback threads
646 // assigned to HALs which do not have master volume support will apply
647 // master volume during the mix operation. Threads with HALs which do
648 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800649 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700650 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651
652 return NO_ERROR;
653}
654
Glenn Kastenf78aee72012-01-04 11:00:47 -0800655status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656{
Eric Laurenta1884f92011-08-23 08:25:03 -0700657 status_t ret = initCheck();
658 if (ret != NO_ERROR) {
659 return ret;
660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661
662 // check calling permissions
663 if (!settingsAllowed()) {
664 return PERMISSION_DENIED;
665 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800666 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000667 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 return BAD_VALUE;
669 }
670
671 { // scope for the lock
672 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700673 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700674 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700675 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 mHardwareStatus = AUDIO_HW_IDLE;
677 }
678
679 if (NO_ERROR == ret) {
680 Mutex::Autolock _l(mLock);
681 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800682 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700683 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684 }
685
686 return ret;
687}
688
689status_t AudioFlinger::setMicMute(bool state)
690{
Eric Laurenta1884f92011-08-23 08:25:03 -0700691 status_t ret = initCheck();
692 if (ret != NO_ERROR) {
693 return ret;
694 }
695
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 // check calling permissions
697 if (!settingsAllowed()) {
698 return PERMISSION_DENIED;
699 }
700
701 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700702 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700704 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mHardwareStatus = AUDIO_HW_IDLE;
706 return ret;
707}
708
709bool AudioFlinger::getMicMute() const
710{
Eric Laurenta1884f92011-08-23 08:25:03 -0700711 status_t ret = initCheck();
712 if (ret != NO_ERROR) {
713 return false;
714 }
715
Dima Zavinfce7a472011-04-19 22:30:36 -0700716 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800717 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700718 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700720 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 mHardwareStatus = AUDIO_HW_IDLE;
722 return state;
723}
724
725status_t AudioFlinger::setMasterMute(bool muted)
726{
John Grossmand8f178d2012-07-20 14:51:35 -0700727 status_t ret = initCheck();
728 if (ret != NO_ERROR) {
729 return ret;
730 }
731
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 // check calling permissions
733 if (!settingsAllowed()) {
734 return PERMISSION_DENIED;
735 }
736
John Grossmanee578c02012-07-23 17:05:46 -0700737 Mutex::Autolock _l(mLock);
738 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700739
John Grossmanee578c02012-07-23 17:05:46 -0700740 // Set master mute in the HALs which support it.
741 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
742 AutoMutex lock(mHardwareLock);
743 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700744
John Grossmanee578c02012-07-23 17:05:46 -0700745 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
746 if (dev->canSetMasterMute()) {
747 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700748 }
John Grossmanee578c02012-07-23 17:05:46 -0700749 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700750 }
751
John Grossmanee578c02012-07-23 17:05:46 -0700752 // Now set the master mute in each playback thread. Playback threads
753 // assigned to HALs which do not have master mute support will apply master
754 // mute during the mix operation. Threads with HALs which do support master
755 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800756 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700757 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758
759 return NO_ERROR;
760}
761
762float AudioFlinger::masterVolume() const
763{
Glenn Kasten98067102011-12-13 11:47:54 -0800764 Mutex::Autolock _l(mLock);
765 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766}
767
768bool AudioFlinger::masterMute() const
769{
Glenn Kasten98067102011-12-13 11:47:54 -0800770 Mutex::Autolock _l(mLock);
771 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772}
773
John Grossman4ff14ba2012-02-08 16:37:41 -0800774float AudioFlinger::masterVolume_l() const
775{
John Grossman4ff14ba2012-02-08 16:37:41 -0800776 return mMasterVolume;
777}
778
John Grossmand8f178d2012-07-20 14:51:35 -0700779bool AudioFlinger::masterMute_l() const
780{
John Grossmanee578c02012-07-23 17:05:46 -0700781 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700782}
783
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800784status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
785 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786{
787 // check calling permissions
788 if (!settingsAllowed()) {
789 return PERMISSION_DENIED;
790 }
791
Glenn Kasten263709e2012-01-06 08:40:01 -0800792 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000793 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 return BAD_VALUE;
795 }
796
797 AutoMutex lock(mLock);
798 PlaybackThread *thread = NULL;
799 if (output) {
800 thread = checkPlaybackThread_l(output);
801 if (thread == NULL) {
802 return BAD_VALUE;
803 }
804 }
805
806 mStreamTypes[stream].volume = value;
807
808 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800809 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700810 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 }
812 } else {
813 thread->setStreamVolume(stream, value);
814 }
815
816 return NO_ERROR;
817}
818
Glenn Kastenfff6d712012-01-12 16:38:12 -0800819status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820{
821 // check calling permissions
822 if (!settingsAllowed()) {
823 return PERMISSION_DENIED;
824 }
825
Glenn Kasten263709e2012-01-06 08:40:01 -0800826 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700827 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000828 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 return BAD_VALUE;
830 }
831
Eric Laurent93575202011-01-18 18:39:02 -0800832 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 mStreamTypes[stream].mute = muted;
834 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700835 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836
837 return NO_ERROR;
838}
839
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800840float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841{
Glenn Kasten263709e2012-01-06 08:40:01 -0800842 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 return 0.0f;
844 }
845
846 AutoMutex lock(mLock);
847 float volume;
848 if (output) {
849 PlaybackThread *thread = checkPlaybackThread_l(output);
850 if (thread == NULL) {
851 return 0.0f;
852 }
853 volume = thread->streamVolume(stream);
854 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800855 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 }
857
858 return volume;
859}
860
Glenn Kastenfff6d712012-01-12 16:38:12 -0800861bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862{
Glenn Kasten263709e2012-01-06 08:40:01 -0800863 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 return true;
865 }
866
Glenn Kasten6637baa2012-01-09 09:40:36 -0800867 AutoMutex lock(mLock);
868 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869}
870
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800871status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872{
Glenn Kasten411e4472012-11-02 10:00:06 -0700873 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
874 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 // check calling permissions
876 if (!settingsAllowed()) {
877 return PERMISSION_DENIED;
878 }
879
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 // ioHandle == 0 means the parameters are global to the audio hardware interface
881 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700882 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700883 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800884 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
887 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
888 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
889 status_t result = dev->set_parameters(dev, keyValuePairs.string());
890 final_result = result ?: final_result;
891 }
892 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800893 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700894 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
895 AudioParameter param = AudioParameter(keyValuePairs);
896 String8 value;
897 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700898 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
899 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700900 for (size_t i = 0; i < mRecordThreads.size(); i++) {
901 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurent88959252012-08-28 14:26:53 -0700902 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -0700903 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
904 // collect all of the thread's session IDs
905 KeyedVector<int, bool> ids = thread->sessionIds();
906 // suspend effects associated with those session IDs
907 for (size_t j = 0; j < ids.size(); ++j) {
908 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700909 thread->setEffectSuspended(FX_IID_AEC,
910 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700911 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700912 thread->setEffectSuspended(FX_IID_NS,
913 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700914 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700915 }
916 }
Eric Laurentbee53372011-08-29 12:42:48 -0700917 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700918 }
919 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700920 String8 screenState;
921 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
922 bool isOff = screenState == "off";
923 if (isOff != (gScreenState & 1)) {
924 gScreenState = ((gScreenState & ~1) + 2) | isOff;
925 }
926 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700927 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 }
929
930 // hold a strong ref on thread in case closeOutput() or closeInput() is called
931 // and the thread is exited once the lock is released
932 sp<ThreadBase> thread;
933 {
934 Mutex::Autolock _l(mLock);
935 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700936 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800938 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700939 // indicate output device change to all input threads for pre processing
940 AudioParameter param = AudioParameter(keyValuePairs);
941 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700942 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
943 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700944 for (size_t i = 0; i < mRecordThreads.size(); i++) {
945 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
946 }
947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 }
949 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800950 if (thread != 0) {
951 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952 }
953 return BAD_VALUE;
954}
955
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800956String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700957{
Glenn Kasten411e4472012-11-02 10:00:06 -0700958 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
959 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960
Eric Laurenta4c5a552012-03-29 10:12:40 -0700961 Mutex::Autolock _l(mLock);
962
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700964 String8 out_s8;
965
Dima Zavin799a70e2011-04-18 16:57:27 -0700966 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800967 char *s;
968 {
969 AutoMutex lock(mHardwareLock);
970 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700971 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800972 s = dev->get_parameters(dev, keys.string());
973 mHardwareStatus = AUDIO_HW_IDLE;
974 }
John Grossmanef7740b2012-02-09 11:28:36 -0800975 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700976 free(s);
977 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700978 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 }
980
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
982 if (playbackThread != NULL) {
983 return playbackThread->getParameters(keys);
984 }
985 RecordThread *recordThread = checkRecordThread_l(ioHandle);
986 if (recordThread != NULL) {
987 return recordThread->getParameters(keys);
988 }
989 return String8("");
990}
991
Glenn Kastendd8104c2012-07-02 12:42:44 -0700992size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
993 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994{
Eric Laurenta1884f92011-08-23 08:25:03 -0700995 status_t ret = initCheck();
996 if (ret != NO_ERROR) {
997 return 0;
998 }
999
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001000 AutoMutex lock(mHardwareLock);
1001 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001002 struct audio_config config = {
1003 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001004 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001005 format: format,
1006 };
John Grossmanee578c02012-07-23 17:05:46 -07001007 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1008 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001009 mHardwareStatus = AUDIO_HW_IDLE;
1010 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011}
1012
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001013unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 Mutex::Autolock _l(mLock);
1016
1017 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1018 if (recordThread != NULL) {
1019 return recordThread->getInputFramesLost();
1020 }
1021 return 0;
1022}
1023
1024status_t AudioFlinger::setVoiceVolume(float value)
1025{
Eric Laurenta1884f92011-08-23 08:25:03 -07001026 status_t ret = initCheck();
1027 if (ret != NO_ERROR) {
1028 return ret;
1029 }
1030
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 // check calling permissions
1032 if (!settingsAllowed()) {
1033 return PERMISSION_DENIED;
1034 }
1035
1036 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001037 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001038 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001039 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040 mHardwareStatus = AUDIO_HW_IDLE;
1041
1042 return ret;
1043}
1044
Glenn Kastenb59a5022012-11-16 12:01:44 -08001045status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001046 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047{
1048 status_t status;
1049
1050 Mutex::Autolock _l(mLock);
1051
1052 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1053 if (playbackThread != NULL) {
1054 return playbackThread->getRenderPosition(halFrames, dspFrames);
1055 }
1056
1057 return BAD_VALUE;
1058}
1059
1060void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1061{
1062
1063 Mutex::Autolock _l(mLock);
1064
Glenn Kastenbb001922012-02-03 11:10:26 -08001065 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 if (mNotificationClients.indexOfKey(pid) < 0) {
1067 sp<NotificationClient> notificationClient = new NotificationClient(this,
1068 client,
1069 pid);
Steve Block3856b092011-10-20 11:56:00 +01001070 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071
1072 mNotificationClients.add(pid, notificationClient);
1073
1074 sp<IBinder> binder = client->asBinder();
1075 binder->linkToDeath(notificationClient);
1076
1077 // the config change is always sent from playback or record threads to avoid deadlock
1078 // with AudioSystem::gLock
1079 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001080 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 }
1082
1083 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001084 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 }
1086 }
1087}
1088
1089void AudioFlinger::removeNotificationClient(pid_t pid)
1090{
1091 Mutex::Autolock _l(mLock);
1092
Glenn Kastena3b09252012-01-20 09:19:01 -08001093 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001094
Steve Block3856b092011-10-20 11:56:00 +01001095 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001096 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001097 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001098 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001099 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001100 ALOGV(" pid %d @ %d", ref->mPid, i);
1101 if (ref->mPid == pid) {
1102 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001103 mAudioSessionRefs.removeAt(i);
1104 delete ref;
1105 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001106 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001107 } else {
1108 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001109 }
1110 }
1111 if (removed) {
1112 purgeStaleEffects_l();
1113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114}
1115
1116// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001117void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118{
1119 size_t size = mNotificationClients.size();
1120 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001121 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1122 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 }
1124}
1125
1126// removeClient_l() must be called with AudioFlinger::mLock held
1127void AudioFlinger::removeClient_l(pid_t pid)
1128{
Glenn Kasten411e4472012-11-02 10:00:06 -07001129 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten8af901c2012-11-01 11:11:38 -07001130 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 mClients.removeItem(pid);
1132}
1133
Eric Laurent717e1282012-06-29 16:36:52 -07001134// getEffectThread_l() must be called with AudioFlinger::mLock held
1135sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1136{
1137 sp<PlaybackThread> thread;
1138
1139 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1140 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1141 ALOG_ASSERT(thread == 0);
1142 thread = mPlaybackThreads.valueAt(i);
1143 }
1144 }
1145
1146 return thread;
1147}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148
1149// ----------------------------------------------------------------------------
1150
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001151AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent88959252012-08-28 14:26:53 -07001152 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kasten2662ac92012-07-30 10:59:30 -07001153 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001154 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001155 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001156 // mChannelMask
1157 mChannelCount(0),
1158 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1159 mParamStatus(NO_ERROR),
Eric Laurent88959252012-08-28 14:26:53 -07001160 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1161 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kasten2662ac92012-07-30 10:59:30 -07001162 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001163 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164{
1165}
1166
1167AudioFlinger::ThreadBase::~ThreadBase()
1168{
1169 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001170 // do not lock the mutex in destructor
1171 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001172 if (mPowerManager != 0) {
1173 sp<IBinder> binder = mPowerManager->asBinder();
1174 binder->unlinkToDeath(mDeathRecipient);
1175 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176}
1177
1178void AudioFlinger::ThreadBase::exit()
1179{
Steve Block3856b092011-10-20 11:56:00 +01001180 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2fa114d2012-09-28 14:49:39 -07001181 // do any cleanup required for exit to succeed
1182 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001184 // This lock prevents the following race in thread (uniprocessor for illustration):
1185 // if (!exitPending()) {
1186 // // context switch from here to exit()
1187 // // exit() calls requestExit(), what exitPending() observes
1188 // // exit() calls signal(), which is dropped since no waiters
1189 // // context switch back from exit() to here
1190 // mWaitWorkCV.wait(...);
1191 // // now thread is hung
1192 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001193 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 requestExit();
Eric Laurent67d8ac32012-09-24 15:02:17 -07001195 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001197 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1198 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 requestExitAndWait();
1200}
1201
Mathias Agopian65ab4712010-07-14 17:59:35 -07001202status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1203{
1204 status_t status;
1205
Steve Block3856b092011-10-20 11:56:00 +01001206 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 Mutex::Autolock _l(mLock);
1208
1209 mNewParameters.add(keyValuePairs);
1210 mWaitWorkCV.signal();
1211 // wait condition with timeout in case the thread loop has exited
1212 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001213 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 status = mParamStatus;
1215 mWaitWorkCV.signal();
1216 } else {
1217 status = TIMED_OUT;
1218 }
1219 return status;
1220}
1221
Eric Laurentef6be0b2012-09-13 11:18:23 -07001222void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223{
1224 Mutex::Autolock _l(mLock);
Eric Laurentef6be0b2012-09-13 11:18:23 -07001225 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226}
1227
Eric Laurentef6be0b2012-09-13 11:18:23 -07001228// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1229void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230{
Eric Laurentef6be0b2012-09-13 11:18:23 -07001231 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1232 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
Glenn Kasten8af901c2012-11-01 11:11:38 -07001233 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
1234 param);
Eric Laurentef6be0b2012-09-13 11:18:23 -07001235 mWaitWorkCV.signal();
1236}
1237
1238// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1239void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1240{
1241 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1242 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1243 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1244 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 mWaitWorkCV.signal();
1246}
1247
1248void AudioFlinger::ThreadBase::processConfigEvents()
1249{
1250 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001251 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001252 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurentef6be0b2012-09-13 11:18:23 -07001253 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 mConfigEvents.removeAt(0);
1255 // release mLock before locking AudioFlinger mLock: lock order is always
1256 // AudioFlinger then ThreadBase to avoid cross deadlock
1257 mLock.unlock();
Eric Laurentef6be0b2012-09-13 11:18:23 -07001258 switch(event->type()) {
1259 case CFG_EVENT_PRIO: {
1260 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1261 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1262 if (err != 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07001263 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
1264 "error %d",
Eric Laurentef6be0b2012-09-13 11:18:23 -07001265 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1266 }
1267 } break;
1268 case CFG_EVENT_IO: {
1269 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1270 mAudioFlinger->mLock.lock();
1271 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1272 mAudioFlinger->mLock.unlock();
1273 } break;
1274 default:
1275 ALOGE("processConfigEvents() unknown event type %d", event->type());
1276 break;
1277 }
1278 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279 mLock.lock();
1280 }
1281 mLock.unlock();
1282}
1283
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001284void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285{
1286 const size_t SIZE = 256;
1287 char buffer[SIZE];
1288 String8 result;
1289
1290 bool locked = tryLock(mLock);
1291 if (!locked) {
1292 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1293 write(fd, buffer, strlen(buffer));
1294 }
1295
Eric Laurent612bbb52012-03-14 15:03:26 -07001296 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1297 result.append(buffer);
1298 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1299 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1301 result.append(buffer);
Glenn Kasten1127d652012-11-14 08:44:39 -08001302 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001304 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1305 result.append(buffer);
1306 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307 result.append(buffer);
1308 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1309 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001310 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1311 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001312 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1313 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001314 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315 result.append(buffer);
1316
1317 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1318 result.append(buffer);
1319 result.append(" Index Command");
1320 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1321 snprintf(buffer, SIZE, "\n %02d ", i);
1322 result.append(buffer);
1323 result.append(mNewParameters[i]);
1324 }
1325
1326 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1327 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001329 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330 result.append(buffer);
1331 }
1332 result.append("\n");
1333
1334 write(fd, result.string(), result.size());
1335
1336 if (locked) {
1337 mLock.unlock();
1338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339}
1340
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001341void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001342{
1343 const size_t SIZE = 256;
1344 char buffer[SIZE];
1345 String8 result;
1346
1347 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1348 write(fd, buffer, strlen(buffer));
1349
1350 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1351 sp<EffectChain> chain = mEffectChains[i];
1352 if (chain != 0) {
1353 chain->dump(fd, args);
1354 }
1355 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001356}
1357
Eric Laurentfeb0db62011-07-22 09:04:31 -07001358void AudioFlinger::ThreadBase::acquireWakeLock()
1359{
1360 Mutex::Autolock _l(mLock);
1361 acquireWakeLock_l();
1362}
1363
1364void AudioFlinger::ThreadBase::acquireWakeLock_l()
1365{
1366 if (mPowerManager == 0) {
1367 // use checkService() to avoid blocking if power service is not up yet
1368 sp<IBinder> binder =
1369 defaultServiceManager()->checkService(String16("power"));
1370 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001371 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001372 } else {
1373 mPowerManager = interface_cast<IPowerManager>(binder);
1374 binder->linkToDeath(mDeathRecipient);
1375 }
1376 }
1377 if (mPowerManager != 0) {
1378 sp<IBinder> binder = new BBinder();
1379 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1380 binder,
1381 String16(mName));
1382 if (status == NO_ERROR) {
1383 mWakeLockToken = binder;
1384 }
Steve Block3856b092011-10-20 11:56:00 +01001385 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001386 }
1387}
1388
1389void AudioFlinger::ThreadBase::releaseWakeLock()
1390{
1391 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001392 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001393}
1394
1395void AudioFlinger::ThreadBase::releaseWakeLock_l()
1396{
1397 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001398 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001399 if (mPowerManager != 0) {
1400 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1401 }
1402 mWakeLockToken.clear();
1403 }
1404}
1405
1406void AudioFlinger::ThreadBase::clearPowerManager()
1407{
1408 Mutex::Autolock _l(mLock);
1409 releaseWakeLock_l();
1410 mPowerManager.clear();
1411}
1412
1413void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1414{
1415 sp<ThreadBase> thread = mThread.promote();
1416 if (thread != 0) {
1417 thread->clearPowerManager();
1418 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001419 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001420}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001421
Eric Laurent59255e42011-07-27 19:49:51 -07001422void AudioFlinger::ThreadBase::setEffectSuspended(
1423 const effect_uuid_t *type, bool suspend, int sessionId)
1424{
1425 Mutex::Autolock _l(mLock);
1426 setEffectSuspended_l(type, suspend, sessionId);
1427}
1428
1429void AudioFlinger::ThreadBase::setEffectSuspended_l(
1430 const effect_uuid_t *type, bool suspend, int sessionId)
1431{
Glenn Kasten090f0192012-01-30 13:00:02 -08001432 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001433 if (chain != 0) {
1434 if (type != NULL) {
1435 chain->setEffectSuspended_l(type, suspend);
1436 } else {
1437 chain->setEffectSuspendedAll_l(suspend);
1438 }
1439 }
1440
1441 updateSuspendedSessions_l(type, suspend, sessionId);
1442}
1443
1444void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1445{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001446 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001447 if (index < 0) {
1448 return;
1449 }
1450
Glenn Kasten0a7af182012-07-09 16:09:19 -07001451 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1452 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001453
1454 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001455 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001456 for (int j = 0; j < desc->mRefCount; j++) {
1457 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1458 chain->setEffectSuspendedAll_l(true);
1459 } else {
Steve Block3856b092011-10-20 11:56:00 +01001460 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001461 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001462 chain->setEffectSuspended_l(&desc->mType, true);
1463 }
1464 }
1465 }
1466}
1467
Eric Laurent59255e42011-07-27 19:49:51 -07001468void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1469 bool suspend,
1470 int sessionId)
1471{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001472 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001473
1474 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1475
1476 if (suspend) {
1477 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001478 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001479 } else {
1480 mSuspendedSessions.add(sessionId, sessionEffects);
1481 }
1482 } else {
1483 if (index < 0) {
1484 return;
1485 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001486 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001487 }
1488
1489
1490 int key = EffectChain::kKeyForSuspendAll;
1491 if (type != NULL) {
1492 key = type->timeLow;
1493 }
1494 index = sessionEffects.indexOfKey(key);
1495
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001496 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001497 if (suspend) {
1498 if (index >= 0) {
1499 desc = sessionEffects.valueAt(index);
1500 } else {
1501 desc = new SuspendedSessionDesc();
1502 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001503 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001504 }
1505 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001506 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001507 }
1508 desc->mRefCount++;
1509 } else {
1510 if (index < 0) {
1511 return;
1512 }
1513 desc = sessionEffects.valueAt(index);
1514 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001515 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001516 sessionEffects.removeItemsAt(index);
1517 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001518 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001519 sessionId);
1520 mSuspendedSessions.removeItem(sessionId);
1521 }
1522 }
1523 }
1524 if (!sessionEffects.isEmpty()) {
1525 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1526 }
1527}
1528
1529void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1530 bool enabled,
1531 int sessionId)
1532{
1533 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001534 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1535}
Eric Laurent59255e42011-07-27 19:49:51 -07001536
Eric Laurenta85a74a2011-10-19 11:44:54 -07001537void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1538 bool enabled,
1539 int sessionId)
1540{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001541 if (mType != RECORD) {
1542 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1543 // another session. This gives the priority to well behaved effect control panels
1544 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001545 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1546 // global effects
1547 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001548 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1549 }
1550 }
Eric Laurent59255e42011-07-27 19:49:51 -07001551
1552 sp<EffectChain> chain = getEffectChain_l(sessionId);
1553 if (chain != 0) {
1554 chain->checkSuspendOnEffectEnabled(effect, enabled);
1555 }
1556}
1557
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558// ----------------------------------------------------------------------------
1559
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001560AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1561 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001562 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001563 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001564 type_t type)
Eric Laurent88959252012-08-28 14:26:53 -07001565 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001566 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001567 // mStreamTypes[] initialized in constructor body
1568 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001569 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001570 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001571 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001572 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001573 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001574 // index 0 is reserved for normal mixer's submix
1575 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576{
Glenn Kasten480b4682012-02-28 12:30:08 -08001577 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001578
John Grossmanee578c02012-07-23 17:05:46 -07001579 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1580 // it would be safer to explicitly pass initial masterVolume/masterMute as
1581 // parameter.
1582 //
1583 // If the HAL we are using has support for master volume or master mute,
1584 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1585 // and the mute set to false).
1586 mMasterVolume = audioFlinger->masterVolume_l();
1587 mMasterMute = audioFlinger->masterMute_l();
1588 if (mOutput && mOutput->audioHwDev) {
1589 if (mOutput->audioHwDev->canSetMasterVolume()) {
1590 mMasterVolume = 1.0;
1591 }
1592
1593 if (mOutput->audioHwDev->canSetMasterMute()) {
1594 mMasterMute = false;
1595 }
1596 }
1597
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 readOutputParameters();
1599
Glenn Kasten263709e2012-01-06 08:40:01 -08001600 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001601 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1602 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1603 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001604 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1605 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001607 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1608 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609}
1610
1611AudioFlinger::PlaybackThread::~PlaybackThread()
1612{
1613 delete [] mMixBuffer;
1614}
1615
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001616void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617{
1618 dumpInternals(fd, args);
1619 dumpTracks(fd, args);
1620 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621}
1622
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001623void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624{
1625 const size_t SIZE = 256;
1626 char buffer[SIZE];
1627 String8 result;
1628
Glenn Kasten58912562012-04-03 10:45:00 -07001629 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1630 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1631 const stream_type_t *st = &mStreamTypes[i];
1632 if (i > 0) {
1633 result.appendFormat(", ");
1634 }
1635 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1636 if (st->mute) {
1637 result.append("M");
1638 }
1639 }
1640 result.append("\n");
1641 write(fd, result.string(), result.length());
1642 result.clear();
1643
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1645 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001646 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 for (size_t i = 0; i < mTracks.size(); ++i) {
1648 sp<Track> track = mTracks[i];
1649 if (track != 0) {
1650 track->dump(buffer, SIZE);
1651 result.append(buffer);
1652 }
1653 }
1654
1655 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1656 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001657 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001659 sp<Track> track = mActiveTracks[i].promote();
1660 if (track != 0) {
1661 track->dump(buffer, SIZE);
1662 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 }
1664 }
1665 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001666
1667 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1668 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1669 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1670 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671}
1672
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001673void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674{
1675 const size_t SIZE = 256;
1676 char buffer[SIZE];
1677 String8 result;
1678
1679 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1680 result.append(buffer);
Glenn Kasten8af901c2012-11-01 11:11:38 -07001681 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1682 ns2ms(systemTime() - mLastWriteTime));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683 result.append(buffer);
1684 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1685 result.append(buffer);
1686 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1687 result.append(buffer);
1688 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1689 result.append(buffer);
1690 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1691 result.append(buffer);
1692 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1693 result.append(buffer);
1694 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001695 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696
1697 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698}
1699
1700// Thread virtuals
1701status_t AudioFlinger::PlaybackThread::readyToRun()
1702{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001703 status_t status = initCheck();
1704 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001705 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001706 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001707 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001709 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710}
1711
1712void AudioFlinger::PlaybackThread::onFirstRef()
1713{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001714 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715}
1716
Jean-Michel Trivi2fa114d2012-09-28 14:49:39 -07001717// ThreadBase virtuals
1718void AudioFlinger::PlaybackThread::preExit()
1719{
1720 ALOGV(" preExit()");
1721 // FIXME this is using hard-coded strings but in the future, this functionality will be
1722 // converted to use audio HAL extensions required to support tunneling
1723 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1724}
1725
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001727sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001729 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001731 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001732 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08001733 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 const sp<IMemory>& sharedBuffer,
1735 int sessionId,
Glenn Kastenc2674152012-11-06 15:03:34 -08001736 IAudioFlinger::track_flags_t *flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001737 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 status_t *status)
1739{
1740 sp<Track> track;
1741 status_t lStatus;
1742
Glenn Kastenc2674152012-11-06 15:03:34 -08001743 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
Glenn Kasten73d22752012-03-19 13:38:30 -07001744
1745 // client expresses a preference for FAST, but we get the final say
Glenn Kastenc2674152012-11-06 15:03:34 -08001746 if (*flags & IAudioFlinger::TRACK_FAST) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001747 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001748 // not timed
1749 (!isTimed) &&
1750 // either of these use cases:
1751 (
1752 // use case 1: shared buffer with any frame count
1753 (
1754 (sharedBuffer != 0)
1755 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001756 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001757 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001758 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001759 ((frameCount == 0) ||
Glenn Kastend7101432012-11-14 13:42:25 -08001760 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001761 )
1762 ) &&
1763 // PCM data
1764 audio_is_linear_pcm(format) &&
1765 // mono or stereo
1766 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1767 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001768#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001769 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001770 (sampleRate == mSampleRate) &&
1771#endif
1772 // normal mixer has an associated fast mixer
1773 hasFastMixer() &&
1774 // there are sufficient fast track slots available
1775 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001776 // FIXME test that MixerThread for this fast track has a capable output HAL
1777 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001778 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001779 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1780 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001781 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001782 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001783 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001784 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001785 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001786 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten1127d652012-11-14 08:44:39 -08001787 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten58912562012-04-03 10:45:00 -07001788 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1789 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1790 audio_is_linear_pcm(format),
1791 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kastenc2674152012-11-06 15:03:34 -08001792 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001793 // For compatibility with AudioTrack calculation, buffer depth is forced
1794 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1795 // This is probably too conservative, but legacy application code may depend on it.
1796 // If you change this calculation, also review the start threshold which is related.
1797 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1798 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1799 if (minBufCount < 2) {
1800 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001801 }
Glenn Kasten7da35f22012-11-14 12:54:39 -08001802 size_t minFrameCount = mNormalFrameCount * minBufCount;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001803 if (frameCount < minFrameCount) {
1804 frameCount = minFrameCount;
1805 }
1806 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001807 }
1808
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001810 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1811 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kasten1127d652012-11-14 08:44:39 -08001812 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001813 "for output %p with format %d",
1814 sampleRate, format, channelMask, mOutput, mFormat);
1815 lStatus = BAD_VALUE;
1816 goto Exit;
1817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818 }
1819 } else {
1820 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1821 if (sampleRate > mSampleRate*2) {
Glenn Kasten1127d652012-11-14 08:44:39 -08001822 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 lStatus = BAD_VALUE;
1824 goto Exit;
1825 }
1826 }
1827
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001828 lStatus = initCheck();
1829 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001830 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 goto Exit;
1832 }
1833
1834 { // scope for mLock
1835 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001836
1837 // all tracks in same audio session must share the same routing strategy otherwise
1838 // conflicts will happen when tracks are moved from one output to another by audio policy
1839 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001840 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001841 for (size_t i = 0; i < mTracks.size(); ++i) {
1842 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001843 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001844 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001845 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001846 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001847 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001848 lStatus = BAD_VALUE;
1849 goto Exit;
1850 }
1851 }
1852 }
1853
John Grossman4ff14ba2012-02-08 16:37:41 -08001854 if (!isTimed) {
1855 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kastenc2674152012-11-06 15:03:34 -08001856 channelMask, frameCount, sharedBuffer, sessionId, *flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001857 } else {
1858 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1859 channelMask, frameCount, sharedBuffer, sessionId);
1860 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001861 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 lStatus = NO_MEMORY;
1863 goto Exit;
1864 }
1865 mTracks.add(track);
1866
1867 sp<EffectChain> chain = getEffectChain_l(sessionId);
1868 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001869 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001871 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001872 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001874
Glenn Kastenc2674152012-11-06 15:03:34 -08001875 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001876 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1877 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1878 // so ask activity manager to do this on our behalf
1879 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001880 }
1881 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001882
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 lStatus = NO_ERROR;
1884
1885Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001886 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 *status = lStatus;
1888 }
1889 return track;
1890}
1891
Glenn Kastenb59a5022012-11-16 12:01:44 -08001892uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurente737cda2012-05-22 18:55:44 -07001893{
1894 if (mFastMixer != NULL) {
1895 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1896 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1897 }
1898 return latency;
1899}
1900
Glenn Kastenb59a5022012-11-16 12:01:44 -08001901uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurente737cda2012-05-22 18:55:44 -07001902{
1903 return latency;
1904}
1905
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906uint32_t AudioFlinger::PlaybackThread::latency() const
1907{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001908 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001909 return latency_l();
1910}
1911uint32_t AudioFlinger::PlaybackThread::latency_l() const
1912{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001913 if (initCheck() == NO_ERROR) {
Glenn Kastenb59a5022012-11-16 12:01:44 -08001914 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001915 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 return 0;
1917 }
1918}
1919
Glenn Kasten6637baa2012-01-09 09:40:36 -08001920void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001922 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001923 // Don't apply master volume in SW if our HAL can do it for us.
1924 if (mOutput && mOutput->audioHwDev &&
1925 mOutput->audioHwDev->canSetMasterVolume()) {
1926 mMasterVolume = 1.0;
1927 } else {
1928 mMasterVolume = value;
1929 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930}
1931
Glenn Kasten6637baa2012-01-09 09:40:36 -08001932void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001934 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001935 // Don't apply master mute in SW if our HAL can do it for us.
1936 if (mOutput && mOutput->audioHwDev &&
1937 mOutput->audioHwDev->canSetMasterMute()) {
1938 mMasterMute = false;
1939 } else {
1940 mMasterMute = muted;
1941 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942}
1943
Glenn Kasten6637baa2012-01-09 09:40:36 -08001944void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001946 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948}
1949
Glenn Kasten6637baa2012-01-09 09:40:36 -08001950void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001952 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954}
1955
Glenn Kastenfff6d712012-01-12 16:38:12 -08001956float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001958 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 return mStreamTypes[stream].volume;
1960}
1961
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962// addTrack_l() must be called with ThreadBase::mLock held
1963status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1964{
1965 status_t status = ALREADY_EXISTS;
1966
1967 // set retry count for buffer fill
1968 track->mRetryCount = kMaxTrackStartupRetries;
1969 if (mActiveTracks.indexOf(track) < 0) {
1970 // the track is newly added, make sure it fills up all its
1971 // buffers before playing. This is to ensure the client will
1972 // effectively get the latency it requested.
1973 track->mFillingUpStatus = Track::FS_FILLING;
1974 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001975 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976 mActiveTracks.add(track);
1977 if (track->mainBuffer() != mMixBuffer) {
1978 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1979 if (chain != 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07001980 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1981 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001982 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 }
1984 }
1985
1986 status = NO_ERROR;
1987 }
1988
Steve Block3856b092011-10-20 11:56:00 +01001989 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 mWaitWorkCV.broadcast();
1991
1992 return status;
1993}
1994
1995// destroyTrack_l() must be called with ThreadBase::mLock held
1996void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1997{
1998 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001999 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002001 removeTrack_l(track);
2002 }
2003}
2004
2005void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2006{
Eric Laurent29864602012-05-08 18:57:51 -07002007 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002008 mTracks.remove(track);
2009 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002010 // redundant as track is about to be destroyed, for dumpsys only
2011 track->mName = -1;
2012 if (track->isFastTrack()) {
2013 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002014 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002015 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2016 mFastTrackAvailMask |= 1 << index;
2017 // redundant as track is about to be destroyed, for dumpsys only
2018 track->mFastIndex = -1;
2019 }
Eric Laurentb469b942011-05-09 12:09:06 -07002020 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2021 if (chain != 0) {
2022 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 }
2024}
2025
2026String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2027{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002028 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002029 char *s;
2030
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002031 Mutex::Autolock _l(mLock);
2032 if (initCheck() != NO_ERROR) {
2033 return out_s8;
2034 }
2035
Dima Zavin799a70e2011-04-18 16:57:27 -07002036 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002037 out_s8 = String8(s);
2038 free(s);
2039 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040}
2041
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002042// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2044 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002045 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046
Glenn Kasten8af901c2012-11-01 11:11:38 -07002047 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
2048 param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049
2050 switch (event) {
2051 case AudioSystem::OUTPUT_OPENED:
2052 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002053 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 desc.samplingRate = mSampleRate;
2055 desc.format = mFormat;
Glenn Kasten8af901c2012-11-01 11:11:38 -07002056 desc.frameCount = mNormalFrameCount; // FIXME see
2057 // AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 desc.latency = latency();
2059 param2 = &desc;
2060 break;
2061
2062 case AudioSystem::STREAM_CONFIG_CHANGED:
2063 param2 = &param;
2064 case AudioSystem::OUTPUT_CLOSED:
2065 default:
2066 break;
2067 }
2068 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2069}
2070
2071void AudioFlinger::PlaybackThread::readOutputParameters()
2072{
Dima Zavin799a70e2011-04-18 16:57:27 -07002073 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002074 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2075 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002076 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002077 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002078 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002079 if (mFrameCount & 15) {
2080 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2081 mFrameCount);
2082 }
2083
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002084 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002085 double multiplier = 1.0;
Glenn Kasten8af901c2012-11-01 11:11:38 -07002086 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2087 kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002088 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002089 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2090 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2091 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2092 maxNormalFrameCount = maxNormalFrameCount & ~15;
2093 if (maxNormalFrameCount < minNormalFrameCount) {
2094 maxNormalFrameCount = minNormalFrameCount;
2095 }
2096 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2097 if (multiplier <= 1.0) {
2098 multiplier = 1.0;
2099 } else if (multiplier <= 2.0) {
2100 if (2 * mFrameCount <= maxNormalFrameCount) {
2101 multiplier = 2.0;
2102 } else {
2103 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2104 }
2105 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07002106 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
2107 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
2108 // track, but we sometimes have to do this to satisfy the maximum frame count
2109 // constraint)
Glenn Kasten4adcede2012-05-14 12:26:02 -07002110 // FIXME this rounding up should not be done if no HAL SRC
2111 uint32_t truncMult = (uint32_t) multiplier;
2112 if ((truncMult & 1)) {
2113 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2114 ++truncMult;
2115 }
2116 }
2117 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002118 }
Glenn Kasten58912562012-04-03 10:45:00 -07002119 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002120 mNormalFrameCount = multiplier * mFrameCount;
2121 // round up to nearest 16 frames to satisfy AudioMixer
2122 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten8af901c2012-11-01 11:11:38 -07002123 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
2124 mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125
Glenn Kastene9dd0172012-01-27 18:08:45 -08002126 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002127 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2128 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129
Eric Laurentde070132010-07-13 04:45:46 -07002130 // force reconfiguration of effect chains and engines to take new buffer size and audio
2131 // parameters into account
2132 // Note that mLock is not held when readOutputParameters() is called from the constructor
2133 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2134 // matter.
2135 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2136 Vector< sp<EffectChain> > effectChains = mEffectChains;
2137 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002138 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140}
2141
Eric Laurente737cda2012-05-22 18:55:44 -07002142
Glenn Kastenb59a5022012-11-16 12:01:44 -08002143status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144{
Glenn Kastena0d68332012-01-27 16:47:15 -08002145 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 return BAD_VALUE;
2147 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002148 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002149 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 return INVALID_OPERATION;
2151 }
Glenn Kastenb59a5022012-11-16 12:01:44 -08002152 size_t framesWritten = mBytesWritten / mFrameSize;
2153 *halFrames = framesWritten;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002154
Eric Laurent6090a172012-09-23 15:20:50 -07002155 if (isSuspended()) {
2156 // return an estimation of rendered frames when the output is suspended
Glenn Kastenb59a5022012-11-16 12:01:44 -08002157 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2158 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
Eric Laurent6090a172012-09-23 15:20:50 -07002159 return NO_ERROR;
2160 } else {
2161 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163}
2164
Glenn Kasten106e8a42012-08-02 13:37:12 -07002165uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166{
2167 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002168 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002170 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 }
2172
2173 for (size_t i = 0; i < mTracks.size(); ++i) {
2174 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002175 if (sessionId == track->sessionId() &&
Glenn Kastend12b0332012-11-05 13:38:15 -08002176 !(track->mCblk->flags & CBLK_INVALID)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002177 result |= TRACK_SESSION;
2178 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 }
2180 }
2181
Eric Laurent39e94f82010-07-28 01:32:47 -07002182 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183}
2184
Eric Laurentde070132010-07-13 04:45:46 -07002185uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2186{
Dima Zavinfce7a472011-04-19 22:30:36 -07002187 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002188 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002189 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2190 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002191 }
2192 for (size_t i = 0; i < mTracks.size(); i++) {
2193 sp<Track> track = mTracks[i];
2194 if (sessionId == track->sessionId() &&
Glenn Kastend12b0332012-11-05 13:38:15 -08002195 !(track->mCblk->flags & CBLK_INVALID)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002196 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002197 }
2198 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002199 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002200}
2201
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202
Glenn Kastenaed850d2012-01-26 09:46:34 -08002203AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002204{
2205 Mutex::Autolock _l(mLock);
2206 return mOutput;
2207}
2208
2209AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2210{
2211 Mutex::Autolock _l(mLock);
2212 AudioStreamOut *output = mOutput;
2213 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002214 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2215 // must push a NULL and wait for ack
2216 mOutputSink.clear();
2217 mPipeSink.clear();
2218 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002219 return output;
2220}
2221
2222// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002223audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002224{
2225 if (mOutput == NULL) {
2226 return NULL;
2227 }
2228 return &mOutput->stream->common;
2229}
2230
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002231uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002232{
Eric Laurentab9071b2012-06-04 13:45:29 -07002233 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002234}
2235
Eric Laurenta011e352012-03-29 15:51:43 -07002236status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2237{
2238 if (!isValidSyncEvent(event)) {
2239 return BAD_VALUE;
2240 }
2241
2242 Mutex::Autolock _l(mLock);
2243
2244 for (size_t i = 0; i < mTracks.size(); ++i) {
2245 sp<Track> track = mTracks[i];
2246 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002247 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002248 return NO_ERROR;
2249 }
2250 }
2251
2252 return NAME_NOT_FOUND;
2253}
2254
Glenn Kasten106e8a42012-08-02 13:37:12 -07002255bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002256{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002257 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002258}
2259
Glenn Kasten8af901c2012-11-01 11:11:38 -07002260void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2261 const Vector< sp<Track> >& tracksToRemove)
Eric Laurent44a957f2012-05-15 15:26:05 -07002262{
2263 size_t count = tracksToRemove.size();
2264 if (CC_UNLIKELY(count)) {
2265 for (size_t i = 0 ; i < count ; i++) {
2266 const sp<Track>& track = tracksToRemove.itemAt(i);
2267 if ((track->sharedBuffer() != 0) &&
2268 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2269 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2270 }
2271 }
2272 }
2273
2274}
2275
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276// ----------------------------------------------------------------------------
2277
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002278AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002279 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002280 : PlaybackThread(audioFlinger, output, id, device, type),
2281 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002282 // mFastMixer below
2283 mFastMixerFutex(0)
2284 // mOutputSink below
2285 // mPipeSink below
2286 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002288 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten520a9af2012-06-21 12:56:37 -07002289 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%u, "
Glenn Kasten58912562012-04-03 10:45:00 -07002290 "mFrameCount=%d, mNormalFrameCount=%d",
2291 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2292 mNormalFrameCount);
2293 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2294
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002296 if (mChannelCount != FCC_2) {
2297 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298 }
Glenn Kasten58912562012-04-03 10:45:00 -07002299
2300 // create an NBAIO sink for the HAL output stream, and negotiate
2301 mOutputSink = new AudioStreamOutSink(output->stream);
2302 size_t numCounterOffers = 0;
2303 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2304 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2305 ALOG_ASSERT(index == 0);
2306
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002307 // initialize fast mixer depending on configuration
2308 bool initFastMixer;
2309 switch (kUseFastMixer) {
2310 case FastMixer_Never:
2311 initFastMixer = false;
2312 break;
2313 case FastMixer_Always:
2314 initFastMixer = true;
2315 break;
2316 case FastMixer_Static:
2317 case FastMixer_Dynamic:
2318 initFastMixer = mFrameCount < mNormalFrameCount;
2319 break;
2320 }
2321 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002322
2323 // create a MonoPipe to connect our submix to FastMixer
2324 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002325 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2326 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2327 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2328 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002329 const NBAIO_Format offers[1] = {format};
2330 size_t numCounterOffers = 0;
2331 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2332 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002333 monoPipe->setAvgFrames((mScreenState & 1) ?
2334 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002335 mPipeSink = monoPipe;
2336
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002337#ifdef TEE_SINK_FRAMES
2338 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2339 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2340 numCounterOffers = 0;
2341 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2342 ALOG_ASSERT(index == 0);
2343 mTeeSink = teeSink;
2344 PipeReader *teeSource = new PipeReader(*teeSink);
2345 numCounterOffers = 0;
2346 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2347 ALOG_ASSERT(index == 0);
2348 mTeeSource = teeSource;
2349#endif
2350
Glenn Kasten58912562012-04-03 10:45:00 -07002351 // create fast mixer and configure it initially with just one fast track for our submix
2352 mFastMixer = new FastMixer();
2353 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002354#ifdef STATE_QUEUE_DUMP
2355 sq->setObserverDump(&mStateQueueObserverDump);
2356 sq->setMutatorDump(&mStateQueueMutatorDump);
2357#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002358 FastMixerState *state = sq->begin();
2359 FastTrack *fastTrack = &state->mFastTracks[0];
2360 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2361 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2362 fastTrack->mVolumeProvider = NULL;
2363 fastTrack->mGeneration++;
2364 state->mFastTracksGen++;
2365 state->mTrackMask = 1;
2366 // fast mixer will use the HAL output sink
2367 state->mOutputSink = mOutputSink.get();
2368 state->mOutputSinkGen++;
2369 state->mFrameCount = mFrameCount;
2370 state->mCommand = FastMixerState::COLD_IDLE;
2371 // already done in constructor initialization list
2372 //mFastMixerFutex = 0;
2373 state->mColdFutexAddr = &mFastMixerFutex;
2374 state->mColdGen++;
2375 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002376 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002377 sq->end();
2378 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2379
2380 // start the fast mixer
2381 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002382 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002383 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002384 if (err != 0) {
2385 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002386 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002387 }
Glenn Kasten58912562012-04-03 10:45:00 -07002388
Glenn Kastenc15d6652012-05-30 14:52:57 -07002389#ifdef AUDIO_WATCHDOG
2390 // create and start the watchdog
2391 mAudioWatchdog = new AudioWatchdog();
2392 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2393 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2394 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002395 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002396 if (err != 0) {
2397 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002398 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002399 }
2400#endif
2401
Glenn Kasten58912562012-04-03 10:45:00 -07002402 } else {
2403 mFastMixer = NULL;
2404 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002405
2406 switch (kUseFastMixer) {
2407 case FastMixer_Never:
2408 case FastMixer_Dynamic:
2409 mNormalSink = mOutputSink;
2410 break;
2411 case FastMixer_Always:
2412 mNormalSink = mPipeSink;
2413 break;
2414 case FastMixer_Static:
2415 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2416 break;
2417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418}
2419
2420AudioFlinger::MixerThread::~MixerThread()
2421{
Glenn Kasten58912562012-04-03 10:45:00 -07002422 if (mFastMixer != NULL) {
2423 FastMixerStateQueue *sq = mFastMixer->sq();
2424 FastMixerState *state = sq->begin();
2425 if (state->mCommand == FastMixerState::COLD_IDLE) {
2426 int32_t old = android_atomic_inc(&mFastMixerFutex);
2427 if (old == -1) {
2428 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2429 }
2430 }
2431 state->mCommand = FastMixerState::EXIT;
2432 sq->end();
2433 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2434 mFastMixer->join();
2435 // Though the fast mixer thread has exited, it's state queue is still valid.
2436 // We'll use that extract the final state which contains one remaining fast track
2437 // corresponding to our sub-mix.
2438 state = sq->begin();
2439 ALOG_ASSERT(state->mTrackMask == 1);
2440 FastTrack *fastTrack = &state->mFastTracks[0];
2441 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2442 delete fastTrack->mBufferProvider;
2443 sq->end(false /*didModify*/);
2444 delete mFastMixer;
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002445#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002446 if (mAudioWatchdog != 0) {
2447 mAudioWatchdog->requestExit();
2448 mAudioWatchdog->requestExitAndWait();
2449 mAudioWatchdog.clear();
2450 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002451#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002452 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453 delete mAudioMixer;
2454}
2455
Glenn Kasten83efdd02012-02-24 07:21:32 -08002456class CpuStats {
2457public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002458 CpuStats();
2459 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002460#ifdef DEBUG_CPU_USAGE
2461private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002462 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2463 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2464
2465 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2466
2467 int mCpuNum; // thread's current CPU number
2468 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002469#endif
2470};
2471
Glenn Kasten190a46f2012-03-06 11:27:10 -08002472CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002473#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002474 : mCpuNum(-1), mCpukHz(-1)
2475#endif
2476{
2477}
2478
2479void CpuStats::sample(const String8 &title) {
2480#ifdef DEBUG_CPU_USAGE
2481 // get current thread's delta CPU time in wall clock ns
2482 double wcNs;
2483 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2484
2485 // record sample for wall clock statistics
2486 if (valid) {
2487 mWcStats.sample(wcNs);
2488 }
2489
2490 // get the current CPU number
2491 int cpuNum = sched_getcpu();
2492
2493 // get the current CPU frequency in kHz
2494 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2495
2496 // check if either CPU number or frequency changed
2497 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2498 mCpuNum = cpuNum;
2499 mCpukHz = cpukHz;
2500 // ignore sample for purposes of cycles
2501 valid = false;
2502 }
2503
2504 // if no change in CPU number or frequency, then record sample for cycle statistics
2505 if (valid && mCpukHz > 0) {
2506 double cycles = wcNs * cpukHz * 0.000001;
2507 mHzStats.sample(cycles);
2508 }
2509
2510 unsigned n = mWcStats.n();
2511 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002512 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002513 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002514 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2515 double perLoop = elapsed / (double) n;
2516 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002517 double perLoop1k = perLoop * 0.001;
2518 double mean = mWcStats.mean();
2519 double stddev = mWcStats.stddev();
2520 double minimum = mWcStats.minimum();
2521 double maximum = mWcStats.maximum();
2522 double meanCycles = mHzStats.mean();
2523 double stddevCycles = mHzStats.stddev();
2524 double minCycles = mHzStats.minimum();
2525 double maxCycles = mHzStats.maximum();
2526 mCpuUsage.resetElapsed();
2527 mWcStats.reset();
2528 mHzStats.reset();
2529 ALOGD("CPU usage for %s over past %.1f secs\n"
2530 " (%u mixer loops at %.1f mean ms per loop):\n"
2531 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2532 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2533 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2534 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002535 elapsed * .000000001, n, perLoop * .000001,
2536 mean * .001,
2537 stddev * .001,
2538 minimum * .001,
2539 maximum * .001,
2540 mean / perLoop100,
2541 stddev / perLoop100,
2542 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002543 maximum / perLoop100,
2544 meanCycles / perLoop1k,
2545 stddevCycles / perLoop1k,
2546 minCycles / perLoop1k,
2547 maxCycles / perLoop1k);
2548
Glenn Kasten83efdd02012-02-24 07:21:32 -08002549 }
2550 }
2551#endif
2552};
2553
Glenn Kasten37d825e2012-02-24 07:21:48 -08002554void AudioFlinger::PlaybackThread::checkSilentMode_l()
2555{
2556 if (!mMasterMute) {
2557 char value[PROPERTY_VALUE_MAX];
2558 if (property_get("ro.audio.silent", value, "0") > 0) {
2559 char *endptr;
2560 unsigned long ul = strtoul(value, &endptr, 0);
2561 if (*endptr == '\0' && ul != 0) {
2562 ALOGD("Silence is golden");
2563 // The setprop command will not allow a property to be changed after
2564 // the first time it is set, so we don't have to worry about un-muting.
2565 setMasterMute_l(true);
2566 }
2567 }
2568 }
2569}
2570
Glenn Kasten000f0e32012-03-01 17:10:56 -08002571bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572{
2573 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002574
Glenn Kasten000f0e32012-03-01 17:10:56 -08002575 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002576
2577 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002579
Glenn Kasten000f0e32012-03-01 17:10:56 -08002580 // DUPLICATING
2581 // FIXME could this be made local to while loop?
2582 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002583
Glenn Kasten66fcab92012-02-24 14:59:21 -08002584 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002585 sleepTime = idleSleepTime;
2586
Glenn Kasten9f34a362012-03-20 16:46:41 -07002587 if (mType == MIXER) {
2588 sleepTimeShift = 0;
2589 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002590
Glenn Kasten83efdd02012-02-24 07:21:32 -08002591 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002592 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593
Eric Laurentfeb0db62011-07-22 09:04:31 -07002594 acquireWakeLock();
2595
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 while (!exitPending())
2597 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002598 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002599
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002600 Vector< sp<EffectChain> > effectChains;
2601
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602 processConfigEvents();
2603
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 { // scope for mLock
2605
2606 Mutex::Autolock _l(mLock);
2607
2608 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002609 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 }
2611
Glenn Kastenfa26a852012-03-06 11:28:04 -08002612 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002613
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002615 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002616 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002618
2619 threadLoop_standby();
2620
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622 }
2623
Glenn Kasten3e074702012-02-28 18:40:35 -08002624 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 // we're about to wait, flush the binder command buffer
2626 IPCThreadState::self()->flushCommands();
2627
Glenn Kastenfa26a852012-03-06 11:28:04 -08002628 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002629
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 if (exitPending()) break;
2631
Eric Laurentfeb0db62011-07-22 09:04:31 -07002632 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002634 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002636 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002637 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638
Eric Laurentda747442012-04-25 18:53:13 -07002639 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002640 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent6090a172012-09-23 15:20:50 -07002641 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002642
Glenn Kasten37d825e2012-02-24 07:21:48 -08002643 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644
Glenn Kasten000f0e32012-03-01 17:10:56 -08002645 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002647 if (mType == MIXER) {
2648 sleepTimeShift = 0;
2649 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002650
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 continue;
2652 }
2653 }
2654
Glenn Kasten81028042012-04-30 18:15:12 -07002655 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002656 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
2658 // prevent any changes in effect chain list and in each effect chain
2659 // during mixing and effect process as the audio buffers could be deleted
2660 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002661 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002662 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663
Glenn Kastenfec279f2012-03-08 07:47:15 -08002664 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002665 threadLoop_mix();
2666 } else {
2667 threadLoop_sleepTime();
2668 }
2669
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002670 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002671 sleepTime = suspendSleepTimeUs();
Eric Laurent6090a172012-09-23 15:20:50 -07002672 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002673 }
2674
2675 // only process effects if we're going to write
2676 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002677 for (size_t i = 0; i < effectChains.size(); i ++) {
2678 effectChains[i]->process_l();
2679 }
2680 }
2681
2682 // enable changes in effect chain
2683 unlockEffectChains(effectChains);
2684
2685 // sleepTime == 0 means we must write to audio hardware
2686 if (sleepTime == 0) {
2687
2688 threadLoop_write();
2689
2690if (mType == MIXER) {
2691 // write blocked detection
2692 nsecs_t now = systemTime();
2693 nsecs_t delta = now - mLastWriteTime;
2694 if (!mStandby && delta > maxPeriod) {
2695 mNumDelayedWrites++;
2696 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002697#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002698 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002699#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002700 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2701 ns2ms(delta), mNumDelayedWrites, this);
2702 lastWarning = now;
2703 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002704 }
2705}
2706
2707 mStandby = false;
2708 } else {
2709 usleep(sleepTime);
2710 }
2711
Glenn Kasten58912562012-04-03 10:45:00 -07002712 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002713 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002714 // same lock. This will also mutate and push a new fast mixer state.
2715 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002716 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002717
Glenn Kastenfa26a852012-03-06 11:28:04 -08002718 // FIXME I don't understand the need for this here;
2719 // it was in the original code but maybe the
2720 // assignment in saveOutputTracks() makes this unnecessary?
2721 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002722
2723 // Effect chains will be actually deleted here if they were removed from
2724 // mEffectChains list during mixing or effects processing
2725 effectChains.clear();
2726
2727 // FIXME Note that the above .clear() is no longer necessary since effectChains
2728 // is now local to this block, but will keep it for now (at least until merge done).
2729 }
2730
Glenn Kasten9f34a362012-03-20 16:46:41 -07002731 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2732 if (mType == MIXER || mType == DIRECT) {
2733 // put output stream into standby mode
2734 if (!mStandby) {
2735 mOutput->stream->common.standby(&mOutput->stream->common);
2736 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002737 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002738
2739 releaseWakeLock();
2740
2741 ALOGV("Thread %p type %d exiting", this, mType);
2742 return false;
2743}
2744
Glenn Kasten58912562012-04-03 10:45:00 -07002745void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2746{
Glenn Kasten58912562012-04-03 10:45:00 -07002747 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2748}
2749
2750void AudioFlinger::MixerThread::threadLoop_write()
2751{
2752 // FIXME we should only do one push per cycle; confirm this is true
2753 // Start the fast mixer if it's not already running
2754 if (mFastMixer != NULL) {
2755 FastMixerStateQueue *sq = mFastMixer->sq();
2756 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002757 if (state->mCommand != FastMixerState::MIX_WRITE &&
2758 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002759 if (state->mCommand == FastMixerState::COLD_IDLE) {
2760 int32_t old = android_atomic_inc(&mFastMixerFutex);
2761 if (old == -1) {
2762 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2763 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002764#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002765 if (mAudioWatchdog != 0) {
2766 mAudioWatchdog->resume();
2767 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002768#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002769 }
2770 state->mCommand = FastMixerState::MIX_WRITE;
2771 sq->end();
2772 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002773 if (kUseFastMixer == FastMixer_Dynamic) {
2774 mNormalSink = mPipeSink;
2775 }
Glenn Kasten58912562012-04-03 10:45:00 -07002776 } else {
2777 sq->end(false /*didModify*/);
2778 }
2779 }
2780 PlaybackThread::threadLoop_write();
2781}
2782
Glenn Kasten000f0e32012-03-01 17:10:56 -08002783// shared by MIXER and DIRECT, overridden by DUPLICATING
2784void AudioFlinger::PlaybackThread::threadLoop_write()
2785{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002786 // FIXME rewrite to reduce number of system calls
2787 mLastWriteTime = systemTime();
2788 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002789 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002790
Eric Laurent67c0a582012-05-01 19:31:12 -07002791 // If an NBAIO sink is present, use it to write the normal mixer's submix
2792 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002793#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002794 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002795#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002796 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002797#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002798 // update the setpoint when gScreenState changes
2799 uint32_t screenState = gScreenState;
2800 if (screenState != mScreenState) {
2801 mScreenState = screenState;
2802 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2803 if (pipe != NULL) {
2804 pipe->setAvgFrames((mScreenState & 1) ?
2805 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2806 }
2807 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002808 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002809#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002810 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002811#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002812 if (framesWritten > 0) {
2813 bytesWritten = framesWritten << mBitShift;
2814 } else {
2815 bytesWritten = framesWritten;
2816 }
2817 // otherwise use the HAL / AudioStreamOut directly
2818 } else {
2819 // Direct output thread.
2820 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002821 }
2822
Eric Laurent67c0a582012-05-01 19:31:12 -07002823 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002824 mNumWrites++;
2825 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002826}
2827
Glenn Kasten58912562012-04-03 10:45:00 -07002828void AudioFlinger::MixerThread::threadLoop_standby()
2829{
2830 // Idle the fast mixer if it's currently running
2831 if (mFastMixer != NULL) {
2832 FastMixerStateQueue *sq = mFastMixer->sq();
2833 FastMixerState *state = sq->begin();
2834 if (!(state->mCommand & FastMixerState::IDLE)) {
2835 state->mCommand = FastMixerState::COLD_IDLE;
2836 state->mColdFutexAddr = &mFastMixerFutex;
2837 state->mColdGen++;
2838 mFastMixerFutex = 0;
2839 sq->end();
2840 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2841 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002842 if (kUseFastMixer == FastMixer_Dynamic) {
2843 mNormalSink = mOutputSink;
2844 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002845#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002846 if (mAudioWatchdog != 0) {
2847 mAudioWatchdog->pause();
2848 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002849#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002850 } else {
2851 sq->end(false /*didModify*/);
2852 }
2853 }
2854 PlaybackThread::threadLoop_standby();
2855}
2856
Glenn Kasten000f0e32012-03-01 17:10:56 -08002857// shared by MIXER and DIRECT, overridden by DUPLICATING
2858void AudioFlinger::PlaybackThread::threadLoop_standby()
2859{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002860 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002861 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002862}
2863
2864void AudioFlinger::MixerThread::threadLoop_mix()
2865{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002866 // obtain the presentation timestamp of the next output buffer
2867 int64_t pts;
2868 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002869
John Grossman2c3b2da2012-08-02 17:08:54 -07002870 if (mNormalSink != 0) {
2871 status = mNormalSink->getNextWriteTimestamp(&pts);
2872 } else {
2873 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002875
Glenn Kasten952eeb22012-03-06 11:30:57 -08002876 if (status != NO_ERROR) {
2877 pts = AudioBufferProvider::kInvalidPTS;
2878 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002879
Glenn Kasten952eeb22012-03-06 11:30:57 -08002880 // mix buffers...
2881 mAudioMixer->process(pts);
2882 // increase sleep time progressively when application underrun condition clears.
2883 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2884 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2885 // such that we would underrun the audio HAL.
2886 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2887 sleepTimeShift--;
2888 }
2889 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002890 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002891 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002892}
2893
2894void AudioFlinger::MixerThread::threadLoop_sleepTime()
2895{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002896 // If no tracks are ready, sleep once for the duration of an output
2897 // buffer size, then write 0s to the output
2898 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002899 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002900 sleepTime = activeSleepTime >> sleepTimeShift;
2901 if (sleepTime < kMinThreadSleepTimeUs) {
2902 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002904 // reduce sleep time in case of consecutive application underruns to avoid
2905 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2906 // duration we would end up writing less data than needed by the audio HAL if
2907 // the condition persists.
2908 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2909 sleepTimeShift++;
2910 }
2911 } else {
2912 sleepTime = idleSleepTime;
2913 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002914 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002915 memset (mMixBuffer, 0, mixBufferSize);
2916 sleepTime = 0;
Glenn Kastenb59a5022012-11-16 12:01:44 -08002917 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
Glenn Kasten8af901c2012-11-01 11:11:38 -07002918 "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002919 }
2920 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921}
2922
2923// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002924AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002925 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926{
2927
Glenn Kasten29c23c32012-01-26 13:37:52 -08002928 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002930 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 size_t mixedTracks = 0;
2932 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002933 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002934 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002935 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936
2937 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002938 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939
Eric Laurent571d49c2010-08-11 05:20:11 -07002940 if (masterMute) {
2941 masterVolume = 0;
2942 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002944 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002946 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002947 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948 masterVolume = (float)((v + (1 << 23)) >> 24);
2949 chain.clear();
2950 }
2951
Glenn Kasten288ed212012-04-25 17:52:27 -07002952 // prepare a new state to push
2953 FastMixerStateQueue *sq = NULL;
2954 FastMixerState *state = NULL;
2955 bool didModify = false;
2956 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2957 if (mFastMixer != NULL) {
2958 sq = mFastMixer->sq();
2959 state = sq->begin();
2960 }
2961
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002963 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 if (t == 0) continue;
2965
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002966 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002968
Glenn Kasten288ed212012-04-25 17:52:27 -07002969 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002970 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002971
2972 // It's theoretically possible (though unlikely) for a fast track to be created
2973 // and then removed within the same normal mix cycle. This is not a problem, as
2974 // the track never becomes active so it's fast mixer slot is never touched.
2975 // The converse, of removing an (active) track and then creating a new track
2976 // at the identical fast mixer slot within the same normal mix cycle,
2977 // is impossible because the slot isn't marked available until the end of each cycle.
2978 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002979 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2980 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002981 FastTrack *fastTrack = &state->mFastTracks[j];
2982
2983 // Determine whether the track is currently in underrun condition,
2984 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002985 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2986 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002987 uint32_t recentFull = (underruns.mBitFields.mFull -
2988 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2989 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2990 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2991 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2992 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2993 uint32_t recentUnderruns = recentPartial + recentEmpty;
2994 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002995 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002996 // or stopped which can occur when flush() is called while active
2997 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002998 track->mUnderrunCount += recentUnderruns;
2999 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003000
Glenn Kastend08f48c2012-05-01 18:14:02 -07003001 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003002 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003003 bool isActive = true;
3004 switch (track->mState) {
3005 case TrackBase::STOPPING_1:
3006 // track stays active in STOPPING_1 state until first underrun
3007 if (recentUnderruns > 0) {
3008 track->mState = TrackBase::STOPPING_2;
3009 }
3010 break;
3011 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003012 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003013 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003014 break;
3015 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003016 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003017 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003018 break;
3019 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003020 if (recentFull > 0 || recentPartial > 0) {
3021 // track has provided at least some frames recently: reset retry count
3022 track->mRetryCount = kMaxTrackRetries;
3023 }
3024 if (recentUnderruns == 0) {
3025 // no recent underruns: stay active
3026 break;
3027 }
3028 // there has recently been an underrun of some kind
3029 if (track->sharedBuffer() == 0) {
3030 // were any of the recent underruns "empty" (no frames available)?
3031 if (recentEmpty == 0) {
3032 // no, then ignore the partial underruns as they are allowed indefinitely
3033 break;
3034 }
3035 // there has recently been an "empty" underrun: decrement the retry counter
3036 if (--(track->mRetryCount) > 0) {
3037 break;
3038 }
3039 // indicate to client process that the track was disabled because of underrun;
3040 // it will then automatically call start() when data is available
Glenn Kastend12b0332012-11-05 13:38:15 -08003041 android_atomic_or(CBLK_DISABLED, &track->mCblk->flags);
Glenn Kasten09474df2012-05-10 14:48:07 -07003042 // remove from active list, but state remains ACTIVE [confusing but true]
3043 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003044 break;
3045 }
3046 // fall through
3047 case TrackBase::STOPPING_2:
3048 case TrackBase::PAUSED:
3049 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003050 case TrackBase::STOPPED:
3051 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003052 // Check for presentation complete if track is inactive
3053 // We have consumed all the buffers of this track.
3054 // This would be incomplete if we auto-paused on underrun
3055 {
3056 size_t audioHALFrames =
3057 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Glenn Kastenb59a5022012-11-16 12:01:44 -08003058 size_t framesWritten = mBytesWritten / mFrameSize;
Glenn Kasten126c9102012-10-18 15:51:31 -07003059 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003060 // track stays in active list until presentation is complete
3061 break;
3062 }
3063 }
3064 if (track->isStopping_2()) {
3065 track->mState = TrackBase::STOPPED;
3066 }
3067 if (track->isStopped()) {
3068 // Can't reset directly, as fast mixer is still polling this track
3069 // track->reset();
3070 // So instead mark this track as needing to be reset after push with ack
3071 resetMask |= 1 << i;
3072 }
3073 isActive = false;
3074 break;
3075 case TrackBase::IDLE:
3076 default:
3077 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003078 }
3079
3080 if (isActive) {
3081 // was it previously inactive?
3082 if (!(state->mTrackMask & (1 << j))) {
3083 ExtendedAudioBufferProvider *eabp = track;
3084 VolumeProvider *vp = track;
3085 fastTrack->mBufferProvider = eabp;
3086 fastTrack->mVolumeProvider = vp;
3087 fastTrack->mSampleRate = track->mSampleRate;
3088 fastTrack->mChannelMask = track->mChannelMask;
3089 fastTrack->mGeneration++;
3090 state->mTrackMask |= 1 << j;
3091 didModify = true;
3092 // no acknowledgement required for newly active tracks
3093 }
3094 // cache the combined master volume and stream type volume for fast mixer; this
3095 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3096 track->mCachedVolume = track->isMuted() ?
3097 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3098 ++fastTracks;
3099 } else {
3100 // was it previously active?
3101 if (state->mTrackMask & (1 << j)) {
3102 fastTrack->mBufferProvider = NULL;
3103 fastTrack->mGeneration++;
3104 state->mTrackMask &= ~(1 << j);
3105 didModify = true;
3106 // If any fast tracks were removed, we must wait for acknowledgement
3107 // because we're about to decrement the last sp<> on those tracks.
3108 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003109 } else {
3110 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003111 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003112 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003113 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003114 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003115 }
3116 continue;
3117 }
3118
3119 { // local variable scope to avoid goto warning
3120
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121 audio_track_cblk_t* cblk = track->cblk();
3122
3123 // The first time a track is added we wait
3124 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003125 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003126 // make sure that we have enough frames to mix one full buffer.
3127 // enforce this condition only once to enable draining the buffer in case the client
3128 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003129 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003130 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003131 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003132 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003133 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten1127d652012-11-14 08:44:39 -08003134 if (t->sampleRate() == mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003135 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003136 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003137 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003138 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003139 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003140 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003141 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3142 // the minimum track buffer size is normally twice the number of frames necessary
3143 // to fill one buffer and the resampler should not leave more than one buffer worth
3144 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003145 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003146 }
3147 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003148 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 !track->isPaused() && !track->isTerminated())
3150 {
Glenn Kasten8af901c2012-11-01 11:11:38 -07003151 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server,
3152 this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153
3154 mixedTracks++;
3155
3156 // track->mainBuffer() != mMixBuffer means there is an effect chain
3157 // connected to the track
3158 chain.clear();
3159 if (track->mainBuffer() != mMixBuffer) {
3160 chain = getEffectChain_l(track->sessionId());
3161 // Delegate volume control to effect in track effect chain if needed
3162 if (chain != 0) {
3163 tracksWithEffect++;
3164 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07003165 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3166 "session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003167 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 }
3169 }
3170
3171
3172 int param = AudioMixer::VOLUME;
3173 if (track->mFillingUpStatus == Track::FS_FILLED) {
3174 // no ramp for the first volume setting
3175 track->mFillingUpStatus = Track::FS_ACTIVE;
3176 if (track->mState == TrackBase::RESUMING) {
3177 track->mState = TrackBase::ACTIVE;
3178 param = AudioMixer::RAMP_VOLUME;
3179 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003180 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 } else if (cblk->server != 0) {
3182 // If the track is stopped before the first frame was mixed,
3183 // do not apply ramp
3184 param = AudioMixer::RAMP_VOLUME;
3185 }
3186
3187 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003188 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003189 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003190 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003191 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 if (track->isPausing()) {
3193 track->setPaused();
3194 }
3195 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003196
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003198 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003200 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003201 vl = vlr & 0xFFFF;
3202 vr = vlr >> 16;
3203 // track volumes come from shared memory, so can't be trusted and must be clamped
3204 if (vl > MAX_GAIN_INT) {
3205 ALOGV("Track left volume out of range: %04X", vl);
3206 vl = MAX_GAIN_INT;
3207 }
3208 if (vr > MAX_GAIN_INT) {
3209 ALOGV("Track right volume out of range: %04X", vr);
3210 vr = MAX_GAIN_INT;
3211 }
3212 // now apply the master volume and stream type volume
3213 vl = (uint32_t)(v * vl) << 12;
3214 vr = (uint32_t)(v * vr) << 12;
3215 // assuming master volume and stream type volume each go up to 1.0,
3216 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217
Glenn Kasten05632a52012-01-03 14:22:33 -08003218 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3219 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003220 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003221 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003222 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003223 }
3224 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003226 // Delegate volume control to effect in track effect chain if needed
3227 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3228 // Do not ramp volume if volume is controlled by effect
3229 param = AudioMixer::VOLUME;
3230 track->mHasVolumeController = true;
3231 } else {
3232 // force no volume ramp when volume controller was just disabled or removed
3233 // from effect chain to avoid volume spike
3234 if (track->mHasVolumeController) {
3235 param = AudioMixer::VOLUME;
3236 }
3237 track->mHasVolumeController = false;
3238 }
3239
3240 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003241 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003242 vl = (vl + (1 << 11)) >> 12;
3243 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3244 vr = (vr + (1 << 11)) >> 12;
3245 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003246
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003247 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 -07003248
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003250 mAudioMixer->setBufferProvider(name, track);
3251 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003253 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3254 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3255 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003257 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 AudioMixer::TRACK,
3259 AudioMixer::FORMAT, (void *)track->format());
3260 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003261 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003263 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003265 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 AudioMixer::RESAMPLE,
3267 AudioMixer::SAMPLE_RATE,
3268 (void *)(cblk->sampleRate));
3269 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003270 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 AudioMixer::TRACK,
3272 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3273 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003274 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 AudioMixer::TRACK,
3276 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3277
3278 // reset retry count
3279 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003280
Eric Laurent27741442012-01-17 19:20:12 -08003281 // If one track is ready, set the mixer ready if:
3282 // - the mixer was not ready during previous round OR
3283 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003284 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003285 mixerStatus != MIXER_TRACKS_ENABLED) {
3286 mixerStatus = MIXER_TRACKS_READY;
3287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003289 // clear effect chain input buffer if an active track underruns to avoid sending
3290 // previous audio buffer again to effects
3291 chain = getEffectChain_l(track->sessionId());
3292 if (chain != 0) {
3293 chain->clearInputBuffer();
3294 }
3295
Glenn Kasten8af901c2012-11-01 11:11:38 -07003296 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user,
3297 cblk->server, this);
Glenn Kasten52013e72012-09-26 08:34:10 -07003298 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003299 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 // We have consumed all the buffers of this track.
3301 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003302 // TODO: use actual buffer filling status instead of latency when available from
3303 // audio HAL
Jean-Michel Trivi115b87e2012-10-16 10:29:01 -07003304 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Glenn Kastenb59a5022012-11-16 12:01:44 -08003305 size_t framesWritten = mBytesWritten / mFrameSize;
Glenn Kasten126c9102012-10-18 15:51:31 -07003306 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003307 if (track->isStopped()) {
3308 track->reset();
3309 }
Eric Laurenta011e352012-03-29 15:51:43 -07003310 tracksToRemove->add(track);
3311 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003313 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 // No buffers for this track. Give it a few chances to
3315 // fill a buffer, then remove it from active list.
Glenn Kasten52013e72012-09-26 08:34:10 -07003316 if (--(track->mRetryCount) <= 0) {
3317 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003319 // indicate to client process that the track was disabled because of underrun;
3320 // it will then automatically call start() when data is available
Glenn Kastend12b0332012-11-05 13:38:15 -08003321 android_atomic_or(CBLK_DISABLED, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003322 // If one track is not ready, mark the mixer also not ready if:
3323 // - the mixer was ready during previous round OR
3324 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003325 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003326 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 mixerStatus = MIXER_TRACKS_ENABLED;
3328 }
3329 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003330 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 }
Glenn Kasten58912562012-04-03 10:45:00 -07003332
3333 } // local variable scope to avoid goto warning
3334track_is_ready: ;
3335
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 }
3337
Glenn Kasten288ed212012-04-25 17:52:27 -07003338 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003339 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003340 if (didModify) {
3341 state->mFastTracksGen++;
3342 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3343 if (kUseFastMixer == FastMixer_Dynamic &&
3344 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3345 state->mCommand = FastMixerState::COLD_IDLE;
3346 state->mColdFutexAddr = &mFastMixerFutex;
3347 state->mColdGen++;
3348 mFastMixerFutex = 0;
3349 if (kUseFastMixer == FastMixer_Dynamic) {
3350 mNormalSink = mOutputSink;
3351 }
3352 // If we go into cold idle, need to wait for acknowledgement
3353 // so that fast mixer stops doing I/O.
3354 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003355 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003356 }
3357 sq->end();
3358 }
3359 if (sq != NULL) {
3360 sq->end(didModify);
3361 sq->push(block);
3362 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003363#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003364 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3365 mAudioWatchdog->pause();
3366 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003367#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003368
3369 // Now perform the deferred reset on fast tracks that have stopped
3370 while (resetMask != 0) {
3371 size_t i = __builtin_ctz(resetMask);
3372 ALOG_ASSERT(i < count);
3373 resetMask &= ~(1 << i);
3374 sp<Track> t = mActiveTracks[i].promote();
3375 if (t == 0) continue;
3376 Track* track = t.get();
3377 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3378 track->reset();
3379 }
Glenn Kasten58912562012-04-03 10:45:00 -07003380
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 // remove all the tracks that need to be...
3382 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003383 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 for (size_t i=0 ; i<count ; i++) {
3385 const sp<Track>& track = tracksToRemove->itemAt(i);
3386 mActiveTracks.remove(track);
3387 if (track->mainBuffer() != mMixBuffer) {
3388 chain = getEffectChain_l(track->sessionId());
3389 if (chain != 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07003390 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3391 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003392 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 }
3394 }
3395 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003396 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 }
3398 }
3399 }
3400
3401 // mix buffer must be cleared if all tracks are connected to an
3402 // effect chain as in this case the mixer will not write to
3403 // mix buffer and track effects will accumulate into it
Glenn Kasten8af901c2012-11-01 11:11:38 -07003404 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3405 (mixedTracks == 0 && fastTracks > 0)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003406 // FIXME as a performance optimization, should remember previous zero status
3407 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408 }
3409
Glenn Kasten58912562012-04-03 10:45:00 -07003410 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003411 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003412 if (fastTracks > 0) {
3413 mixerStatus = MIXER_TRACKS_READY;
3414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 return mixerStatus;
3416}
3417
Glenn Kasten66fcab92012-02-24 14:59:21 -08003418/*
3419The derived values that are cached:
3420 - mixBufferSize from frame count * frame size
3421 - activeSleepTime from activeSleepTimeUs()
3422 - idleSleepTime from idleSleepTimeUs()
3423 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3424 - maxPeriod from frame count and sample rate (MIXER only)
3425
3426The parameters that affect these derived values are:
3427 - frame count
3428 - frame size
3429 - sample rate
3430 - device type: A2DP or not
3431 - device latency
3432 - format: PCM or not
3433 - active sleep time
3434 - idle sleep time
3435*/
3436
3437void AudioFlinger::PlaybackThread::cacheParameters_l()
3438{
Glenn Kasten58912562012-04-03 10:45:00 -07003439 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003440 activeSleepTime = activeSleepTimeUs();
3441 idleSleepTime = idleSleepTimeUs();
3442}
3443
Eric Laurent22167852012-06-20 12:26:32 -07003444void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445{
Steve Block3856b092011-10-20 11:56:00 +01003446 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003447 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003449
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450 size_t size = mTracks.size();
3451 for (size_t i = 0; i < size; i++) {
3452 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003453 if (t->streamType() == streamType) {
Glenn Kastend12b0332012-11-05 13:38:15 -08003454 android_atomic_or(CBLK_INVALID, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 }
3457 }
3458}
3459
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003461int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462{
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003463 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464}
3465
3466// deleteTrackName_l() must be called with ThreadBase::mLock held
3467void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3468{
Steve Block3856b092011-10-20 11:56:00 +01003469 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 mAudioMixer->deleteTrackName(name);
3471}
3472
3473// checkForNewParameters_l() must be called with ThreadBase::mLock held
3474bool AudioFlinger::MixerThread::checkForNewParameters_l()
3475{
Glenn Kasten58912562012-04-03 10:45:00 -07003476 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3477 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 bool reconfig = false;
3479
3480 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003481
3482 if (mFastMixer != NULL) {
3483 FastMixerStateQueue *sq = mFastMixer->sq();
3484 FastMixerState *state = sq->begin();
3485 if (!(state->mCommand & FastMixerState::IDLE)) {
3486 previousCommand = state->mCommand;
3487 state->mCommand = FastMixerState::HOT_IDLE;
3488 sq->end();
3489 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3490 } else {
3491 sq->end(false /*didModify*/);
3492 }
3493 }
3494
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 status_t status = NO_ERROR;
3496 String8 keyValuePair = mNewParameters[0];
3497 AudioParameter param = AudioParameter(keyValuePair);
3498 int value;
3499
3500 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3501 reconfig = true;
3502 }
3503 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003504 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 status = BAD_VALUE;
3506 } else {
3507 reconfig = true;
3508 }
3509 }
3510 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003511 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512 status = BAD_VALUE;
3513 } else {
3514 reconfig = true;
3515 }
3516 }
3517 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3518 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003519 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 // if frame count is changed after track creation
3521 if (!mTracks.isEmpty()) {
3522 status = INVALID_OPERATION;
3523 } else {
3524 reconfig = true;
3525 }
3526 }
3527 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003528#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003529 // when changing the audio output device, call addBatteryData to notify
3530 // the change
Eric Laurent88959252012-08-28 14:26:53 -07003531 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003532 uint32_t params = 0;
3533 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003534 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003535 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3536 }
3537
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003538 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003539 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003540 // check if any other device (except speaker) is on
3541 if (value & deviceWithoutSpeaker ) {
3542 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3543 }
3544
3545 if (params != 0) {
3546 addBatteryData(params);
3547 }
3548 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003549#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003550
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 // forward device change to effects that have requested to be
3552 // aware of attached audio device.
Eric Laurent88959252012-08-28 14:26:53 -07003553 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent88959252012-08-28 14:26:53 -07003555 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 }
3557 }
3558
3559 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003560 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003561 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003563 mOutput->stream->common.standby(&mOutput->stream->common);
3564 mStandby = true;
3565 mBytesWritten = 0;
3566 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003567 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 }
3569 if (status == NO_ERROR && reconfig) {
3570 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003571 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3572 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003574 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003576 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 if (name < 0) break;
3578 mTracks[i]->mName = name;
3579 // limit track sample rate to 2 x new output sample rate
3580 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3581 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3582 }
3583 }
Eric Laurentef6be0b2012-09-13 11:18:23 -07003584 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 }
3586 }
3587
3588 mNewParameters.removeAt(0);
3589
3590 mParamStatus = status;
3591 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003592 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3593 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003594 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 }
Glenn Kasten58912562012-04-03 10:45:00 -07003596
3597 if (!(previousCommand & FastMixerState::IDLE)) {
3598 ALOG_ASSERT(mFastMixer != NULL);
3599 FastMixerStateQueue *sq = mFastMixer->sq();
3600 FastMixerState *state = sq->begin();
3601 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3602 state->mCommand = previousCommand;
3603 sq->end();
3604 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3605 }
3606
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 return reconfig;
3608}
3609
Glenn Kasten8c327342012-09-30 12:29:28 -07003610void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611{
Glenn Kasten8c327342012-09-30 12:29:28 -07003612 NBAIO_Source *teeSource = source.get();
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003613 if (teeSource != NULL) {
Glenn Kasten8c327342012-09-30 12:29:28 -07003614 char teeTime[16];
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003615 struct timeval tv;
3616 gettimeofday(&tv, NULL);
3617 struct tm tm;
3618 localtime_r(&tv.tv_sec, &tm);
Glenn Kasten8c327342012-09-30 12:29:28 -07003619 strftime(teeTime, sizeof(teeTime), "%T", &tm);
3620 char teePath[64];
3621 sprintf(teePath, "/data/misc/media/%s_%d.wav", teeTime, id);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003622 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3623 if (teeFd >= 0) {
3624 char wavHeader[44];
3625 memcpy(wavHeader,
3626 "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",
3627 sizeof(wavHeader));
3628 NBAIO_Format format = teeSource->format();
3629 unsigned channelCount = Format_channelCount(format);
3630 ALOG_ASSERT(channelCount <= FCC_2);
Glenn Kasten1127d652012-11-14 08:44:39 -08003631 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003632 wavHeader[22] = channelCount; // number of channels
3633 wavHeader[24] = sampleRate; // sample rate
3634 wavHeader[25] = sampleRate >> 8;
3635 wavHeader[32] = channelCount * 2; // block alignment
3636 write(teeFd, wavHeader, sizeof(wavHeader));
3637 size_t total = 0;
3638 bool firstRead = true;
3639 for (;;) {
3640#define TEE_SINK_READ 1024
3641 short buffer[TEE_SINK_READ * FCC_2];
3642 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003643 ssize_t actual = teeSource->read(buffer, count,
3644 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003645 bool wasFirstRead = firstRead;
3646 firstRead = false;
3647 if (actual <= 0) {
3648 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3649 continue;
3650 }
3651 break;
3652 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003653 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003654 write(teeFd, buffer, actual * channelCount * sizeof(short));
3655 total += actual;
3656 }
3657 lseek(teeFd, (off_t) 4, SEEK_SET);
3658 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3659 write(teeFd, &temp, sizeof(temp));
3660 lseek(teeFd, (off_t) 40, SEEK_SET);
3661 temp = total * channelCount * sizeof(short);
3662 write(teeFd, &temp, sizeof(temp));
3663 close(teeFd);
3664 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3665 } else {
3666 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3667 }
3668 }
Glenn Kasten8c327342012-09-30 12:29:28 -07003669}
3670
3671void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3672{
3673 const size_t SIZE = 256;
3674 char buffer[SIZE];
3675 String8 result;
3676
3677 PlaybackThread::dumpInternals(fd, args);
3678
3679 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3680 result.append(buffer);
3681 write(fd, result.string(), result.size());
3682
3683 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3684 FastMixerDumpState copy = mFastMixerDumpState;
3685 copy.dump(fd);
3686
3687#ifdef STATE_QUEUE_DUMP
3688 // Similar for state queue
3689 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3690 observerCopy.dump(fd);
3691 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3692 mutatorCopy.dump(fd);
3693#endif
3694
3695 // Write the tee output to a .wav file
3696 dumpTee(fd, mTeeSource, mId);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003697
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003698#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003699 if (mAudioWatchdog != 0) {
3700 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3701 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3702 wdCopy.dump(fd);
3703 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003704#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705}
3706
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003707uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708{
Glenn Kasten58912562012-04-03 10:45:00 -07003709 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710}
3711
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003712uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003713{
Glenn Kasten58912562012-04-03 10:45:00 -07003714 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003715}
3716
Glenn Kasten66fcab92012-02-24 14:59:21 -08003717void AudioFlinger::MixerThread::cacheParameters_l()
3718{
3719 PlaybackThread::cacheParameters_l();
3720
3721 // FIXME: Relaxed timing because of a certain device that can't meet latency
3722 // Should be reduced to 2x after the vendor fixes the driver issue
3723 // increase threshold again due to low power audio mode. The way this warning
3724 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003725 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003726}
3727
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003729AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003730 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003731 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003732 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003733{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734}
3735
3736AudioFlinger::DirectOutputThread::~DirectOutputThread()
3737{
3738}
3739
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003740AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3741 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003742)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003744 sp<Track> trackToRemove;
3745
Glenn Kastenfec279f2012-03-08 07:47:15 -08003746 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747
Glenn Kasten952eeb22012-03-06 11:30:57 -08003748 // find out which tracks need to be processed
3749 if (mActiveTracks.size() != 0) {
3750 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003751 // The track died recently
3752 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753
Glenn Kasten952eeb22012-03-06 11:30:57 -08003754 Track* const track = t.get();
3755 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003756
Glenn Kasten952eeb22012-03-06 11:30:57 -08003757 // The first time a track is added we wait
3758 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003759 uint32_t minFrames;
3760 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3761 minFrames = mNormalFrameCount;
3762 } else {
3763 minFrames = 1;
3764 }
3765 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003766 !track->isPaused() && !track->isTerminated())
3767 {
Glenn Kastencbe4b362012-10-18 15:51:03 -07003768 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769
Glenn Kasten952eeb22012-03-06 11:30:57 -08003770 if (track->mFillingUpStatus == Track::FS_FILLED) {
3771 track->mFillingUpStatus = Track::FS_ACTIVE;
3772 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003773 if (track->mState == TrackBase::RESUMING) {
3774 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003776 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003777
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 // compute volume for this track
3779 float left, right;
3780 if (track->isMuted() || mMasterMute || track->isPausing() ||
3781 mStreamTypes[track->streamType()].mute) {
3782 left = right = 0;
3783 if (track->isPausing()) {
3784 track->setPaused();
3785 }
3786 } else {
3787 float typeVolume = mStreamTypes[track->streamType()].volume;
3788 float v = mMasterVolume * typeVolume;
3789 uint32_t vlr = cblk->getVolumeLR();
3790 float v_clamped = v * (vlr & 0xFFFF);
3791 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3792 left = v_clamped/MAX_GAIN;
3793 v_clamped = v * (vlr >> 16);
3794 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3795 right = v_clamped/MAX_GAIN;
3796 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 if (left != mLeftVolFloat || right != mRightVolFloat) {
3799 mLeftVolFloat = left;
3800 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801
Glenn Kasten952eeb22012-03-06 11:30:57 -08003802 // Convert volumes from float to 8.24
3803 uint32_t vl = (uint32_t)(left * (1 << 24));
3804 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805
Glenn Kasten952eeb22012-03-06 11:30:57 -08003806 // Delegate volume control to effect in track effect chain if needed
3807 // only one effect chain can be present on DirectOutputThread, so if
3808 // there is one, the track is connected to it
3809 if (!mEffectChains.isEmpty()) {
3810 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003811 mEffectChains[0]->setVolume_l(&vl, &vr);
3812 left = (float)vl / (1 << 24);
3813 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003814 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003815 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003816 }
3817
3818 // reset retry count
3819 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003820 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003821 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003822 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003823 // clear effect chain input buffer if an active track underruns to avoid sending
3824 // previous audio buffer again to effects
3825 if (!mEffectChains.isEmpty()) {
3826 mEffectChains[0]->clearInputBuffer();
3827 }
3828
Glenn Kastencbe4b362012-10-18 15:51:03 -07003829 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten52013e72012-09-26 08:34:10 -07003830 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003831 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003832 // We have consumed all the buffers of this track.
3833 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003834 // TODO: implement behavior for compressed audio
Jean-Michel Trivi115b87e2012-10-16 10:29:01 -07003835 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Glenn Kastenb59a5022012-11-16 12:01:44 -08003836 size_t framesWritten = mBytesWritten / mFrameSize;
Glenn Kasten126c9102012-10-18 15:51:31 -07003837 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003838 if (track->isStopped()) {
3839 track->reset();
3840 }
Eric Laurenta011e352012-03-29 15:51:43 -07003841 trackToRemove = track;
3842 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003843 } else {
3844 // No buffers for this track. Give it a few chances to
3845 // fill a buffer, then remove it from active list.
Glenn Kasten52013e72012-09-26 08:34:10 -07003846 if (--(track->mRetryCount) <= 0) {
3847 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003848 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003849 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003850 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003851 }
3852 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003853 }
3854 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003855
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003856 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003857 // remove all the tracks that need to be...
3858 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003859 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003860 mActiveTracks.remove(trackToRemove);
3861 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003862 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003863 trackToRemove->sessionId());
3864 mEffectChains[0]->decActiveTrackCnt();
3865 }
3866 if (trackToRemove->isTerminated()) {
3867 removeTrack_l(trackToRemove);
3868 }
3869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870
Glenn Kastenfec279f2012-03-08 07:47:15 -08003871 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003872}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003873
Glenn Kasten000f0e32012-03-01 17:10:56 -08003874void AudioFlinger::DirectOutputThread::threadLoop_mix()
3875{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003876 AudioBufferProvider::Buffer buffer;
3877 size_t frameCount = mFrameCount;
3878 int8_t *curBuf = (int8_t *)mMixBuffer;
3879 // output audio to hardware
3880 while (frameCount) {
3881 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003882 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003883 if (CC_UNLIKELY(buffer.raw == NULL)) {
3884 memset(curBuf, 0, frameCount * mFrameSize);
3885 break;
3886 }
3887 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3888 frameCount -= buffer.frameCount;
3889 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003890 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003891 }
3892 sleepTime = 0;
3893 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003894 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003895
Glenn Kasten000f0e32012-03-01 17:10:56 -08003896}
3897
3898void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3899{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003900 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003901 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003902 sleepTime = activeSleepTime;
3903 } else {
3904 sleepTime = idleSleepTime;
3905 }
3906 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003907 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003908 sleepTime = 0;
3909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910}
3911
3912// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003913int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3914 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915{
3916 return 0;
3917}
3918
3919// deleteTrackName_l() must be called with ThreadBase::mLock held
3920void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3921{
3922}
3923
3924// checkForNewParameters_l() must be called with ThreadBase::mLock held
3925bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3926{
3927 bool reconfig = false;
3928
3929 while (!mNewParameters.isEmpty()) {
3930 status_t status = NO_ERROR;
3931 String8 keyValuePair = mNewParameters[0];
3932 AudioParameter param = AudioParameter(keyValuePair);
3933 int value;
3934
3935 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3936 // do not accept frame count changes if tracks are open as the track buffer
3937 // size depends on frame count and correct behavior would not be garantied
3938 // if frame count is changed after track creation
3939 if (!mTracks.isEmpty()) {
3940 status = INVALID_OPERATION;
3941 } else {
3942 reconfig = true;
3943 }
3944 }
3945 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003946 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003947 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003949 mOutput->stream->common.standby(&mOutput->stream->common);
3950 mStandby = true;
3951 mBytesWritten = 0;
3952 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003953 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954 }
3955 if (status == NO_ERROR && reconfig) {
3956 readOutputParameters();
Eric Laurentef6be0b2012-09-13 11:18:23 -07003957 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958 }
3959 }
3960
3961 mNewParameters.removeAt(0);
3962
3963 mParamStatus = status;
3964 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003965 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3966 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003967 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968 }
3969 return reconfig;
3970}
3971
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003972uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003973{
3974 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003975 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003976 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 } else {
3978 time = 10000;
3979 }
3980 return time;
3981}
3982
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003983uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984{
3985 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003986 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003987 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 } else {
3989 time = 10000;
3990 }
3991 return time;
3992}
3993
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003994uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003995{
3996 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003997 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003998 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3999 } else {
4000 time = 10000;
4001 }
4002 return time;
4003}
4004
Glenn Kasten66fcab92012-02-24 14:59:21 -08004005void AudioFlinger::DirectOutputThread::cacheParameters_l()
4006{
4007 PlaybackThread::cacheParameters_l();
4008
4009 // use shorter standby delay as on normal output to release
4010 // hardware resources as soon as possible
4011 standbyDelay = microseconds(activeSleepTime*2);
4012}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004013
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014// ----------------------------------------------------------------------------
4015
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004016AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004017 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten8af901c2012-11-01 11:11:38 -07004018 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4019 DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004020 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022 addOutputTrack(mainThread);
4023}
4024
4025AudioFlinger::DuplicatingThread::~DuplicatingThread()
4026{
4027 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4028 mOutputTracks[i]->destroy();
4029 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030}
4031
Glenn Kasten000f0e32012-03-01 17:10:56 -08004032void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004034 // mix buffers...
4035 if (outputsReady(outputTracks)) {
4036 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4037 } else {
4038 memset(mMixBuffer, 0, mixBufferSize);
4039 }
4040 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004041 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004042 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004043}
4044
4045void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4046{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004047 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004048 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004049 sleepTime = activeSleepTime;
4050 } else {
4051 sleepTime = idleSleepTime;
4052 }
4053 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004054 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4055 writeFrames = mNormalFrameCount;
4056 memset(mMixBuffer, 0, mixBufferSize);
4057 } else {
4058 // flush remaining overflow buffers in output tracks
4059 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004060 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004061 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004062 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004063}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064
Glenn Kasten000f0e32012-03-01 17:10:56 -08004065void AudioFlinger::DuplicatingThread::threadLoop_write()
4066{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004067 for (size_t i = 0; i < outputTracks.size(); i++) {
4068 outputTracks[i]->write(mMixBuffer, writeFrames);
4069 }
4070 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004071}
Glenn Kasten688a6402012-02-29 07:57:06 -08004072
Glenn Kasten000f0e32012-03-01 17:10:56 -08004073void AudioFlinger::DuplicatingThread::threadLoop_standby()
4074{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004075 // DuplicatingThread implements standby by stopping all tracks
4076 for (size_t i = 0; i < outputTracks.size(); i++) {
4077 outputTracks[i]->stop();
4078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079}
4080
Glenn Kastenfa26a852012-03-06 11:28:04 -08004081void AudioFlinger::DuplicatingThread::saveOutputTracks()
4082{
4083 outputTracks = mOutputTracks;
4084}
4085
4086void AudioFlinger::DuplicatingThread::clearOutputTracks()
4087{
4088 outputTracks.clear();
4089}
4090
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4092{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004093 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004094 // FIXME explain this formula
Glenn Kasten7da35f22012-11-14 12:54:39 -08004095 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004096 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 this,
4098 mSampleRate,
4099 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004100 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 frameCount);
4102 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004103 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004105 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004106 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107 }
4108}
4109
4110void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4111{
4112 Mutex::Autolock _l(mLock);
4113 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004114 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 mOutputTracks[i]->destroy();
4116 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004117 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 return;
4119 }
4120 }
Steve Block3856b092011-10-20 11:56:00 +01004121 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122}
4123
Glenn Kasten438b0362012-03-06 11:24:48 -08004124// caller must hold mLock
4125void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126{
4127 mWaitTimeMs = UINT_MAX;
4128 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4129 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004130 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4132 if (waitTimeMs < mWaitTimeMs) {
4133 mWaitTimeMs = waitTimeMs;
4134 }
4135 }
4136 }
4137}
4138
4139
Glenn Kasten8af901c2012-11-01 11:11:38 -07004140bool AudioFlinger::DuplicatingThread::outputsReady(
4141 const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142{
4143 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004144 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 if (thread == 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07004146 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4147 outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 return false;
4149 }
4150 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004151 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07004153 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4154 thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 return false;
4156 }
4157 }
4158 return true;
4159}
4160
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004161uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162{
4163 return (mWaitTimeMs * 1000) / 2;
4164}
4165
Glenn Kasten66fcab92012-02-24 14:59:21 -08004166void AudioFlinger::DuplicatingThread::cacheParameters_l()
4167{
4168 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4169 updateWaitTime_l();
4170
4171 MixerThread::cacheParameters_l();
4172}
4173
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174// ----------------------------------------------------------------------------
4175
4176// TrackBase constructor must be called with AudioFlinger::mLock held
4177AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004178 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 const sp<Client>& client,
4180 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004181 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004182 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004183 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 const sp<IMemory>& sharedBuffer,
4185 int sessionId)
4186 : RefBase(),
4187 mThread(thread),
4188 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004189 mCblk(NULL),
4190 // mBuffer
4191 // mBufferEnd
Glenn Kastene2a05862012-11-13 09:58:55 -08004192 mStepCount(0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004194 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 mFormat(format),
Glenn Kasten520a9af2012-06-21 12:56:37 -07004196 mChannelMask(channelMask),
4197 mChannelCount(popcount(channelMask)),
4198 mFrameSize(audio_is_linear_pcm(format) ?
4199 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
Glenn Kastend7101432012-11-14 13:42:25 -08004200 mFrameCount(frameCount),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004201 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 mSessionId(sessionId)
4203{
Glenn Kastenac657262012-11-05 13:39:09 -08004204 // client == 0 implies sharedBuffer == 0
4205 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
4206
Glenn Kasten8af901c2012-11-01 11:11:38 -07004207 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
4208 sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209
Steve Blockb8a80522011-12-20 16:23:08 +00004210 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004211 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten520a9af2012-06-21 12:56:37 -07004212 size_t bufferSize = frameCount * mFrameSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004213 if (sharedBuffer == 0) {
4214 size += bufferSize;
4215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216
Glenn Kastenac657262012-11-05 13:39:09 -08004217 if (client != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218 mCblkMemory = client->heap()->allocate(size);
4219 if (mCblkMemory != 0) {
4220 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastenac657262012-11-05 13:39:09 -08004221 // can't assume mCblk != NULL
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004223 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224 client->heap()->dump("AudioTrack");
4225 return;
4226 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004227 } else {
4228 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenac657262012-11-05 13:39:09 -08004229 // assume mCblk != NULL
4230 }
4231
4232 // construct the shared structure in-place.
4233 if (mCblk != NULL) {
Glenn Kastenea7939a2012-03-14 12:56:26 -07004234 new(mCblk) audio_track_cblk_t();
4235 // clear all buffers
Glenn Kastend7101432012-11-14 13:42:25 -08004236 mCblk->frameCount_ = frameCount;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004237 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004238// uncomment the following lines to quickly test 32-bit wraparound
Glenn Kastenac657262012-11-05 13:39:09 -08004239// mCblk->user = 0xffff0000;
4240// mCblk->server = 0xffff0000;
4241// mCblk->userBase = 0xffff0000;
4242// mCblk->serverBase = 0xffff0000;
Glenn Kastenac657262012-11-05 13:39:09 -08004243 if (sharedBuffer == 0) {
4244 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
Glenn Kasten520a9af2012-06-21 12:56:37 -07004245 memset(mBuffer, 0, bufferSize);
Glenn Kastenac657262012-11-05 13:39:09 -08004246 // Force underrun condition to avoid false underrun callback until first data is
4247 // written to buffer (other flags are cleared)
4248 mCblk->flags = CBLK_UNDERRUN;
4249 } else {
4250 mBuffer = sharedBuffer->pointer();
4251 }
Glenn Kastenea7939a2012-03-14 12:56:26 -07004252 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254}
4255
4256AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4257{
Glenn Kastena0d68332012-01-27 16:47:15 -08004258 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004259 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004261 } else {
4262 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 }
4264 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004265 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004266 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004267 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004269 // If the client's reference count drops to zero, the associated destructor
4270 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4271 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 mClient.clear();
4273 }
4274}
4275
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004276// AudioBufferProvider interface
4277// getNextBuffer() = 0;
4278// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4280{
Glenn Kastene0feee32011-12-13 11:53:26 -08004281 buffer->raw = NULL;
Glenn Kastene2a05862012-11-13 09:58:55 -08004282 mStepCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004283 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004284 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 buffer->frameCount = 0;
4286}
4287
4288bool AudioFlinger::ThreadBase::TrackBase::step() {
4289 bool result;
4290 audio_track_cblk_t* cblk = this->cblk();
4291
Glenn Kastend7101432012-11-14 13:42:25 -08004292 result = cblk->stepServer(mStepCount, mFrameCount, isOut());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004294 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004295 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 }
4297 return result;
4298}
4299
4300void AudioFlinger::ThreadBase::TrackBase::reset() {
4301 audio_track_cblk_t* cblk = this->cblk();
4302
4303 cblk->user = 0;
4304 cblk->server = 0;
4305 cblk->userBase = 0;
4306 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004307 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004308 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309}
4310
Glenn Kasten1127d652012-11-14 08:44:39 -08004311uint32_t AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4312 return mCblk->sampleRate;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313}
4314
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4316 audio_track_cblk_t* cblk = this->cblk();
Glenn Kasten520a9af2012-06-21 12:56:37 -07004317 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase) * mFrameSize;
4318 int8_t *bufferEnd = bufferStart + frames * mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319
4320 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004321 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4322 "TrackBase::getBuffer buffer out of range:\n"
4323 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
Glenn Kasten520a9af2012-06-21 12:56:37 -07004324 " server %u, serverBase %u, user %u, userBase %u, frameSize %u",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Glenn Kasten520a9af2012-06-21 12:56:37 -07004326 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327
4328 return bufferStart;
4329}
4330
Eric Laurenta011e352012-03-29 15:51:43 -07004331status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4332{
4333 mSyncEvents.add(event);
4334 return NO_ERROR;
4335}
4336
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337// ----------------------------------------------------------------------------
4338
4339// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4340AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004341 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004343 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004345 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004346 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004347 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004349 int sessionId,
4350 IAudioFlinger::track_flags_t flags)
Glenn Kasten8af901c2012-11-01 11:11:38 -07004351 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
4352 sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004353 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004354 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004355 // mRetryCount initialized later when needed
4356 mSharedBuffer(sharedBuffer),
4357 mStreamType(streamType),
4358 mName(-1), // see note below
4359 mMainBuffer(thread->mixBuffer()),
4360 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004361 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004362 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004363 mFlags(flags),
4364 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004365 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004366 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004367{
4368 if (mCblk != NULL) {
Glenn Kasten893a0542012-05-30 10:32:06 -07004369 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivicff71372012-09-10 18:58:27 -07004370 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004371 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004372 if (mName < 0) {
4373 ALOGE("no more track names available");
4374 return;
4375 }
4376 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004377 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten58912562012-04-03 10:45:00 -07004378 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4379 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004380 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004381 // FIXME This is too eager. We allocate a fast track index before the
4382 // fast track becomes active. Since fast tracks are a scarce resource,
4383 // this means we are potentially denying other more important fast tracks from
4384 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004385 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004386 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004387 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004388 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004389 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07004392 ALOGV("Track constructor name %d, calling pid %d", mName,
4393 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394}
4395
4396AudioFlinger::PlaybackThread::Track::~Track()
4397{
Steve Block3856b092011-10-20 11:56:00 +01004398 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399}
4400
4401void AudioFlinger::PlaybackThread::Track::destroy()
4402{
4403 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4404 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004405 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004406 // we must acquire a strong reference on this Track before locking mLock
4407 // here so that the destructor is called only when exiting this function.
4408 // On the other hand, as long as Track::destroy() is only called by
4409 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4410 // this Track with its member mTrack.
4411 sp<Track> keep(this);
4412 { // scope for mLock
4413 sp<ThreadBase> thread = mThread.promote();
4414 if (thread != 0) {
4415 if (!isOutputTrack()) {
4416 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004417 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004418
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004419#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004420 // to track the speaker usage
4421 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004422#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
4424 AudioSystem::releaseOutput(thread->id());
4425 }
4426 Mutex::Autolock _l(thread->mLock);
4427 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4428 playbackThread->destroyTrack_l(this);
4429 }
4430 }
4431}
4432
Glenn Kasten288ed212012-04-25 17:52:27 -07004433/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4434{
Glenn Kastene2a05862012-11-13 09:58:55 -08004435 result.append(" Name Client Type Fmt Chn mask Session StpCnt fCount S M F SRate "
Glenn Kasten8af901c2012-11-01 11:11:38 -07004436 "L dB R dB Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004437}
4438
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4440{
Glenn Kasten83d86532012-01-17 14:39:34 -08004441 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004442 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004443 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004444 } else {
4445 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4446 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004447 track_state state = mState;
4448 char stateChar;
4449 switch (state) {
4450 case IDLE:
4451 stateChar = 'I';
4452 break;
4453 case TERMINATED:
4454 stateChar = 'T';
4455 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004456 case STOPPING_1:
4457 stateChar = 's';
4458 break;
4459 case STOPPING_2:
4460 stateChar = '5';
4461 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004462 case STOPPED:
4463 stateChar = 'S';
4464 break;
4465 case RESUMING:
4466 stateChar = 'R';
4467 break;
4468 case ACTIVE:
4469 stateChar = 'A';
4470 break;
4471 case PAUSING:
4472 stateChar = 'p';
4473 break;
4474 case PAUSED:
4475 stateChar = 'P';
4476 break;
Eric Laurent29864602012-05-08 18:57:51 -07004477 case FLUSHED:
4478 stateChar = 'F';
4479 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004480 default:
4481 stateChar = '?';
4482 break;
4483 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004484 char nowInUnderrun;
4485 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4486 case UNDERRUN_FULL:
4487 nowInUnderrun = ' ';
4488 break;
4489 case UNDERRUN_PARTIAL:
4490 nowInUnderrun = '<';
4491 break;
4492 case UNDERRUN_EMPTY:
4493 nowInUnderrun = '*';
4494 break;
4495 default:
4496 nowInUnderrun = '?';
4497 break;
4498 }
Glenn Kastene213c862012-04-25 13:46:15 -07004499 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4500 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004501 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 mStreamType,
4503 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004504 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505 mSessionId,
Glenn Kastene2a05862012-11-13 09:58:55 -08004506 mStepCount,
Glenn Kastend7101432012-11-14 13:42:25 -08004507 mFrameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004508 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 mMute,
4510 mFillingUpStatus,
4511 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004512 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4513 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 mCblk->server,
4515 mCblk->user,
4516 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004517 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004518 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004519 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004520 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521}
4522
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004523// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004524status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004525 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004527 audio_track_cblk_t* cblk = this->cblk();
4528 uint32_t framesReady;
4529 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004531 // Check if last stepServer failed, try to step now
4532 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004533 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4534 // Since the fast mixer is higher priority than client callback thread,
4535 // it does not result in priority inversion for client.
4536 // But a non-blocking solution would be preferable to avoid
4537 // fast mixer being unable to tryLock(), and
4538 // to avoid the extra context switches if the client wakes up,
4539 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004540 if (!step()) goto getNextBuffer_exit;
4541 ALOGV("stepServer recovered");
4542 mStepServerFailed = false;
4543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544
Glenn Kasten288ed212012-04-25 17:52:27 -07004545 // FIXME Same as above
Glenn Kastenba850982012-11-06 16:15:41 -08004546 framesReady = cblk->framesReadyOut();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004548 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549 uint32_t s = cblk->server;
Glenn Kastend7101432012-11-14 13:42:25 -08004550 uint32_t bufferEnd = cblk->serverBase + mFrameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551
4552 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4553 if (framesReq > framesReady) {
4554 framesReq = framesReady;
4555 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004556 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004557 framesReq = bufferEnd - s;
4558 }
4559
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004560 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004561 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564
4565getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004566 buffer->raw = NULL;
4567 buffer->frameCount = 0;
4568 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4569 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570}
4571
Glenn Kasten288ed212012-04-25 17:52:27 -07004572// Note that framesReady() takes a mutex on the control block using tryLock().
4573// This could result in priority inversion if framesReady() is called by the normal mixer,
4574// as the normal mixer thread runs at lower
4575// priority than the client's callback thread: there is a short window within framesReady()
4576// during which the normal mixer could be preempted, and the client callback would block.
4577// Another problem can occur if framesReady() is called by the fast mixer:
4578// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4579// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4580size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kastenba850982012-11-06 16:15:41 -08004581 return mCblk->framesReadyOut();
John Grossman4ff14ba2012-02-08 16:37:41 -08004582}
4583
Glenn Kasten288ed212012-04-25 17:52:27 -07004584// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004586 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587
Glenn Kastend7101432012-11-14 13:42:25 -08004588 if (framesReady() >= mFrameCount ||
Glenn Kastend12b0332012-11-05 13:38:15 -08004589 (mCblk->flags & CBLK_FORCEREADY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590 mFillingUpStatus = FS_FILLED;
Glenn Kastend12b0332012-11-05 13:38:15 -08004591 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 return true;
4593 }
4594 return false;
4595}
4596
Glenn Kasten3acbd052012-02-28 10:39:56 -08004597status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004598 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599{
4600 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004601 ALOGV("start(%d), calling pid %d session %d",
4602 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004603
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 sp<ThreadBase> thread = mThread.promote();
4605 if (thread != 0) {
4606 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004607 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 // here the track could be either new, or restarted
4609 // in both cases "unstop" the track
4610 if (mState == PAUSED) {
4611 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004612 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 } else {
4614 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004615 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004616 }
4617
4618 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4619 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004620 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004622
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004623#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004624 // to track the speaker usage
4625 if (status == NO_ERROR) {
4626 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4627 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004628#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004629 }
4630 if (status == NO_ERROR) {
4631 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4632 playbackThread->addTrack_l(this);
4633 } else {
4634 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004635 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 }
4637 } else {
4638 status = BAD_VALUE;
4639 }
4640 return status;
4641}
4642
4643void AudioFlinger::PlaybackThread::Track::stop()
4644{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004645 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646 sp<ThreadBase> thread = mThread.promote();
4647 if (thread != 0) {
4648 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004649 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004650 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 // If the track is not active (PAUSED and buffers full), flush buffers
4652 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4653 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4654 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004655 mState = STOPPED;
4656 } else if (!isFastTrack()) {
4657 mState = STOPPED;
4658 } else {
4659 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4660 // and then to STOPPED and reset() when presentation is complete
4661 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07004663 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
4664 playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 }
4666 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4667 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004668 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004670
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004671#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004672 // to track the speaker usage
4673 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004674#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004675 }
4676 }
4677}
4678
4679void AudioFlinger::PlaybackThread::Track::pause()
4680{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004681 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004682 sp<ThreadBase> thread = mThread.promote();
4683 if (thread != 0) {
4684 Mutex::Autolock _l(thread->mLock);
4685 if (mState == ACTIVE || mState == RESUMING) {
4686 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004687 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688 if (!isOutputTrack()) {
4689 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004690 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004692
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004693#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004694 // to track the speaker usage
4695 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004696#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 }
4698 }
4699 }
4700}
4701
4702void AudioFlinger::PlaybackThread::Track::flush()
4703{
Steve Block3856b092011-10-20 11:56:00 +01004704 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705 sp<ThreadBase> thread = mThread.promote();
4706 if (thread != 0) {
4707 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004708 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kasten5b78fc92012-11-15 14:13:16 -08004709 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710 return;
4711 }
4712 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004713 // FLUSHED state
4714 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004715 // do not reset the track if it is still in the process of being stopped or paused.
4716 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004717 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004718 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004719 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4720 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4721 reset();
4722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 }
4724}
4725
4726void AudioFlinger::PlaybackThread::Track::reset()
4727{
4728 // Do not reset twice to avoid discarding data written just after a flush and before
4729 // the audioflinger thread detects the track is stopped.
4730 if (!mResetDone) {
4731 TrackBase::reset();
4732 // Force underrun condition to avoid false underrun callback until first data is
4733 // written to buffer
Glenn Kastend12b0332012-11-05 13:38:15 -08004734 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
4735 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 mFillingUpStatus = FS_FILLING;
4737 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004738 if (mState == FLUSHED) {
4739 mState = IDLE;
4740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741 }
4742}
4743
4744void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4745{
4746 mMute = muted;
4747}
4748
Mathias Agopian65ab4712010-07-14 17:59:35 -07004749status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4750{
4751 status_t status = DEAD_OBJECT;
4752 sp<ThreadBase> thread = mThread.promote();
4753 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004754 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004755 sp<AudioFlinger> af = mClient->audioFlinger();
4756
4757 Mutex::Autolock _l(af->mLock);
4758
4759 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004760
Eric Laurent109347d2012-07-02 12:31:03 -07004761 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004762 Mutex::Autolock _dl(playbackThread->mLock);
4763 Mutex::Autolock _sl(srcThread->mLock);
4764 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4765 if (chain == 0) {
4766 return INVALID_OPERATION;
4767 }
4768
4769 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4770 if (effect == 0) {
4771 return INVALID_OPERATION;
4772 }
4773 srcThread->removeEffect_l(effect);
4774 playbackThread->addEffect_l(effect);
4775 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4776 if (effect->state() == EffectModule::ACTIVE ||
4777 effect->state() == EffectModule::STOPPING) {
4778 effect->start();
4779 }
4780
4781 sp<EffectChain> dstChain = effect->chain().promote();
4782 if (dstChain == 0) {
4783 srcThread->addEffect_l(effect);
4784 return INVALID_OPERATION;
4785 }
4786 AudioSystem::unregisterEffect(effect->id());
4787 AudioSystem::registerEffect(&effect->desc(),
4788 srcThread->id(),
4789 dstChain->strategy(),
4790 AUDIO_SESSION_OUTPUT_MIX,
4791 effect->id());
4792 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004793 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794 }
4795 return status;
4796}
4797
4798void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4799{
4800 mAuxEffectId = EffectId;
4801 mAuxBuffer = buffer;
4802}
4803
Eric Laurenta011e352012-03-29 15:51:43 -07004804bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4805 size_t audioHalFrames)
4806{
4807 // a track is considered presented when the total number of frames written to audio HAL
4808 // corresponds to the number of frames written when presentationComplete() is called for the
4809 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4810 if (mPresentationCompleteFrames == 0) {
4811 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4812 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4813 mPresentationCompleteFrames, audioHalFrames);
4814 }
4815 if (framesWritten >= mPresentationCompleteFrames) {
4816 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4817 mSessionId, framesWritten);
4818 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004819 return true;
4820 }
4821 return false;
4822}
4823
4824void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4825{
4826 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4827 if (mSyncEvents[i]->type() == type) {
4828 mSyncEvents[i]->trigger();
4829 mSyncEvents.removeAt(i);
4830 i--;
4831 }
4832 }
4833}
4834
Glenn Kasten58912562012-04-03 10:45:00 -07004835// implement VolumeBufferProvider interface
4836
4837uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4838{
4839 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4840 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4841 uint32_t vlr = mCblk->getVolumeLR();
4842 uint32_t vl = vlr & 0xFFFF;
4843 uint32_t vr = vlr >> 16;
4844 // track volumes come from shared memory, so can't be trusted and must be clamped
4845 if (vl > MAX_GAIN_INT) {
4846 vl = MAX_GAIN_INT;
4847 }
4848 if (vr > MAX_GAIN_INT) {
4849 vr = MAX_GAIN_INT;
4850 }
4851 // now apply the cached master volume and stream type volume;
4852 // this is trusted but lacks any synchronization or barrier so may be stale
4853 float v = mCachedVolume;
4854 vl *= v;
4855 vr *= v;
4856 // re-combine into U4.16
4857 vlr = (vr << 16) | (vl & 0xFFFF);
4858 // FIXME look at mute, pause, and stop flags
4859 return vlr;
4860}
Eric Laurenta011e352012-03-29 15:51:43 -07004861
Eric Laurent29864602012-05-08 18:57:51 -07004862status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4863{
4864 if (mState == TERMINATED || mState == PAUSED ||
4865 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4866 (mState == STOPPED)))) {
4867 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4868 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4869 event->cancel();
4870 return INVALID_OPERATION;
4871 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004872 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004873 return NO_ERROR;
4874}
4875
Glenn Kastenba850982012-11-06 16:15:41 -08004876bool AudioFlinger::PlaybackThread::Track::isOut() const
4877{
4878 return true;
4879}
4880
John Grossman4ff14ba2012-02-08 16:37:41 -08004881// timed audio tracks
4882
4883sp<AudioFlinger::PlaybackThread::TimedTrack>
4884AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004885 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004886 const sp<Client>& client,
4887 audio_stream_type_t streamType,
4888 uint32_t sampleRate,
4889 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004890 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004891 size_t frameCount,
John Grossman4ff14ba2012-02-08 16:37:41 -08004892 const sp<IMemory>& sharedBuffer,
4893 int sessionId) {
4894 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004895 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004896
Glenn Kastena0356762012-03-19 10:38:51 -07004897 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004898 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4899 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004900}
4901
4902AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004903 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004904 const sp<Client>& client,
4905 audio_stream_type_t streamType,
4906 uint32_t sampleRate,
4907 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004908 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004909 size_t frameCount,
John Grossman4ff14ba2012-02-08 16:37:41 -08004910 const sp<IMemory>& sharedBuffer,
4911 int sessionId)
4912 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004913 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004914 mQueueHeadInFlight(false),
4915 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004916 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004917 mTimedSilenceBuffer(NULL),
4918 mTimedSilenceBufferSize(0),
4919 mTimedAudioOutputOnTime(false),
4920 mMediaTimeTransformValid(false)
4921{
4922 LocalClock lc;
4923 mLocalTimeFreq = lc.getLocalFreq();
4924
4925 mLocalTimeToSampleTransform.a_zero = 0;
4926 mLocalTimeToSampleTransform.b_zero = 0;
4927 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4928 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4929 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4930 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004931
4932 mMediaTimeToSampleTransform.a_zero = 0;
4933 mMediaTimeToSampleTransform.b_zero = 0;
4934 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4935 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4936 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4937 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004938}
4939
4940AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4941 mClient->releaseTimedTrack();
4942 delete [] mTimedSilenceBuffer;
4943}
4944
4945status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4946 size_t size, sp<IMemory>* buffer) {
4947
4948 Mutex::Autolock _l(mTimedBufferQueueLock);
4949
4950 trimTimedBufferQueue_l();
4951
4952 // lazily initialize the shared memory heap for timed buffers
4953 if (mTimedMemoryDealer == NULL) {
4954 const int kTimedBufferHeapSize = 512 << 10;
4955
4956 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4957 "AudioFlingerTimed");
4958 if (mTimedMemoryDealer == NULL)
4959 return NO_MEMORY;
4960 }
4961
4962 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4963 if (newBuffer == NULL) {
4964 newBuffer = mTimedMemoryDealer->allocate(size);
4965 if (newBuffer == NULL)
4966 return NO_MEMORY;
4967 }
4968
4969 *buffer = newBuffer;
4970 return NO_ERROR;
4971}
4972
4973// caller must hold mTimedBufferQueueLock
4974void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4975 int64_t mediaTimeNow;
4976 {
4977 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4978 if (!mMediaTimeTransformValid)
4979 return;
4980
4981 int64_t targetTimeNow;
4982 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4983 ? mCCHelper.getCommonTime(&targetTimeNow)
4984 : mCCHelper.getLocalTime(&targetTimeNow);
4985
4986 if (OK != res)
4987 return;
4988
4989 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4990 &mediaTimeNow)) {
4991 return;
4992 }
4993 }
4994
John Grossman1c345192012-03-27 14:00:17 -07004995 size_t trimEnd;
4996 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004997 int64_t bufEnd;
4998
John Grossmanc95cfbb2012-04-12 11:53:11 -07004999 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5000 // We have a next buffer. Just use its PTS as the PTS of the frame
5001 // following the last frame in this buffer. If the stream is sparse
5002 // (ie, there are deliberate gaps left in the stream which should be
5003 // filled with silence by the TimedAudioTrack), then this can result
5004 // in one extra buffer being left un-trimmed when it could have
5005 // been. In general, this is not typical, and we would rather
5006 // optimized away the TS calculation below for the more common case
5007 // where PTSes are contiguous.
5008 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5009 } else {
5010 // We have no next buffer. Compute the PTS of the frame following
5011 // the last frame in this buffer by computing the duration of of
5012 // this frame in media time units and adding it to the PTS of the
5013 // buffer.
5014 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005015 / mFrameSize;
John Grossmanc95cfbb2012-04-12 11:53:11 -07005016
5017 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5018 &bufEnd)) {
5019 ALOGE("Failed to convert frame count of %lld to media time"
5020 " duration" " (scale factor %d/%u) in %s",
5021 frameCount,
5022 mMediaTimeToSampleTransform.a_to_b_numer,
5023 mMediaTimeToSampleTransform.a_to_b_denom,
5024 __PRETTY_FUNCTION__);
5025 break;
5026 }
5027 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005028 }
John Grossman9fbdee12012-03-26 17:51:46 -07005029
5030 if (bufEnd > mediaTimeNow)
5031 break;
5032
5033 // Is the buffer we want to use in the middle of a mix operation right
5034 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5035 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005036 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005037 mTrimQueueHeadOnRelease = true;
5038 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005039 }
5040
John Grossman9fbdee12012-03-26 17:51:46 -07005041 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005042 if (trimStart < trimEnd) {
5043 // Update the bookkeeping for framesReady()
5044 for (size_t i = trimStart; i < trimEnd; ++i) {
5045 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5046 }
5047
5048 // Now actually remove the buffers from the queue.
5049 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005050 }
5051}
5052
John Grossman1c345192012-03-27 14:00:17 -07005053void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5054 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005055 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5056 "%s called (reason \"%s\"), but timed buffer queue has no"
5057 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005058
5059 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5060 mTimedBufferQueue.removeAt(0);
5061}
5062
5063void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5064 const TimedBuffer& buf,
5065 const char* logTag) {
5066 uint32_t bufBytes = buf.buffer()->size();
5067 uint32_t consumedAlready = buf.position();
5068
Eric Laurentb388e532012-04-14 13:32:48 -07005069 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005070 "Bad bookkeeping while updating frames pending. Timed buffer is"
5071 " only %u bytes long, but claims to have consumed %u"
5072 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005073 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005074
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005075 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005076 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5077 "Bad bookkeeping while updating frames pending. Should have at"
5078 " least %u queued frames, but we think we have only %u. (update"
5079 " reason: \"%s\")",
5080 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005081
5082 mFramesPendingInQueue -= bufFrames;
5083}
5084
John Grossman4ff14ba2012-02-08 16:37:41 -08005085status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5086 const sp<IMemory>& buffer, int64_t pts) {
5087
5088 {
5089 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5090 if (!mMediaTimeTransformValid)
5091 return INVALID_OPERATION;
5092 }
5093
5094 Mutex::Autolock _l(mTimedBufferQueueLock);
5095
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005096 uint32_t bufFrames = buffer->size() / mFrameSize;
John Grossman1c345192012-03-27 14:00:17 -07005097 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005098 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5099
5100 return NO_ERROR;
5101}
5102
5103status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5104 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5105
John Grossman1c345192012-03-27 14:00:17 -07005106 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5107 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5108 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005109
5110 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5111 target == TimedAudioTrack::COMMON_TIME)) {
5112 return BAD_VALUE;
5113 }
5114
5115 Mutex::Autolock lock(mMediaTimeTransformLock);
5116 mMediaTimeTransform = xform;
5117 mMediaTimeTransformTarget = target;
5118 mMediaTimeTransformValid = true;
5119
5120 return NO_ERROR;
5121}
5122
5123#define min(a, b) ((a) < (b) ? (a) : (b))
5124
5125// implementation of getNextBuffer for tracks whose buffers have timestamps
5126status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5127 AudioBufferProvider::Buffer* buffer, int64_t pts)
5128{
5129 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005130 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005131 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005132 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005133 return INVALID_OPERATION;
5134 }
5135
John Grossman4ff14ba2012-02-08 16:37:41 -08005136 Mutex::Autolock _l(mTimedBufferQueueLock);
5137
John Grossman9fbdee12012-03-26 17:51:46 -07005138 ALOG_ASSERT(!mQueueHeadInFlight,
5139 "getNextBuffer called without releaseBuffer!");
5140
John Grossman4ff14ba2012-02-08 16:37:41 -08005141 while (true) {
5142
5143 // if we have no timed buffers, then fail
5144 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005145 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005146 buffer->frameCount = 0;
5147 return NOT_ENOUGH_DATA;
5148 }
5149
5150 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5151
5152 // calculate the PTS of the head of the timed buffer queue expressed in
5153 // local time
5154 int64_t headLocalPTS;
5155 {
5156 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5157
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005158 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005159
5160 if (mMediaTimeTransform.a_to_b_denom == 0) {
5161 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005162 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005163 return NO_ERROR;
5164 }
5165
5166 int64_t transformedPTS;
5167 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5168 &transformedPTS)) {
5169 // the transform failed. this shouldn't happen, but if it does
5170 // then just drop this buffer
5171 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005172 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005173 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005174 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005175 return NO_ERROR;
5176 }
5177
5178 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5179 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5180 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005181 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005182 buffer->frameCount = 0;
5183 return INVALID_OPERATION;
5184 }
5185 } else {
5186 headLocalPTS = transformedPTS;
5187 }
5188 }
5189
5190 // adjust the head buffer's PTS to reflect the portion of the head buffer
5191 // that has already been consumed
5192 int64_t effectivePTS = headLocalPTS +
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005193 ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate());
John Grossman4ff14ba2012-02-08 16:37:41 -08005194
5195 // Calculate the delta in samples between the head of the input buffer
5196 // queue and the start of the next output buffer that will be written.
5197 // If the transformation fails because of over or underflow, it means
5198 // that the sample's position in the output stream is so far out of
5199 // whack that it should just be dropped.
5200 int64_t sampleDelta;
5201 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5202 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005203 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5204 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005205 continue;
5206 }
5207 if (!mLocalTimeToSampleTransform.doForwardTransform(
5208 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005209 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005210 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005211 continue;
5212 }
5213
John Grossman1c345192012-03-27 14:00:17 -07005214 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5215 " sampleDelta=[%d.%08x]",
5216 head.pts(), head.position(), pts,
5217 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5218 + (sampleDelta >> 32)),
5219 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005220
5221 // if the delta between the ideal placement for the next input sample and
5222 // the current output position is within this threshold, then we will
5223 // concatenate the next input samples to the previous output
5224 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005225 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005226
5227 // if this is the first buffer of audio that we're emitting from this track
5228 // then it should be almost exactly on time.
5229 const int64_t kSampleStartupThreshold = 1LL << 32;
5230
5231 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005232 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005233 // the next input is close enough to being on time, so concatenate it
5234 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005235 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005236
John Grossman1c345192012-03-27 14:00:17 -07005237 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5238 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005239 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005240 }
5241
5242 // Looks like our output is not on time. Reset our on timed status.
5243 // Next time we mix samples from our input queue, then should be within
5244 // the StartupThreshold.
5245 mTimedAudioOutputOnTime = false;
5246 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005247 // the gap between the current output position and the proper start of
5248 // the next input sample is too big, so fill it with silence
5249 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5250
John Grossman9fbdee12012-03-26 17:51:46 -07005251 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005252 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5253 return NO_ERROR;
5254 } else {
5255 // the next input sample is late
5256 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5257 size_t onTimeSamplePosition =
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005258 head.position() + lateFrames * mFrameSize;
John Grossman4ff14ba2012-02-08 16:37:41 -08005259
5260 if (onTimeSamplePosition > head.buffer()->size()) {
5261 // all the remaining samples in the head are too late, so
5262 // drop it and move on
5263 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005264 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005265 continue;
5266 } else {
5267 // skip over the late samples
5268 head.setPosition(onTimeSamplePosition);
5269
5270 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005271 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005272
5273 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5274 return NO_ERROR;
5275 }
5276 }
5277 }
5278}
5279
5280// Yield samples from the timed buffer queue head up to the given output
5281// buffer's capacity.
5282//
5283// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005284void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005285 AudioBufferProvider::Buffer* buffer) {
5286
5287 const TimedBuffer& head = mTimedBufferQueue[0];
5288
5289 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5290 head.position());
5291
5292 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005293 mFrameSize);
John Grossman4ff14ba2012-02-08 16:37:41 -08005294 size_t framesRequested = buffer->frameCount;
5295 buffer->frameCount = min(framesLeftInHead, framesRequested);
5296
John Grossman9fbdee12012-03-26 17:51:46 -07005297 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005298 mTimedAudioOutputOnTime = true;
5299}
5300
5301// Yield samples of silence up to the given output buffer's capacity
5302//
5303// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005304void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005305 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5306
5307 // lazily allocate a buffer filled with silence
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005308 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005309 delete [] mTimedSilenceBuffer;
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005310 mTimedSilenceBufferSize = numFrames * mFrameSize;
John Grossman4ff14ba2012-02-08 16:37:41 -08005311 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5312 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5313 }
5314
5315 buffer->raw = mTimedSilenceBuffer;
5316 size_t framesRequested = buffer->frameCount;
5317 buffer->frameCount = min(numFrames, framesRequested);
5318
5319 mTimedAudioOutputOnTime = false;
5320}
5321
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005322// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005323void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5324 AudioBufferProvider::Buffer* buffer) {
5325
5326 Mutex::Autolock _l(mTimedBufferQueueLock);
5327
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005328 // If the buffer which was just released is part of the buffer at the head
5329 // of the queue, be sure to update the amt of the buffer which has been
5330 // consumed. If the buffer being returned is not part of the head of the
5331 // queue, its either because the buffer is part of the silence buffer, or
5332 // because the head of the timed queue was trimmed after the mixer called
5333 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005334 if (buffer->raw == mTimedSilenceBuffer) {
5335 ALOG_ASSERT(!mQueueHeadInFlight,
5336 "Queue head in flight during release of silence buffer!");
5337 goto done;
5338 }
5339
5340 ALOG_ASSERT(mQueueHeadInFlight,
5341 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5342 " head in flight.");
5343
5344 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005345 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005346
5347 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005348 void* end = reinterpret_cast<void*>(
5349 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5350 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005351
John Grossman9fbdee12012-03-26 17:51:46 -07005352 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5353 "released buffer not within the head of the timed buffer"
5354 " queue; qHead = [%p, %p], released buffer = %p",
5355 start, end, buffer->raw);
5356
5357 head.setPosition(head.position() +
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005358 (buffer->frameCount * mFrameSize));
John Grossman9fbdee12012-03-26 17:51:46 -07005359 mQueueHeadInFlight = false;
5360
John Grossman1c345192012-03-27 14:00:17 -07005361 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5362 "Bad bookkeeping during releaseBuffer! Should have at"
5363 " least %u queued frames, but we think we have only %u",
5364 buffer->frameCount, mFramesPendingInQueue);
5365
5366 mFramesPendingInQueue -= buffer->frameCount;
5367
John Grossman9fbdee12012-03-26 17:51:46 -07005368 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5369 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005370 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005371 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005372 }
John Grossman9fbdee12012-03-26 17:51:46 -07005373 } else {
5374 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5375 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005376 }
5377
John Grossman9fbdee12012-03-26 17:51:46 -07005378done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005379 buffer->raw = 0;
5380 buffer->frameCount = 0;
5381}
5382
Glenn Kasten288ed212012-04-25 17:52:27 -07005383size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005384 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005385 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005386}
5387
5388AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5389 : mPTS(0), mPosition(0) {}
5390
5391AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5392 const sp<IMemory>& buffer, int64_t pts)
5393 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5394
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395// ----------------------------------------------------------------------------
5396
5397// RecordTrack constructor must be called with AudioFlinger::mLock held
5398AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005399 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400 const sp<Client>& client,
5401 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005402 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005403 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08005404 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405 int sessionId)
5406 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005407 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 mOverflow(false)
5409{
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005410 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411}
5412
5413AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5414{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005415 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416}
5417
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005418// AudioBufferProvider interface
Glenn Kasten8af901c2012-11-01 11:11:38 -07005419status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
5420 int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421{
5422 audio_track_cblk_t* cblk = this->cblk();
5423 uint32_t framesAvail;
5424 uint32_t framesReq = buffer->frameCount;
5425
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005426 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005427 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005428 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005429 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005430 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 }
5432
Glenn Kastenba850982012-11-06 16:15:41 -08005433 // FIXME lock is not actually held, so overrun is possible
Glenn Kastend7101432012-11-14 13:42:25 -08005434 framesAvail = cblk->framesAvailableIn_l(mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435
Glenn Kastenf6b16782011-12-15 09:51:17 -08005436 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437 uint32_t s = cblk->server;
Glenn Kastend7101432012-11-14 13:42:25 -08005438 uint32_t bufferEnd = cblk->serverBase + mFrameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439
5440 if (framesReq > framesAvail) {
5441 framesReq = framesAvail;
5442 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005443 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444 framesReq = bufferEnd - s;
5445 }
5446
5447 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 buffer->frameCount = framesReq;
5449 return NO_ERROR;
5450 }
5451
5452getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005453 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 buffer->frameCount = 0;
5455 return NOT_ENOUGH_DATA;
5456}
5457
Glenn Kasten3acbd052012-02-28 10:39:56 -08005458status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005459 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460{
5461 sp<ThreadBase> thread = mThread.promote();
5462 if (thread != 0) {
5463 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005464 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 } else {
5466 return BAD_VALUE;
5467 }
5468}
5469
5470void AudioFlinger::RecordThread::RecordTrack::stop()
5471{
5472 sp<ThreadBase> thread = mThread.promote();
5473 if (thread != 0) {
5474 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005475 recordThread->mLock.lock();
5476 bool doStop = recordThread->stop_l(this);
5477 if (doStop) {
5478 TrackBase::reset();
5479 // Force overrun condition to avoid false overrun callback until first data is
5480 // read from buffer
Glenn Kastend12b0332012-11-05 13:38:15 -08005481 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005482 }
5483 recordThread->mLock.unlock();
5484 if (doStop) {
5485 AudioSystem::stopInput(recordThread->id());
5486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 }
5488}
5489
Glenn Kasten510a3d62012-07-16 14:24:34 -07005490/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5491{
Glenn Kastene2a05862012-11-13 09:58:55 -08005492 result.append(" Clien Fmt Chn mask Session Step S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005493}
5494
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5496{
Jean-Michel Trivi60736462012-09-12 18:48:33 -07005497 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005498 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005500 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 mSessionId,
Glenn Kastene2a05862012-11-13 09:58:55 -08005502 mStepCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 mState,
5504 mCblk->sampleRate,
5505 mCblk->server,
Jean-Michel Trivi60736462012-09-12 18:48:33 -07005506 mCblk->user,
Glenn Kastend7101432012-11-14 13:42:25 -08005507 mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508}
5509
Glenn Kastenba850982012-11-06 16:15:41 -08005510bool AudioFlinger::RecordThread::RecordTrack::isOut() const
5511{
5512 return false;
5513}
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514
5515// ----------------------------------------------------------------------------
5516
5517AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005518 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519 DuplicatingThread *sourceThread,
5520 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005521 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005522 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08005523 size_t frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005524 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5525 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kasten2f6226a2012-11-08 12:13:58 -08005526 mActive(false), mSourceThread(sourceThread), mBuffers(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527{
5528
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 if (mCblk != NULL) {
Glenn Kasten2f6226a2012-11-08 12:13:58 -08005530 mBuffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 mOutBuffer.frameCount = 0;
5532 playbackThread->mTracks.add(this);
Glenn Kasten411e4472012-11-02 10:00:06 -07005533 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mBuffers %p, " \
Glenn Kasten1127d652012-11-14 08:44:39 -08005534 "mCblk->frameCount %d, mCblk->sampleRate %u, mChannelMask 0x%08x mBufferEnd %p",
Glenn Kasten411e4472012-11-02 10:00:06 -07005535 mCblk, mBuffer, mBuffers,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005536 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005538 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539 }
5540}
5541
5542AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5543{
5544 clearBufferQueue();
5545}
5546
Glenn Kasten3acbd052012-02-28 10:39:56 -08005547status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005548 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005550 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551 if (status != NO_ERROR) {
5552 return status;
5553 }
5554
5555 mActive = true;
5556 mRetryCount = 127;
5557 return status;
5558}
5559
5560void AudioFlinger::PlaybackThread::OutputTrack::stop()
5561{
5562 Track::stop();
5563 clearBufferQueue();
5564 mOutBuffer.frameCount = 0;
5565 mActive = false;
5566}
5567
5568bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5569{
5570 Buffer *pInBuffer;
5571 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005572 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005573 bool outputBufferFull = false;
5574 inBuffer.frameCount = frames;
5575 inBuffer.i16 = data;
5576
5577 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5578
5579 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005580 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 sp<ThreadBase> thread = mThread.promote();
5582 if (thread != 0) {
5583 MixerThread *mixerThread = (MixerThread *)thread.get();
Glenn Kastend7101432012-11-14 13:42:25 -08005584 if (mFrameCount > frames){
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
Glenn Kastend7101432012-11-14 13:42:25 -08005586 uint32_t startFrames = (mFrameCount - frames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587 pInBuffer = new Buffer;
5588 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5589 pInBuffer->frameCount = startFrames;
5590 pInBuffer->i16 = pInBuffer->mBuffer;
5591 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5592 mBufferQueue.add(pInBuffer);
5593 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005594 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
5596 }
5597 }
5598 }
5599
5600 while (waitTimeLeftMs) {
5601 // First write pending buffers, then new data
5602 if (mBufferQueue.size()) {
5603 pInBuffer = mBufferQueue.itemAt(0);
5604 } else {
5605 pInBuffer = &inBuffer;
5606 }
5607
5608 if (pInBuffer->frameCount == 0) {
5609 break;
5610 }
5611
5612 if (mOutBuffer.frameCount == 0) {
5613 mOutBuffer.frameCount = pInBuffer->frameCount;
5614 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005615 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07005616 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this,
5617 mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 outputBufferFull = true;
5619 break;
5620 }
5621 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5622 if (waitTimeLeftMs >= waitTimeMs) {
5623 waitTimeLeftMs -= waitTimeMs;
5624 } else {
5625 waitTimeLeftMs = 0;
5626 }
5627 }
5628
Glenn Kasten8af901c2012-11-01 11:11:38 -07005629 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
5630 pInBuffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kastend7101432012-11-14 13:42:25 -08005632 mCblk->stepUserOut(outFrames, mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 pInBuffer->frameCount -= outFrames;
5634 pInBuffer->i16 += outFrames * channelCount;
5635 mOutBuffer.frameCount -= outFrames;
5636 mOutBuffer.i16 += outFrames * channelCount;
5637
5638 if (pInBuffer->frameCount == 0) {
5639 if (mBufferQueue.size()) {
5640 mBufferQueue.removeAt(0);
5641 delete [] pInBuffer->mBuffer;
5642 delete pInBuffer;
Glenn Kasten8af901c2012-11-01 11:11:38 -07005643 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
5644 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645 } else {
5646 break;
5647 }
5648 }
5649 }
5650
5651 // If we could not write all frames, allocate a buffer and queue it for next time.
5652 if (inBuffer.frameCount) {
5653 sp<ThreadBase> thread = mThread.promote();
5654 if (thread != 0 && !thread->standby()) {
5655 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5656 pInBuffer = new Buffer;
5657 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5658 pInBuffer->frameCount = inBuffer.frameCount;
5659 pInBuffer->i16 = pInBuffer->mBuffer;
Glenn Kasten8af901c2012-11-01 11:11:38 -07005660 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
5661 sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 mBufferQueue.add(pInBuffer);
Glenn Kasten8af901c2012-11-01 11:11:38 -07005663 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
5664 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005665 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07005666 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
5667 mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 }
5669 }
5670 }
5671
5672 // Calling write() with a 0 length buffer, means that no more data will be written:
5673 // If no more buffers are pending, fill output track buffer to make sure it is started
5674 // by output mixer.
5675 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kastend7101432012-11-14 13:42:25 -08005676 if (mCblk->user < mFrameCount) {
5677 frames = mFrameCount - mCblk->user;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 pInBuffer = new Buffer;
5679 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5680 pInBuffer->frameCount = frames;
5681 pInBuffer->i16 = pInBuffer->mBuffer;
5682 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5683 mBufferQueue.add(pInBuffer);
5684 } else if (mActive) {
5685 stop();
5686 }
5687 }
5688
5689 return outputBufferFull;
5690}
5691
Glenn Kasten8af901c2012-11-01 11:11:38 -07005692status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
5693 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694{
5695 int active;
5696 status_t result;
5697 audio_track_cblk_t* cblk = mCblk;
5698 uint32_t framesReq = buffer->frameCount;
5699
Glenn Kastencbe4b362012-10-18 15:51:03 -07005700 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 buffer->frameCount = 0;
5702
Glenn Kastend7101432012-11-14 13:42:25 -08005703 uint32_t framesAvail = cblk->framesAvailableOut(mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704
5705
5706 if (framesAvail == 0) {
5707 Mutex::Autolock _l(cblk->lock);
5708 goto start_loop_here;
5709 while (framesAvail == 0) {
5710 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005711 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005712 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005713 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 }
5715 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5716 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005717 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 }
5719 // read the server count again
5720 start_loop_here:
Glenn Kastend7101432012-11-14 13:42:25 -08005721 framesAvail = cblk->framesAvailableOut_l(mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722 }
5723 }
5724
5725// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005726// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727// }
5728
5729 if (framesReq > framesAvail) {
5730 framesReq = framesAvail;
5731 }
5732
5733 uint32_t u = cblk->user;
Glenn Kastend7101432012-11-14 13:42:25 -08005734 uint32_t bufferEnd = cblk->userBase + mFrameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735
Marco Nelissena1472d92012-03-30 14:36:54 -07005736 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 framesReq = bufferEnd - u;
5738 }
5739
5740 buffer->frameCount = framesReq;
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005741 buffer->raw = cblk->buffer(mBuffers, mFrameSize, u);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 return NO_ERROR;
5743}
5744
5745
5746void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5747{
5748 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749
5750 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005751 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005752 delete [] pBuffer->mBuffer;
5753 delete pBuffer;
5754 }
5755 mBufferQueue.clear();
5756}
5757
5758// ----------------------------------------------------------------------------
5759
5760AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5761 : RefBase(),
5762 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005763 // 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 -07005764 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005765 mPid(pid),
5766 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005767{
5768 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5769}
5770
5771// Client destructor must be called with AudioFlinger::mLock held
5772AudioFlinger::Client::~Client()
5773{
5774 mAudioFlinger->removeClient_l(mPid);
5775}
5776
Glenn Kasten435dbe62012-01-30 10:15:48 -08005777sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778{
5779 return mMemoryDealer;
5780}
5781
John Grossman4ff14ba2012-02-08 16:37:41 -08005782// Reserve one of the limited slots for a timed audio track associated
5783// with this client
5784bool AudioFlinger::Client::reserveTimedTrack()
5785{
5786 const int kMaxTimedTracksPerClient = 4;
5787
5788 Mutex::Autolock _l(mTimedTrackLock);
5789
5790 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5791 ALOGW("can not create timed track - pid %d has exceeded the limit",
5792 mPid);
5793 return false;
5794 }
5795
5796 mTimedTrackCount++;
5797 return true;
5798}
5799
5800// Release a slot for a timed audio track
5801void AudioFlinger::Client::releaseTimedTrack()
5802{
5803 Mutex::Autolock _l(mTimedTrackLock);
5804 mTimedTrackCount--;
5805}
5806
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807// ----------------------------------------------------------------------------
5808
5809AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5810 const sp<IAudioFlingerClient>& client,
5811 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005812 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813{
5814}
5815
5816AudioFlinger::NotificationClient::~NotificationClient()
5817{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818}
5819
5820void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5821{
5822 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005823 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005824}
5825
5826// ----------------------------------------------------------------------------
5827
5828AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5829 : BnAudioTrack(),
5830 mTrack(track)
5831{
5832}
5833
5834AudioFlinger::TrackHandle::~TrackHandle() {
5835 // just stop the track on deletion, associated resources
5836 // will be freed from the main thread once all pending buffers have
5837 // been played. Unless it's not in the active track list, in which
5838 // case we free everything now...
5839 mTrack->destroy();
5840}
5841
Glenn Kasten90716c52012-01-26 13:40:12 -08005842sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5843 return mTrack->getCblk();
5844}
5845
Glenn Kasten3acbd052012-02-28 10:39:56 -08005846status_t AudioFlinger::TrackHandle::start() {
5847 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848}
5849
5850void AudioFlinger::TrackHandle::stop() {
5851 mTrack->stop();
5852}
5853
5854void AudioFlinger::TrackHandle::flush() {
5855 mTrack->flush();
5856}
5857
5858void AudioFlinger::TrackHandle::mute(bool e) {
5859 mTrack->mute(e);
5860}
5861
5862void AudioFlinger::TrackHandle::pause() {
5863 mTrack->pause();
5864}
5865
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5867{
5868 return mTrack->attachAuxEffect(EffectId);
5869}
5870
John Grossman4ff14ba2012-02-08 16:37:41 -08005871status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5872 sp<IMemory>* buffer) {
5873 if (!mTrack->isTimedTrack())
5874 return INVALID_OPERATION;
5875
5876 PlaybackThread::TimedTrack* tt =
5877 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5878 return tt->allocateTimedBuffer(size, buffer);
5879}
5880
5881status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5882 int64_t pts) {
5883 if (!mTrack->isTimedTrack())
5884 return INVALID_OPERATION;
5885
5886 PlaybackThread::TimedTrack* tt =
5887 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5888 return tt->queueTimedBuffer(buffer, pts);
5889}
5890
5891status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5892 const LinearTransform& xform, int target) {
5893
5894 if (!mTrack->isTimedTrack())
5895 return INVALID_OPERATION;
5896
5897 PlaybackThread::TimedTrack* tt =
5898 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5899 return tt->setMediaTimeTransform(
5900 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5901}
5902
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903status_t AudioFlinger::TrackHandle::onTransact(
5904 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5905{
5906 return BnAudioTrack::onTransact(code, data, reply, flags);
5907}
5908
5909// ----------------------------------------------------------------------------
5910
5911sp<IAudioRecord> AudioFlinger::openRecord(
5912 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005913 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005915 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005916 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08005917 size_t frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005918 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005919 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 int *sessionId,
5921 status_t *status)
5922{
5923 sp<RecordThread::RecordTrack> recordTrack;
5924 sp<RecordHandle> recordHandle;
5925 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 status_t lStatus;
5927 RecordThread *thread;
5928 size_t inFrameCount;
5929 int lSessionId;
5930
5931 // check calling permissions
5932 if (!recordingAllowed()) {
5933 lStatus = PERMISSION_DENIED;
5934 goto Exit;
5935 }
5936
5937 // add client to list
5938 { // scope for mLock
5939 Mutex::Autolock _l(mLock);
5940 thread = checkRecordThread_l(input);
5941 if (thread == NULL) {
5942 lStatus = BAD_VALUE;
5943 goto Exit;
5944 }
5945
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005946 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947
5948 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005949 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 lSessionId = *sessionId;
5951 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005952 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 if (sessionId != NULL) {
5954 *sessionId = lSessionId;
5955 }
5956 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07005957 // create new record track.
5958 // The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005959 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5960 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005962 if (lStatus != NO_ERROR) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07005963 // remove local strong reference to Client before deleting the RecordTrack so that the
5964 // Client destructor is called by the TrackBase destructor with mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 client.clear();
5966 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 goto Exit;
5968 }
5969
5970 // return to handle to client
5971 recordHandle = new RecordHandle(recordTrack);
5972 lStatus = NO_ERROR;
5973
5974Exit:
5975 if (status) {
5976 *status = lStatus;
5977 }
5978 return recordHandle;
5979}
5980
5981// ----------------------------------------------------------------------------
5982
Glenn Kasten8af901c2012-11-01 11:11:38 -07005983AudioFlinger::RecordHandle::RecordHandle(
5984 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 : BnAudioRecord(),
5986 mRecordTrack(recordTrack)
5987{
5988}
5989
5990AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005991 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005992 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993}
5994
Glenn Kasten90716c52012-01-26 13:40:12 -08005995sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5996 return mRecordTrack->getCblk();
5997}
5998
Glenn Kasten8af901c2012-11-01 11:11:38 -07005999status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
6000 int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006001 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006002 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003}
6004
6005void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006006 stop_nonvirtual();
6007}
6008
6009void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006010 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 mRecordTrack->stop();
6012}
6013
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014status_t AudioFlinger::RecordHandle::onTransact(
6015 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6016{
6017 return BnAudioRecord::onTransact(code, data, reply, flags);
6018}
6019
6020// ----------------------------------------------------------------------------
6021
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006022AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6023 AudioStreamIn *input,
6024 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006025 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006026 audio_io_handle_t id,
Glenn Kasten8c327342012-09-30 12:29:28 -07006027 audio_devices_t device,
6028 const sp<NBAIO_Sink>& teeSink) :
Eric Laurent88959252012-08-28 14:26:53 -07006029 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006030 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006031 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07006032 mReqChannelCount(popcount(channelMask)),
Glenn Kasten8c327342012-09-30 12:29:28 -07006033 mReqSampleRate(sampleRate),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006034 // mBytesRead is only meaningful while active, and so is cleared in start()
6035 // (but might be better to also clear here for dump?)
Glenn Kasten8c327342012-09-30 12:29:28 -07006036 mTeeSink(teeSink)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037{
Glenn Kasten480b4682012-02-28 12:30:08 -08006038 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006039
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 readInputParameters();
Glenn Kasten8c327342012-09-30 12:29:28 -07006041
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042}
6043
6044
6045AudioFlinger::RecordThread::~RecordThread()
6046{
6047 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006048 delete mResampler;
6049 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050}
6051
6052void AudioFlinger::RecordThread::onFirstRef()
6053{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006054 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055}
6056
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006057status_t AudioFlinger::RecordThread::readyToRun()
6058{
6059 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006060 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006061 return status;
6062}
6063
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064bool AudioFlinger::RecordThread::threadLoop()
6065{
6066 AudioBufferProvider::Buffer buffer;
6067 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006068 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069
Eric Laurent44d98482010-09-30 16:12:31 -07006070 nsecs_t lastWarning = 0;
6071
Glenn Kastene4e2a372012-07-23 12:55:09 -07006072 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006073 acquireWakeLock();
6074
Jean-Michel Trivi89b44702012-09-13 11:44:00 -07006075 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006076 bool readOnce = false;
6077
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078 // start recording
6079 while (!exitPending()) {
6080
6081 processConfigEvents();
6082
6083 { // scope for mLock
6084 Mutex::Autolock _l(mLock);
6085 checkForNewParameters_l();
6086 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006087 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088
6089 if (exitPending()) break;
6090
Eric Laurentfeb0db62011-07-22 09:04:31 -07006091 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006092 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 // go to sleep
6094 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006095 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006096 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097 continue;
6098 }
6099 if (mActiveTrack != 0) {
6100 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006101 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 mActiveTrack.clear();
6103 mStartStopCond.broadcast();
6104 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6105 if (mReqChannelCount != mActiveTrack->channelCount()) {
6106 mActiveTrack.clear();
6107 mStartStopCond.broadcast();
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006108 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 // record start succeeds only if first read from audio input
6110 // succeeds
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006111 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112 mActiveTrack->mState = TrackBase::ACTIVE;
6113 } else {
6114 mActiveTrack.clear();
6115 }
6116 mStartStopCond.broadcast();
6117 }
6118 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006119 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6120 removeTrack_l(mActiveTrack);
6121 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 }
6123 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006124 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 }
6126
6127 if (mActiveTrack != 0) {
6128 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6129 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006130 unlockEffectChains(effectChains);
6131 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 continue;
6133 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006134 for (size_t i = 0; i < effectChains.size(); i ++) {
6135 effectChains[i]->process_l();
6136 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006137
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006139 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006140 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006142 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 // no resampling
6144 while (framesOut) {
6145 size_t framesIn = mFrameCount - mRsmpInIndex;
6146 if (framesIn) {
6147 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
Glenn Kasten8af901c2012-11-01 11:11:38 -07006148 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kasten5aab59a2012-11-12 07:58:20 -08006149 mActiveTrack->mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 if (framesIn > framesOut)
6151 framesIn = framesOut;
6152 mRsmpInIndex += framesIn;
6153 framesOut -= framesIn;
6154 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006155 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 memcpy(dst, src, framesIn * mFrameSize);
6157 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006159 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6160 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006162 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6163 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 }
6165 }
6166 }
6167 if (framesOut && mFrameCount == mRsmpInIndex) {
Glenn Kasten8c327342012-09-30 12:29:28 -07006168 void *readInto;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 if (framesOut == mFrameCount &&
Glenn Kasten8af901c2012-11-01 11:11:38 -07006170 ((int)mChannelCount == mReqChannelCount ||
6171 mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Glenn Kasten8c327342012-09-30 12:29:28 -07006172 readInto = buffer.raw;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 framesOut = 0;
6174 } else {
Glenn Kasten8c327342012-09-30 12:29:28 -07006175 readInto = mRsmpInBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176 mRsmpInIndex = 0;
6177 }
Glenn Kasten8c327342012-09-30 12:29:28 -07006178 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes);
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006179 if (mBytesRead <= 0) {
6180 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6181 {
6182 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 // Force input into standby so that it tries to
6184 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006185 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 }
6188 mRsmpInIndex = mFrameCount;
6189 framesOut = 0;
6190 buffer.frameCount = 0;
Glenn Kasten8c327342012-09-30 12:29:28 -07006191 } else if (mTeeSink != 0) {
6192 (void) mTeeSink->write(readInto,
6193 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 }
6195 }
6196 }
6197 } else {
6198 // resampling
6199
6200 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6201 // alter output frame count as if we were expecting stereo samples
6202 if (mChannelCount == 1 && mReqChannelCount == 1) {
6203 framesOut >>= 1;
6204 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07006205 mResampler->resample(mRsmpOutBuffer, framesOut,
6206 this /* AudioBufferProvider* */);
6207 // ditherAndClamp() works as long as all buffers returned by
6208 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006209 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006210 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Glenn Kasten8af901c2012-11-01 11:11:38 -07006211 // the resampler always outputs stereo samples:
6212 // do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006213 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6214 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006216 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 }
6218
6219 }
Eric Laurenta011e352012-03-29 15:51:43 -07006220 if (mFramestoDrop == 0) {
6221 mActiveTrack->releaseBuffer(&buffer);
6222 } else {
6223 if (mFramestoDrop > 0) {
6224 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006225 if (mFramestoDrop <= 0) {
6226 clearSyncStartEvent();
6227 }
6228 } else {
6229 mFramestoDrop += buffer.frameCount;
6230 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6231 mSyncStartEvent->isCancelled()) {
6232 ALOGW("Synced record %s, session %d, trigger session %d",
6233 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6234 mActiveTrack->sessionId(),
6235 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6236 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006237 }
6238 }
6239 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006240 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 }
6242 // client isn't retrieving buffers fast enough
6243 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006244 if (!mActiveTrack->setOverflow()) {
6245 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006246 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006247 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006248 lastWarning = now;
6249 }
6250 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 // Release the processor for a while before asking for a new buffer.
6252 // This will give the application more chance to read from the buffer and
6253 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006254 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 }
6256 }
Eric Laurentec437d82011-07-26 20:54:46 -07006257 // enable changes in effect chain
6258 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006259 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 }
6261
Glenn Kastene4e2a372012-07-23 12:55:09 -07006262 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263
Glenn Kasten33e6e352012-07-16 15:56:57 -07006264 {
6265 Mutex::Autolock _l(mLock);
6266 mActiveTrack.clear();
6267 mStartStopCond.broadcast();
6268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269
Eric Laurentfeb0db62011-07-22 09:04:31 -07006270 releaseWakeLock();
6271
Steve Block3856b092011-10-20 11:56:00 +01006272 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 return false;
6274}
6275
Glenn Kastene4e2a372012-07-23 12:55:09 -07006276void AudioFlinger::RecordThread::standby()
6277{
6278 if (!mStandby) {
6279 inputStandBy();
6280 mStandby = true;
6281 }
6282}
6283
6284void AudioFlinger::RecordThread::inputStandBy()
6285{
6286 mInput->stream->common.standby(&mInput->stream->common);
6287}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006288
6289sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6290 const sp<AudioFlinger::Client>& client,
6291 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006292 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006293 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08006294 size_t frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006295 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006296 IAudioFlinger::track_flags_t flags,
6297 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006298 status_t *status)
6299{
6300 sp<RecordTrack> track;
6301 status_t lStatus;
6302
6303 lStatus = initCheck();
6304 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006305 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006306 goto Exit;
6307 }
6308
Glenn Kasten1879fff2012-07-11 15:36:59 -07006309 // FIXME use flags and tid similar to createTrack_l()
6310
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006311 { // scope for mLock
6312 Mutex::Autolock _l(mLock);
6313
6314 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006315 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006316
Glenn Kasten7378ca52012-01-20 13:44:40 -08006317 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006318 lStatus = NO_MEMORY;
6319 goto Exit;
6320 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006321 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006322
Eric Laurent59bd0da2011-08-01 09:52:20 -07006323 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurent88959252012-08-28 14:26:53 -07006324 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006325 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006326 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6327 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006328 }
6329 lStatus = NO_ERROR;
6330
6331Exit:
6332 if (status) {
6333 *status = lStatus;
6334 }
6335 return track;
6336}
6337
Eric Laurenta011e352012-03-29 15:51:43 -07006338status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006339 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006340 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341{
Glenn Kasten58912562012-04-03 10:45:00 -07006342 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006343 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006345
6346 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006347 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006348 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6349 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6350 triggerSession,
6351 recordTrack->sessionId(),
6352 syncStartEventCallback,
6353 this);
Eric Laurent29864602012-05-08 18:57:51 -07006354 // Sync event can be cancelled by the trigger session if the track is not in a
6355 // compatible state in which case we start record immediately
6356 if (mSyncStartEvent->isCancelled()) {
6357 clearSyncStartEvent();
6358 } else {
6359 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6360 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6361 }
Eric Laurenta011e352012-03-29 15:51:43 -07006362 }
6363
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006365 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366 if (mActiveTrack != 0) {
6367 if (recordTrack != mActiveTrack.get()) {
6368 status = -EBUSY;
6369 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6370 mActiveTrack->mState = TrackBase::ACTIVE;
6371 }
6372 return status;
6373 }
6374
6375 recordTrack->mState = TrackBase::IDLE;
6376 mActiveTrack = recordTrack;
6377 mLock.unlock();
6378 status_t status = AudioSystem::startInput(mId);
6379 mLock.lock();
6380 if (status != NO_ERROR) {
6381 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006382 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 return status;
6384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385 mRsmpInIndex = mFrameCount;
6386 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006387 if (mResampler != NULL) {
6388 mResampler->reset();
6389 }
6390 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006392 ALOGV("Signal record thread");
Eric Laurent67d8ac32012-09-24 15:02:17 -07006393 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006395 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 mActiveTrack.clear();
6397 status = INVALID_OPERATION;
6398 goto startError;
6399 }
6400 mStartStopCond.wait(mLock);
6401 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006402 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 status = BAD_VALUE;
6404 goto startError;
6405 }
Steve Block3856b092011-10-20 11:56:00 +01006406 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006407 return status;
6408 }
6409startError:
6410 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006411 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006412 return status;
6413}
6414
Eric Laurenta011e352012-03-29 15:51:43 -07006415void AudioFlinger::RecordThread::clearSyncStartEvent()
6416{
6417 if (mSyncStartEvent != 0) {
6418 mSyncStartEvent->cancel();
6419 }
6420 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006421 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006422}
6423
6424void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6425{
6426 sp<SyncEvent> strongEvent = event.promote();
6427
6428 if (strongEvent != 0) {
6429 RecordThread *me = (RecordThread *)strongEvent->cookie();
6430 me->handleSyncStartEvent(strongEvent);
6431 }
6432}
6433
6434void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6435{
Eric Laurent29864602012-05-08 18:57:51 -07006436 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006437 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6438 // from audio HAL
6439 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006440 }
6441}
6442
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006443bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006444 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006445 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6446 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006448 recordTrack->mState = TrackBase::PAUSING;
6449 // do not wait for mStartStopCond if exiting
6450 if (exitPending()) {
6451 return true;
6452 }
6453 mStartStopCond.wait(mLock);
6454 // if we have been restarted, recordTrack == mActiveTrack.get() here
6455 if (exitPending() || recordTrack != mActiveTrack.get()) {
6456 ALOGV("Record stopped OK");
6457 return true;
6458 }
6459 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460}
6461
Glenn Kasten106e8a42012-08-02 13:37:12 -07006462bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006463{
6464 return false;
6465}
6466
6467status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6468{
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006469#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 -07006470 if (!isValidSyncEvent(event)) {
6471 return BAD_VALUE;
6472 }
6473
Glenn Kasten510a3d62012-07-16 14:24:34 -07006474 int eventSession = event->triggerSession();
6475 status_t ret = NAME_NOT_FOUND;
6476
Eric Laurenta011e352012-03-29 15:51:43 -07006477 Mutex::Autolock _l(mLock);
6478
Glenn Kasten510a3d62012-07-16 14:24:34 -07006479 for (size_t i = 0; i < mTracks.size(); i++) {
6480 sp<RecordTrack> track = mTracks[i];
6481 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006482 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006483 ret = NO_ERROR;
6484 }
Eric Laurenta011e352012-03-29 15:51:43 -07006485 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006486 return ret;
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006487#else
6488 return BAD_VALUE;
6489#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006490}
6491
6492void AudioFlinger::RecordThread::RecordTrack::destroy()
6493{
6494 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6495 sp<RecordTrack> keep(this);
6496 {
6497 sp<ThreadBase> thread = mThread.promote();
6498 if (thread != 0) {
6499 if (mState == ACTIVE || mState == RESUMING) {
6500 AudioSystem::stopInput(thread->id());
6501 }
6502 AudioSystem::releaseInput(thread->id());
6503 Mutex::Autolock _l(thread->mLock);
6504 RecordThread *recordThread = (RecordThread *) thread.get();
6505 recordThread->destroyTrack_l(this);
6506 }
6507 }
6508}
6509
6510// destroyTrack_l() must be called with ThreadBase::mLock held
6511void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6512{
6513 track->mState = TrackBase::TERMINATED;
6514 // active tracks are removed by threadLoop()
6515 if (mActiveTrack != track) {
6516 removeTrack_l(track);
6517 }
6518}
6519
6520void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6521{
6522 mTracks.remove(track);
6523 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006524}
6525
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006526void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006527{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006528 dumpInternals(fd, args);
6529 dumpTracks(fd, args);
6530 dumpEffectChains(fd, args);
6531}
6532
6533void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6534{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 const size_t SIZE = 256;
6536 char buffer[SIZE];
6537 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538
6539 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6540 result.append(buffer);
6541
6542 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6544 result.append(buffer);
6545 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6546 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006547 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 result.append(buffer);
6549 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6550 result.append(buffer);
Glenn Kasten1127d652012-11-14 08:44:39 -08006551 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006554 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006555 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006556
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 write(fd, result.string(), result.size());
6558
6559 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006560}
6561
6562void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6563{
6564 const size_t SIZE = 256;
6565 char buffer[SIZE];
6566 String8 result;
6567
6568 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6569 result.append(buffer);
6570 RecordTrack::appendDumpHeader(result);
6571 for (size_t i = 0; i < mTracks.size(); ++i) {
6572 sp<RecordTrack> track = mTracks[i];
6573 if (track != 0) {
6574 track->dump(buffer, SIZE);
6575 result.append(buffer);
6576 }
6577 }
6578
6579 if (mActiveTrack != 0) {
6580 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6581 result.append(buffer);
6582 RecordTrack::appendDumpHeader(result);
6583 mActiveTrack->dump(buffer, SIZE);
6584 result.append(buffer);
6585
6586 }
6587 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588}
6589
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006590// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006591status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592{
6593 size_t framesReq = buffer->frameCount;
6594 size_t framesReady = mFrameCount - mRsmpInIndex;
6595 int channelCount;
6596
6597 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006598 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi89b44702012-09-13 11:44:00 -07006599 if (mBytesRead <= 0) {
6600 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6601 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602 // Force input into standby so that it tries to
6603 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006604 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006605 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006607 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 buffer->frameCount = 0;
6609 return NOT_ENOUGH_DATA;
6610 }
6611 mRsmpInIndex = 0;
6612 framesReady = mFrameCount;
6613 }
6614
6615 if (framesReq > framesReady) {
6616 framesReq = framesReady;
6617 }
6618
6619 if (mChannelCount == 1 && mReqChannelCount == 2) {
6620 channelCount = 1;
6621 } else {
6622 channelCount = 2;
6623 }
6624 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6625 buffer->frameCount = framesReq;
6626 return NO_ERROR;
6627}
6628
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006629// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006630void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6631{
6632 mRsmpInIndex += buffer->frameCount;
6633 buffer->frameCount = 0;
6634}
6635
6636bool AudioFlinger::RecordThread::checkForNewParameters_l()
6637{
6638 bool reconfig = false;
6639
6640 while (!mNewParameters.isEmpty()) {
6641 status_t status = NO_ERROR;
6642 String8 keyValuePair = mNewParameters[0];
6643 AudioParameter param = AudioParameter(keyValuePair);
6644 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006645 audio_format_t reqFormat = mFormat;
Glenn Kasten1127d652012-11-14 08:44:39 -08006646 uint32_t reqSamplingRate = mReqSampleRate;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006647 int reqChannelCount = mReqChannelCount;
6648
6649 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6650 reqSamplingRate = value;
6651 reconfig = true;
6652 }
6653 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006654 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655 reconfig = true;
6656 }
6657 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006658 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 reconfig = true;
6660 }
6661 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6662 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006663 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664 // if frame count is changed after track creation
6665 if (mActiveTrack != 0) {
6666 status = INVALID_OPERATION;
6667 } else {
6668 reconfig = true;
6669 }
6670 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006671 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6672 // forward device change to effects that have requested to be
6673 // aware of attached audio device.
6674 for (size_t i = 0; i < mEffectChains.size(); i++) {
6675 mEffectChains[i]->setDevice_l(value);
6676 }
Eric Laurent88959252012-08-28 14:26:53 -07006677
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006678 // store input device and output device but do not forward output device to audio HAL.
6679 // Note that status is ignored by the caller for output device
6680 // (see AudioFlinger::setParameters()
Eric Laurent88959252012-08-28 14:26:53 -07006681 if (audio_is_output_devices(value)) {
6682 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006683 status = BAD_VALUE;
6684 } else {
Eric Laurent88959252012-08-28 14:26:53 -07006685 mInDevice = value;
Glenn Kasten8af901c2012-11-01 11:11:38 -07006686 // disable AEC and NS if the device is a BT SCO headset supporting those
6687 // pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006688 if (mTracks.size() > 0) {
Eric Laurent88959252012-08-28 14:26:53 -07006689 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6690 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006691 for (size_t i = 0; i < mTracks.size(); i++) {
6692 sp<RecordTrack> track = mTracks[i];
6693 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6694 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6695 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006696 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006697 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006698 }
Eric Laurent2e9b0f22012-08-31 17:44:06 -07006699 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6700 mAudioSource != (audio_source_t)value) {
6701 // forward device change to effects that have requested to be
6702 // aware of attached audio device.
6703 for (size_t i = 0; i < mEffectChains.size(); i++) {
6704 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6705 }
6706 mAudioSource = (audio_source_t)value;
6707 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006708 if (status == NO_ERROR) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07006709 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6710 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006712 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006713 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6714 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715 }
6716 if (reconfig) {
6717 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006718 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006719 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kasten8af901c2012-11-01 11:11:38 -07006720 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common)
6721 <= (2 * reqSamplingRate)) &&
6722 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
6723 <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006724 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 status = NO_ERROR;
6726 }
6727 if (status == NO_ERROR) {
6728 readInputParameters();
Eric Laurentef6be0b2012-09-13 11:18:23 -07006729 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730 }
6731 }
6732 }
6733
6734 mNewParameters.removeAt(0);
6735
6736 mParamStatus = status;
6737 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006738 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6739 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006740 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 }
6742 return reconfig;
6743}
6744
6745String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6746{
Dima Zavinfce7a472011-04-19 22:30:36 -07006747 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006748 String8 out_s8 = String8();
6749
6750 Mutex::Autolock _l(mLock);
6751 if (initCheck() != NO_ERROR) {
6752 return out_s8;
6753 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006754
Dima Zavin799a70e2011-04-18 16:57:27 -07006755 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006756 out_s8 = String8(s);
6757 free(s);
6758 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759}
6760
6761void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6762 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006763 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764
6765 switch (event) {
6766 case AudioSystem::INPUT_OPENED:
6767 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006768 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769 desc.samplingRate = mSampleRate;
6770 desc.format = mFormat;
6771 desc.frameCount = mFrameCount;
6772 desc.latency = 0;
6773 param2 = &desc;
6774 break;
6775
6776 case AudioSystem::INPUT_CLOSED:
6777 default:
6778 break;
6779 }
6780 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6781}
6782
6783void AudioFlinger::RecordThread::readInputParameters()
6784{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006785 delete mRsmpInBuffer;
6786 // mRsmpInBuffer is always assigned a new[] below
6787 delete mRsmpOutBuffer;
6788 mRsmpOutBuffer = NULL;
6789 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006790 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006791
Dima Zavin799a70e2011-04-18 16:57:27 -07006792 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006793 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6794 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006795 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006796 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006797 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006799 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006800 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6801
Glenn Kasten53d76db2012-03-08 12:32:47 -08006802 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 {
6804 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006805 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6806 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006807 if (mChannelCount == 1 && mReqChannelCount == 2) {
6808 channelCount = 1;
6809 } else {
6810 channelCount = 2;
6811 }
6812 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6813 mResampler->setSampleRate(mSampleRate);
6814 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6815 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6816
Glenn Kasten8af901c2012-11-01 11:11:38 -07006817 // optmization: if mono to mono, alter input frame count as if we were inputing
6818 // stereo samples
Mathias Agopian65ab4712010-07-14 17:59:35 -07006819 if (mChannelCount == 1 && mReqChannelCount == 1) {
6820 mFrameCount >>= 1;
6821 }
6822
6823 }
6824 mRsmpInIndex = mFrameCount;
6825}
6826
6827unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6828{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006829 Mutex::Autolock _l(mLock);
6830 if (initCheck() != NO_ERROR) {
6831 return 0;
6832 }
6833
Dima Zavin799a70e2011-04-18 16:57:27 -07006834 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835}
6836
Glenn Kasten106e8a42012-08-02 13:37:12 -07006837uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006838{
6839 Mutex::Autolock _l(mLock);
6840 uint32_t result = 0;
6841 if (getEffectChain_l(sessionId) != 0) {
6842 result = EFFECT_SESSION;
6843 }
6844
Glenn Kasten510a3d62012-07-16 14:24:34 -07006845 for (size_t i = 0; i < mTracks.size(); ++i) {
6846 if (sessionId == mTracks[i]->sessionId()) {
6847 result |= TRACK_SESSION;
6848 break;
6849 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006850 }
6851
6852 return result;
6853}
6854
Glenn Kasten106e8a42012-08-02 13:37:12 -07006855KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006856{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006857 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006858 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006859 for (size_t j = 0; j < mTracks.size(); ++j) {
6860 sp<RecordThread::RecordTrack> track = mTracks[j];
6861 int sessionId = track->sessionId();
6862 if (ids.indexOfKey(sessionId) < 0) {
6863 ids.add(sessionId, true);
6864 }
6865 }
6866 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006867}
6868
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006869AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6870{
6871 Mutex::Autolock _l(mLock);
6872 AudioStreamIn *input = mInput;
6873 mInput = NULL;
6874 return input;
6875}
6876
6877// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006878audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006879{
6880 if (mInput == NULL) {
6881 return NULL;
6882 }
6883 return &mInput->stream->common;
6884}
6885
6886
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887// ----------------------------------------------------------------------------
6888
Eric Laurenta4c5a552012-03-29 10:12:40 -07006889audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6890{
6891 if (!settingsAllowed()) {
6892 return 0;
6893 }
6894 Mutex::Autolock _l(mLock);
6895 return loadHwModule_l(name);
6896}
6897
6898// loadHwModule_l() must be called with AudioFlinger::mLock held
6899audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6900{
6901 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6902 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6903 ALOGW("loadHwModule() module %s already loaded", name);
6904 return mAudioHwDevs.keyAt(i);
6905 }
6906 }
6907
Eric Laurenta4c5a552012-03-29 10:12:40 -07006908 audio_hw_device_t *dev;
6909
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006910 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006911 if (rc) {
6912 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6913 return 0;
6914 }
6915
6916 mHardwareStatus = AUDIO_HW_INIT;
6917 rc = dev->init_check(dev);
6918 mHardwareStatus = AUDIO_HW_IDLE;
6919 if (rc) {
6920 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6921 return 0;
6922 }
6923
John Grossmanee578c02012-07-23 17:05:46 -07006924 // Check and cache this HAL's level of support for master mute and master
6925 // volume. If this is the first HAL opened, and it supports the get
6926 // methods, use the initial values provided by the HAL as the current
6927 // master mute and volume settings.
6928
6929 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6930 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006931 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006932
6933 if (0 == mAudioHwDevs.size()) {
6934 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6935 if (NULL != dev->get_master_volume) {
6936 float mv;
6937 if (OK == dev->get_master_volume(dev, &mv)) {
6938 mMasterVolume = mv;
6939 }
6940 }
6941
6942 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6943 if (NULL != dev->get_master_mute) {
6944 bool mm;
6945 if (OK == dev->get_master_mute(dev, &mm)) {
6946 mMasterMute = mm;
6947 }
6948 }
6949 }
6950
Eric Laurenta4c5a552012-03-29 10:12:40 -07006951 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006952 if ((NULL != dev->set_master_volume) &&
6953 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6954 flags = static_cast<AudioHwDevice::Flags>(flags |
6955 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6956 }
6957
6958 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6959 if ((NULL != dev->set_master_mute) &&
6960 (OK == dev->set_master_mute(dev, mMasterMute))) {
6961 flags = static_cast<AudioHwDevice::Flags>(flags |
6962 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6963 }
6964
Eric Laurenta4c5a552012-03-29 10:12:40 -07006965 mHardwareStatus = AUDIO_HW_IDLE;
6966 }
6967
6968 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006969 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006970
6971 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006972 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006973
6974 return handle;
6975
6976}
6977
Glenn Kasten4c6db4c2012-09-24 11:27:18 -07006978// ----------------------------------------------------------------------------
6979
Glenn Kasten1127d652012-11-14 08:44:39 -08006980uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kasten4c6db4c2012-09-24 11:27:18 -07006981{
6982 Mutex::Autolock _l(mLock);
6983 PlaybackThread *thread = primaryPlaybackThread_l();
6984 return thread != NULL ? thread->sampleRate() : 0;
6985}
6986
Glenn Kasten7da35f22012-11-14 12:54:39 -08006987size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kasten4c6db4c2012-09-24 11:27:18 -07006988{
6989 Mutex::Autolock _l(mLock);
6990 PlaybackThread *thread = primaryPlaybackThread_l();
6991 return thread != NULL ? thread->frameCountHAL() : 0;
6992}
6993
6994// ----------------------------------------------------------------------------
6995
Eric Laurenta4c5a552012-03-29 10:12:40 -07006996audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6997 audio_devices_t *pDevices,
6998 uint32_t *pSamplingRate,
6999 audio_format_t *pFormat,
7000 audio_channel_mask_t *pChannelMask,
7001 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007002 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003{
7004 status_t status;
7005 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007006 struct audio_config config = {
7007 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7008 channel_mask: pChannelMask ? *pChannelMask : 0,
7009 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7010 };
7011 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007012 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013
Eric Laurenta4c5a552012-03-29 10:12:40 -07007014 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7015 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007016 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007017 config.sample_rate,
7018 config.format,
7019 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007020 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021
7022 if (pDevices == NULL || *pDevices == 0) {
7023 return 0;
7024 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007025
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 Mutex::Autolock _l(mLock);
7027
Eric Laurenta4c5a552012-03-29 10:12:40 -07007028 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007029 if (outHwDev == NULL)
7030 return 0;
7031
John Grossmanee578c02012-07-23 17:05:46 -07007032 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007033 audio_io_handle_t id = nextUniqueId();
7034
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007035 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007036
John Grossmanee578c02012-07-23 17:05:46 -07007037 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007038 id,
7039 *pDevices,
7040 (audio_output_flags_t)flags,
7041 &config,
7042 &outStream);
7043
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007044 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8af901c2012-11-01 11:11:38 -07007045 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, "
7046 "Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007047 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007048 config.sample_rate,
7049 config.format,
7050 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051 status);
7052
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007053 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007054 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007055
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007056 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007057 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7058 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007060 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061 } else {
7062 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007063 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064 }
7065 mPlaybackThreads.add(id, thread);
7066
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007067 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7068 if (pFormat != NULL) *pFormat = config.format;
7069 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08007070 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007071
7072 // notify client processes of the new output creation
7073 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007074
7075 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007076 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007077 ALOGI("Using module %d has the primary audio interface", module);
7078 mPrimaryHardwareDev = outHwDev;
7079
7080 AutoMutex lock(mHardwareLock);
7081 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007082 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007083 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085 return id;
7086 }
7087
7088 return 0;
7089}
7090
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007091audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7092 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093{
7094 Mutex::Autolock _l(mLock);
7095 MixerThread *thread1 = checkMixerThread_l(output1);
7096 MixerThread *thread2 = checkMixerThread_l(output2);
7097
7098 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07007099 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
7100 output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 return 0;
7102 }
7103
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007104 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7106 thread->addOutputTrack(thread2);
7107 mPlaybackThreads.add(id, thread);
7108 // notify client processes of the new output creation
7109 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7110 return id;
7111}
7112
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007113status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114{
Glenn Kastend96c5722012-04-25 13:44:49 -07007115 return closeOutput_nonvirtual(output);
7116}
7117
7118status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7119{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120 // keep strong reference on the playback thread so that
7121 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007122 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123 {
7124 Mutex::Autolock _l(mLock);
7125 thread = checkPlaybackThread_l(output);
7126 if (thread == NULL) {
7127 return BAD_VALUE;
7128 }
7129
Steve Block3856b092011-10-20 11:56:00 +01007130 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007132 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007133 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007134 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07007135 DuplicatingThread *dupThread =
7136 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 dupThread->removeOutputTrack((MixerThread *)thread.get());
7138 }
7139 }
7140 }
Glenn Kastena1117922012-01-26 10:53:32 -08007141 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007142 mPlaybackThreads.removeItem(output);
7143 }
7144 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007145 // The thread entity (active unit of execution) is no longer running here,
7146 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007148 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007149 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007150 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007151 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007152 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007153 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154 }
7155 return NO_ERROR;
7156}
7157
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007158status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159{
7160 Mutex::Autolock _l(mLock);
7161 PlaybackThread *thread = checkPlaybackThread_l(output);
7162
7163 if (thread == NULL) {
7164 return BAD_VALUE;
7165 }
7166
Steve Block3856b092011-10-20 11:56:00 +01007167 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168 thread->suspend();
7169
7170 return NO_ERROR;
7171}
7172
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007173status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174{
7175 Mutex::Autolock _l(mLock);
7176 PlaybackThread *thread = checkPlaybackThread_l(output);
7177
7178 if (thread == NULL) {
7179 return BAD_VALUE;
7180 }
7181
Steve Block3856b092011-10-20 11:56:00 +01007182 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183
7184 thread->restore();
7185
7186 return NO_ERROR;
7187}
7188
Eric Laurenta4c5a552012-03-29 10:12:40 -07007189audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7190 audio_devices_t *pDevices,
7191 uint32_t *pSamplingRate,
7192 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007193 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007194{
7195 status_t status;
7196 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007197 struct audio_config config = {
7198 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7199 channel_mask: pChannelMask ? *pChannelMask : 0,
7200 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7201 };
7202 uint32_t reqSamplingRate = config.sample_rate;
7203 audio_format_t reqFormat = config.format;
7204 audio_channel_mask_t reqChannels = config.channel_mask;
7205 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007206 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007207
7208 if (pDevices == NULL || *pDevices == 0) {
7209 return 0;
7210 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007211
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212 Mutex::Autolock _l(mLock);
7213
Eric Laurenta4c5a552012-03-29 10:12:40 -07007214 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007215 if (inHwDev == NULL)
7216 return 0;
7217
John Grossmanee578c02012-07-23 17:05:46 -07007218 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007219 audio_io_handle_t id = nextUniqueId();
7220
John Grossmanee578c02012-07-23 17:05:46 -07007221 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007222 &inStream);
Glenn Kasten8af901c2012-11-01 11:11:38 -07007223 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
7224 "status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007225 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007226 config.sample_rate,
7227 config.format,
7228 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007229 status);
7230
Glenn Kasten8af901c2012-11-01 11:11:38 -07007231 // If the input could not be opened with the requested parameters and we can handle the
7232 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
7233 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007234 if (status == BAD_VALUE &&
7235 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7236 (config.sample_rate <= 2 * reqSamplingRate) &&
7237 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007238 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007239 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007240 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241 }
7242
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007243 if (status == NO_ERROR && inStream != NULL) {
Glenn Kasten8c327342012-09-30 12:29:28 -07007244
7245 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
7246 // or (re-)create if current Pipe is idle and does not match the new format
7247 sp<NBAIO_Sink> teeSink;
7248#ifdef TEE_SINK_INPUT_FRAMES
7249 enum {
7250 TEE_SINK_NO, // don't copy input
7251 TEE_SINK_NEW, // copy input using a new pipe
7252 TEE_SINK_OLD, // copy input using an existing pipe
7253 } kind;
7254 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
7255 popcount(inStream->common.get_channels(&inStream->common)));
7256 if (format == Format_Invalid) {
7257 kind = TEE_SINK_NO;
7258 } else if (mRecordTeeSink == 0) {
7259 kind = TEE_SINK_NEW;
7260 } else if (mRecordTeeSink->getStrongCount() != 1) {
7261 kind = TEE_SINK_NO;
7262 } else if (format == mRecordTeeSink->format()) {
7263 kind = TEE_SINK_OLD;
7264 } else {
7265 kind = TEE_SINK_NEW;
7266 }
7267 switch (kind) {
7268 case TEE_SINK_NEW: {
7269 Pipe *pipe = new Pipe(TEE_SINK_INPUT_FRAMES, format);
7270 size_t numCounterOffers = 0;
7271 const NBAIO_Format offers[1] = {format};
7272 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7273 ALOG_ASSERT(index == 0);
7274 PipeReader *pipeReader = new PipeReader(*pipe);
7275 numCounterOffers = 0;
7276 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7277 ALOG_ASSERT(index == 0);
7278 mRecordTeeSink = pipe;
7279 mRecordTeeSource = pipeReader;
7280 teeSink = pipe;
7281 }
7282 break;
7283 case TEE_SINK_OLD:
7284 teeSink = mRecordTeeSink;
7285 break;
7286 case TEE_SINK_NO:
7287 default:
7288 break;
7289 }
7290#endif
Dima Zavin799a70e2011-04-18 16:57:27 -07007291 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7292
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007293 // Start record thread
7294 // RecorThread require both input and output device indication to forward to audio
7295 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007296 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Glenn Kasten8c327342012-09-30 12:29:28 -07007297
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007298 thread = new RecordThread(this,
7299 input,
7300 reqSamplingRate,
7301 reqChannels,
7302 id,
Glenn Kasten8c327342012-09-30 12:29:28 -07007303 device, teeSink);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007305 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007306 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007307 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007308 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310 // notify client processes of the new input creation
7311 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7312 return id;
7313 }
7314
7315 return 0;
7316}
7317
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007318status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319{
Glenn Kastend96c5722012-04-25 13:44:49 -07007320 return closeInput_nonvirtual(input);
7321}
7322
7323status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7324{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325 // keep strong reference on the record thread so that
7326 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007327 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328 {
7329 Mutex::Autolock _l(mLock);
7330 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007331 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 return BAD_VALUE;
7333 }
7334
Steve Block3856b092011-10-20 11:56:00 +01007335 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007336 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 mRecordThreads.removeItem(input);
7338 }
7339 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007340 // The thread entity (active unit of execution) is no longer running here,
7341 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007343 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007344 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007345 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007346 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007347 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348
7349 return NO_ERROR;
7350}
7351
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007352status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353{
7354 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007355 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356
7357 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7358 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007359 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007360 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361
7362 return NO_ERROR;
7363}
7364
7365
7366int AudioFlinger::newAudioSessionId()
7367{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007368 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369}
7370
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007371void AudioFlinger::acquireAudioSessionId(int audioSession)
7372{
7373 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007374 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007375 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007376 size_t num = mAudioSessionRefs.size();
7377 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007378 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007379 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7380 ref->mCnt++;
7381 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007382 return;
7383 }
7384 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007385 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7386 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007387}
7388
7389void AudioFlinger::releaseAudioSessionId(int audioSession)
7390{
7391 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007392 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007393 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007394 size_t num = mAudioSessionRefs.size();
7395 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007396 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007397 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7398 ref->mCnt--;
7399 ALOGV(" decremented refcount to %d", ref->mCnt);
7400 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007401 mAudioSessionRefs.removeAt(i);
7402 delete ref;
7403 purgeStaleEffects_l();
7404 }
7405 return;
7406 }
7407 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007408 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007409}
7410
7411void AudioFlinger::purgeStaleEffects_l() {
7412
Steve Block3856b092011-10-20 11:56:00 +01007413 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007414
7415 Vector< sp<EffectChain> > chains;
7416
7417 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7418 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7419 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7420 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007421 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7422 chains.push(ec);
7423 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007424 }
7425 }
7426 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7427 sp<RecordThread> t = mRecordThreads.valueAt(i);
7428 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7429 sp<EffectChain> ec = t->mEffectChains[j];
7430 chains.push(ec);
7431 }
7432 }
7433
7434 for (size_t i = 0; i < chains.size(); i++) {
7435 sp<EffectChain> ec = chains[i];
7436 int sessionid = ec->sessionId();
7437 sp<ThreadBase> t = ec->mThread.promote();
7438 if (t == 0) {
7439 continue;
7440 }
7441 size_t numsessionrefs = mAudioSessionRefs.size();
7442 bool found = false;
7443 for (size_t k = 0; k < numsessionrefs; k++) {
7444 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007445 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007446 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007447 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007448 found = true;
7449 break;
7450 }
7451 }
7452 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007453 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007454 // remove all effects from the chain
7455 while (ec->mEffects.size()) {
7456 sp<EffectModule> effect = ec->mEffects[0];
7457 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007458 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007459 if (effect->purgeHandles()) {
7460 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007461 }
7462 AudioSystem::unregisterEffect(effect->id());
7463 }
7464 }
7465 }
7466 return;
7467}
7468
Mathias Agopian65ab4712010-07-14 17:59:35 -07007469// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007470AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007471{
Glenn Kastena1117922012-01-26 10:53:32 -08007472 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473}
7474
7475// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007476AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007477{
7478 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007479 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007480}
7481
7482// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007483AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484{
Glenn Kastena1117922012-01-26 10:53:32 -08007485 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007486}
7487
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007488uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007489{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007490 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491}
7492
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007493AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007494{
7495 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7496 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007497 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007498 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007499 return thread;
7500 }
7501 }
7502 return NULL;
7503}
7504
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007505audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007506{
7507 PlaybackThread *thread = primaryPlaybackThread_l();
7508
7509 if (thread == NULL) {
7510 return 0;
7511 }
7512
Eric Laurent88959252012-08-28 14:26:53 -07007513 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007514}
7515
Eric Laurenta011e352012-03-29 15:51:43 -07007516sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7517 int triggerSession,
7518 int listenerSession,
7519 sync_event_callback_t callBack,
7520 void *cookie)
7521{
7522 Mutex::Autolock _l(mLock);
7523
7524 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7525 status_t playStatus = NAME_NOT_FOUND;
7526 status_t recStatus = NAME_NOT_FOUND;
7527 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7528 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7529 if (playStatus == NO_ERROR) {
7530 return event;
7531 }
7532 }
7533 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7534 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7535 if (recStatus == NO_ERROR) {
7536 return event;
7537 }
7538 }
7539 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7540 mPendingSyncEvents.add(event);
7541 } else {
7542 ALOGV("createSyncEvent() invalid event %d", event->type());
7543 event.clear();
7544 }
7545 return event;
7546}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007547
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548// ----------------------------------------------------------------------------
7549// Effect management
7550// ----------------------------------------------------------------------------
7551
7552
Glenn Kastenf587ba52012-01-26 16:25:10 -08007553status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554{
7555 Mutex::Autolock _l(mLock);
7556 return EffectQueryNumberEffects(numEffects);
7557}
7558
Glenn Kastenf587ba52012-01-26 16:25:10 -08007559status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560{
7561 Mutex::Autolock _l(mLock);
7562 return EffectQueryEffect(index, descriptor);
7563}
7564
Glenn Kasten5e92a782012-01-30 07:40:52 -08007565status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007566 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567{
7568 Mutex::Autolock _l(mLock);
7569 return EffectGetDescriptor(pUuid, descriptor);
7570}
7571
7572
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7574 effect_descriptor_t *pDesc,
7575 const sp<IEffectClient>& effectClient,
7576 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007577 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578 int sessionId,
7579 status_t *status,
7580 int *id,
7581 int *enabled)
7582{
7583 status_t lStatus = NO_ERROR;
7584 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007585 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007587 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007588 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589
7590 if (pDesc == NULL) {
7591 lStatus = BAD_VALUE;
7592 goto Exit;
7593 }
7594
Eric Laurent84e9a102010-09-23 16:10:16 -07007595 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007596 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007597 lStatus = PERMISSION_DENIED;
7598 goto Exit;
7599 }
7600
Dima Zavinfce7a472011-04-19 22:30:36 -07007601 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007602 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007603 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007604 lStatus = PERMISSION_DENIED;
7605 goto Exit;
7606 }
7607
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007608 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007609 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007610 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007611 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007612 lStatus = BAD_VALUE;
7613 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007614 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007615 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007616 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007617 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007618 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007619 }
7620 }
7621
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622 {
7623 Mutex::Autolock _l(mLock);
7624
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625
7626 if (!EffectIsNullUuid(&pDesc->uuid)) {
7627 // if uuid is specified, request effect descriptor
7628 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7629 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007630 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631 goto Exit;
7632 }
7633 } else {
7634 // if uuid is not specified, look for an available implementation
7635 // of the required type in effect factory
7636 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007637 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638 lStatus = BAD_VALUE;
7639 goto Exit;
7640 }
7641 uint32_t numEffects = 0;
7642 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007643 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007644 bool found = false;
7645
7646 lStatus = EffectQueryNumberEffects(&numEffects);
7647 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007648 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007649 goto Exit;
7650 }
7651 for (uint32_t i = 0; i < numEffects; i++) {
7652 lStatus = EffectQueryEffect(i, &desc);
7653 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007654 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007655 continue;
7656 }
7657 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7658 // If matching type found save effect descriptor. If the session is
7659 // 0 and the effect is not auxiliary, continue enumeration in case
7660 // an auxiliary version of this effect type is available
7661 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007662 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007663 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007664 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7665 break;
7666 }
7667 }
7668 }
7669 if (!found) {
7670 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007671 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007672 goto Exit;
7673 }
7674 // For same effect type, chose auxiliary version over insert version if
7675 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007676 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007677 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007678 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 }
7680 }
7681
7682 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007683 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007684 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7685 lStatus = INVALID_OPERATION;
7686 goto Exit;
7687 }
7688
Eric Laurent59255e42011-07-27 19:49:51 -07007689 // check recording permission for visualizer
7690 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7691 !recordingAllowed()) {
7692 lStatus = PERMISSION_DENIED;
7693 goto Exit;
7694 }
7695
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007697 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698
7699 // If output is not specified try to find a matching audio session ID in one of the
7700 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007701 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7702 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007703 // Note: io is never 0 when creating an effect on an input
7704 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007705 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007706 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7707 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007708 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007709 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007710 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007712 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007713 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7714 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7715 io = mRecordThreads.keyAt(i);
7716 break;
7717 }
7718 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007719 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007720 // If no output thread contains the requested session ID, default to
7721 // first output. The effect chain will be moved to the correct output
7722 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007723 if (io == 0 && mPlaybackThreads.size()) {
7724 io = mPlaybackThreads.keyAt(0);
7725 }
Steve Block3856b092011-10-20 11:56:00 +01007726 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007727 }
7728 ThreadBase *thread = checkRecordThread_l(io);
7729 if (thread == NULL) {
7730 thread = checkPlaybackThread_l(io);
7731 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007732 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007733 lStatus = BAD_VALUE;
7734 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007735 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007736 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007737
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007738 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007739
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007740 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007741 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7742 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007743 if (handle != 0 && id != NULL) {
7744 *id = handle->id();
7745 }
7746 }
7747
7748Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007749 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 *status = lStatus;
7751 }
7752 return handle;
7753}
7754
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007755status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7756 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007757{
Steve Block3856b092011-10-20 11:56:00 +01007758 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007759 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007760 Mutex::Autolock _l(mLock);
7761 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007762 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007763 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 }
Eric Laurentde070132010-07-13 04:45:46 -07007765 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7766 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007767 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007768 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769 }
Eric Laurentde070132010-07-13 04:45:46 -07007770 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7771 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007772 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007773 return BAD_VALUE;
7774 }
7775
7776 Mutex::Autolock _dl(dstThread->mLock);
7777 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007778 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007779
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 return NO_ERROR;
7781}
7782
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007783// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007784status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007785 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007786 AudioFlinger::PlaybackThread *dstThread,
7787 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007788{
Steve Block3856b092011-10-20 11:56:00 +01007789 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007790 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007791
Eric Laurent59255e42011-07-27 19:49:51 -07007792 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007793 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007794 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007795 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007796 return INVALID_OPERATION;
7797 }
7798
Eric Laurent39e94f82010-07-28 01:32:47 -07007799 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007800 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007801 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007802 // removed.
7803 srcThread->removeEffectChain_l(chain);
7804
7805 // transfer all effects one by one so that new effect chain is created on new thread with
7806 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007807 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007808 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007809 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007810 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7811 while (effect != 0) {
7812 srcThread->removeEffect_l(effect);
7813 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007814 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7815 if (effect->state() == EffectModule::ACTIVE ||
7816 effect->state() == EffectModule::STOPPING) {
7817 effect->start();
7818 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007819 // if the move request is not received from audio policy manager, the effect must be
7820 // re-registered with the new strategy and output
7821 if (dstChain == 0) {
7822 dstChain = effect->chain().promote();
7823 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007824 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007825 srcThread->addEffect_l(effect);
7826 return NO_INIT;
7827 }
7828 strategy = dstChain->strategy();
7829 }
7830 if (reRegister) {
7831 AudioSystem::unregisterEffect(effect->id());
7832 AudioSystem::registerEffect(&effect->desc(),
7833 dstOutput,
7834 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007835 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007836 effect->id());
7837 }
Eric Laurentde070132010-07-13 04:45:46 -07007838 effect = chain->getEffectFromId_l(0);
7839 }
7840
7841 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842}
7843
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007844
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007846sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007847 const sp<AudioFlinger::Client>& client,
7848 const sp<IEffectClient>& effectClient,
7849 int32_t priority,
7850 int sessionId,
7851 effect_descriptor_t *desc,
7852 int *enabled,
7853 status_t *status
7854 )
7855{
7856 sp<EffectModule> effect;
7857 sp<EffectHandle> handle;
7858 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007860 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 bool effectCreated = false;
7862 bool effectRegistered = false;
7863
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007864 lStatus = initCheck();
7865 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007866 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007867 goto Exit;
7868 }
7869
7870 // Do not allow effects with session ID 0 on direct output or duplicating threads
7871 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007872 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007873 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007874 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875 lStatus = BAD_VALUE;
7876 goto Exit;
7877 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007878 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007879 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007880 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007881 desc->name, desc->flags, mType);
7882 lStatus = BAD_VALUE;
7883 goto Exit;
7884 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885
Steve Block3856b092011-10-20 11:56:00 +01007886 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887
7888 { // scope for mLock
7889 Mutex::Autolock _l(mLock);
7890
7891 // check for existing effect chain with the requested audio session
7892 chain = getEffectChain_l(sessionId);
7893 if (chain == 0) {
7894 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007895 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896 chain = new EffectChain(this, sessionId);
7897 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007898 chain->setStrategy(getStrategyForSession_l(sessionId));
7899 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007901 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007902 }
7903
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007904 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905
7906 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007907 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007909 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 if (lStatus != NO_ERROR) {
7911 goto Exit;
7912 }
7913 effectRegistered = true;
7914 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007915 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916 lStatus = effect->status();
7917 if (lStatus != NO_ERROR) {
7918 goto Exit;
7919 }
Eric Laurentcab11242010-07-15 12:50:15 -07007920 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007921 if (lStatus != NO_ERROR) {
7922 goto Exit;
7923 }
7924 effectCreated = true;
7925
Eric Laurent88959252012-08-28 14:26:53 -07007926 effect->setDevice(mOutDevice);
7927 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007928 effect->setMode(mAudioFlinger->getMode());
Eric Laurent2e9b0f22012-08-31 17:44:06 -07007929 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007930 }
7931 // create effect handle and connect it to effect module
7932 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007933 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007934 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 *enabled = (int)effect->isEnabled();
7936 }
7937 }
7938
7939Exit:
7940 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007941 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007943 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 }
7945 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007946 AudioSystem::unregisterEffect(effect->id());
7947 }
7948 if (chainCreated) {
7949 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007950 }
7951 handle.clear();
7952 }
7953
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007954 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955 *status = lStatus;
7956 }
7957 return handle;
7958}
7959
Eric Laurent717e1282012-06-29 16:36:52 -07007960sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7961{
7962 Mutex::Autolock _l(mLock);
7963 return getEffect_l(sessionId, effectId);
7964}
7965
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007966sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7967{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007968 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007969 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007970}
7971
Eric Laurentde070132010-07-13 04:45:46 -07007972// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7973// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007974status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007975{
7976 // check for existing effect chain with the requested audio session
7977 int sessionId = effect->sessionId();
7978 sp<EffectChain> chain = getEffectChain_l(sessionId);
7979 bool chainCreated = false;
7980
7981 if (chain == 0) {
7982 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007983 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007984 chain = new EffectChain(this, sessionId);
7985 addEffectChain_l(chain);
7986 chain->setStrategy(getStrategyForSession_l(sessionId));
7987 chainCreated = true;
7988 }
Steve Block3856b092011-10-20 11:56:00 +01007989 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007990
7991 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007992 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007993 this, effect->desc().name, chain.get());
7994 return BAD_VALUE;
7995 }
7996
7997 status_t status = chain->addEffect_l(effect);
7998 if (status != NO_ERROR) {
7999 if (chainCreated) {
8000 removeEffectChain_l(chain);
8001 }
8002 return status;
8003 }
8004
Eric Laurent88959252012-08-28 14:26:53 -07008005 effect->setDevice(mOutDevice);
8006 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008007 effect->setMode(mAudioFlinger->getMode());
Eric Laurent2e9b0f22012-08-31 17:44:06 -07008008 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008009 return NO_ERROR;
8010}
8011
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008012void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008013
Steve Block3856b092011-10-20 11:56:00 +01008014 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008015 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008016 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8017 detachAuxEffect_l(effect->id());
8018 }
8019
8020 sp<EffectChain> chain = effect->chain().promote();
8021 if (chain != 0) {
8022 // remove effect chain if removing last effect
8023 if (chain->removeEffect_l(effect) == 0) {
8024 removeEffectChain_l(chain);
8025 }
8026 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008027 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008028 }
8029}
8030
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008031void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008032 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008033{
8034 effectChains = mEffectChains;
8035 for (size_t i = 0; i < mEffectChains.size(); i++) {
8036 mEffectChains[i]->lock();
8037 }
8038}
8039
8040void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008041 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008042{
8043 for (size_t i = 0; i < effectChains.size(); i++) {
8044 effectChains[i]->unlock();
8045 }
8046}
8047
8048sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8049{
8050 Mutex::Autolock _l(mLock);
8051 return getEffectChain_l(sessionId);
8052}
8053
Glenn Kasten106e8a42012-08-02 13:37:12 -07008054sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008055{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008056 size_t size = mEffectChains.size();
8057 for (size_t i = 0; i < size; i++) {
8058 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008059 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008060 }
8061 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008062 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008063}
8064
Glenn Kastenf78aee72012-01-04 11:00:47 -08008065void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008066{
8067 Mutex::Autolock _l(mLock);
8068 size_t size = mEffectChains.size();
8069 for (size_t i = 0; i < size; i++) {
8070 mEffectChains[i]->setMode_l(mode);
8071 }
8072}
8073
8074void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008075 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008076 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008077
Mathias Agopian65ab4712010-07-14 17:59:35 -07008078 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008079 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008080 // delete the effect module if removing last handle on it
8081 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008082 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008083 removeEffect_l(effect);
8084 AudioSystem::unregisterEffect(effect->id());
8085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008086 }
8087}
8088
8089status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8090{
8091 int session = chain->sessionId();
8092 int16_t *buffer = mMixBuffer;
8093 bool ownsBuffer = false;
8094
Steve Block3856b092011-10-20 11:56:00 +01008095 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008096 if (session > 0) {
8097 // Only one effect chain can be present in direct output thread and it uses
8098 // the mix buffer as input
8099 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008100 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008101 buffer = new int16_t[numSamples];
8102 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008103 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104 ownsBuffer = true;
8105 }
8106
8107 // Attach all tracks with same session ID to this chain.
8108 for (size_t i = 0; i < mTracks.size(); ++i) {
8109 sp<Track> track = mTracks[i];
8110 if (session == track->sessionId()) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07008111 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
8112 buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008113 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008114 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008115 }
8116 }
8117
8118 // indicate all active tracks in the chain
8119 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8120 sp<Track> track = mActiveTracks[i].promote();
8121 if (track == 0) continue;
8122 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008123 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008124 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008125 }
8126 }
8127 }
8128
8129 chain->setInBuffer(buffer, ownsBuffer);
8130 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008131 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008132 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008133 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8134 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008136 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8137 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008138 // Effect chain for other sessions are inserted at beginning of effect
8139 // chains list to be processed before output mix effects. Relative order between other
8140 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008141 size_t size = mEffectChains.size();
8142 size_t i = 0;
8143 for (i = 0; i < size; i++) {
8144 if (mEffectChains[i]->sessionId() < session) break;
8145 }
8146 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008147 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008148
8149 return NO_ERROR;
8150}
8151
8152size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8153{
8154 int session = chain->sessionId();
8155
Steve Block3856b092011-10-20 11:56:00 +01008156 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157
8158 for (size_t i = 0; i < mEffectChains.size(); i++) {
8159 if (chain == mEffectChains[i]) {
8160 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008161 // detach all active tracks from the chain
8162 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8163 sp<Track> track = mActiveTracks[i].promote();
8164 if (track == 0) continue;
8165 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008166 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008167 chain.get(), session);
8168 chain->decActiveTrackCnt();
8169 }
8170 }
8171
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172 // detach all tracks with same session ID from this chain
8173 for (size_t i = 0; i < mTracks.size(); ++i) {
8174 sp<Track> track = mTracks[i];
8175 if (session == track->sessionId()) {
8176 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008177 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008178 }
8179 }
Eric Laurentde070132010-07-13 04:45:46 -07008180 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181 }
8182 }
8183 return mEffectChains.size();
8184}
8185
Eric Laurentde070132010-07-13 04:45:46 -07008186status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8187 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188{
8189 Mutex::Autolock _l(mLock);
8190 return attachAuxEffect_l(track, EffectId);
8191}
8192
Eric Laurentde070132010-07-13 04:45:46 -07008193status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8194 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195{
8196 status_t status = NO_ERROR;
8197
8198 if (EffectId == 0) {
8199 track->setAuxBuffer(0, NULL);
8200 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008201 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8202 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008203 if (effect != 0) {
8204 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8205 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8206 } else {
8207 status = INVALID_OPERATION;
8208 }
8209 } else {
8210 status = BAD_VALUE;
8211 }
8212 }
8213 return status;
8214}
8215
8216void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8217{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008218 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 sp<Track> track = mTracks[i];
8220 if (track->auxEffectId() == effectId) {
8221 attachAuxEffect_l(track, 0);
8222 }
8223 }
8224}
8225
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008226status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8227{
8228 // only one chain per input thread
8229 if (mEffectChains.size() != 0) {
8230 return INVALID_OPERATION;
8231 }
Steve Block3856b092011-10-20 11:56:00 +01008232 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008233
8234 chain->setInBuffer(NULL);
8235 chain->setOutBuffer(NULL);
8236
Eric Laurent59255e42011-07-27 19:49:51 -07008237 checkSuspendOnAddEffectChain_l(chain);
8238
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008239 mEffectChains.add(chain);
8240
8241 return NO_ERROR;
8242}
8243
8244size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8245{
Steve Block3856b092011-10-20 11:56:00 +01008246 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008247 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008248 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8249 chain.get(), mEffectChains.size(), this);
8250 if (mEffectChains.size() == 1) {
8251 mEffectChains.removeAt(0);
8252 }
8253 return 0;
8254}
8255
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256// ----------------------------------------------------------------------------
8257// EffectModule implementation
8258// ----------------------------------------------------------------------------
8259
8260#undef LOG_TAG
8261#define LOG_TAG "AudioFlinger::EffectModule"
8262
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008263AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008264 const wp<AudioFlinger::EffectChain>& chain,
8265 effect_descriptor_t *desc,
8266 int id,
8267 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008268 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8269 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008270 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008271 // mConfig is set by configure() and not used before then
8272 mEffectInterface(NULL),
8273 mStatus(NO_INIT), mState(IDLE),
8274 // mMaxDisableWaitCnt is set by configure() and not used before then
8275 // mDisableWaitCnt is set by process() and updateState() and not used before then
8276 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008277{
Steve Block3856b092011-10-20 11:56:00 +01008278 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008279 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280
8281 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008282 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008283
8284 if (mStatus != NO_ERROR) {
8285 return;
8286 }
8287 lStatus = init();
8288 if (lStatus < 0) {
8289 mStatus = lStatus;
8290 goto Error;
8291 }
8292
Steve Block3856b092011-10-20 11:56:00 +01008293 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294 return;
8295Error:
8296 EffectRelease(mEffectInterface);
8297 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008298 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008299}
8300
8301AudioFlinger::EffectModule::~EffectModule()
8302{
Steve Block3856b092011-10-20 11:56:00 +01008303 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008305 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8306 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8307 sp<ThreadBase> thread = mThread.promote();
8308 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008309 audio_stream_t *stream = thread->stream();
8310 if (stream != NULL) {
8311 stream->remove_audio_effect(stream, mEffectInterface);
8312 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008313 }
8314 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008315 // release effect engine
8316 EffectRelease(mEffectInterface);
8317 }
8318}
8319
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008320status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008321{
8322 status_t status;
8323
8324 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008325 int priority = handle->priority();
8326 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008327 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008328 size_t i;
8329 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008330 EffectHandle *h = mHandles[i];
8331 if (h == NULL || h->destroyed_l()) continue;
8332 // first non destroyed handle is considered in control
8333 if (controlHandle == NULL)
8334 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335 if (h->priority() <= priority) break;
8336 }
8337 // if inserted in first place, move effect control from previous owner to this handle
8338 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008339 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008340 if (controlHandle != NULL) {
8341 enabled = controlHandle->enabled();
8342 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008343 }
Eric Laurent59255e42011-07-27 19:49:51 -07008344 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008345 status = NO_ERROR;
8346 } else {
8347 status = ALREADY_EXISTS;
8348 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008349 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008350 mHandles.insertAt(handle, i);
8351 return status;
8352}
8353
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008354size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355{
8356 Mutex::Autolock _l(mLock);
8357 size_t size = mHandles.size();
8358 size_t i;
8359 for (i = 0; i < size; i++) {
8360 if (mHandles[i] == handle) break;
8361 }
8362 if (i == size) {
8363 return size;
8364 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008365 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008366
Mathias Agopian65ab4712010-07-14 17:59:35 -07008367 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008368 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008369 if (i == 0) {
8370 EffectHandle *h = controlHandle_l();
8371 if (h != NULL) {
8372 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008373 }
8374 }
8375
Eric Laurentec437d82011-07-26 20:54:46 -07008376 // Prevent calls to process() and other functions on effect interface from now on.
8377 // The effect engine will be released by the destructor when the last strong reference on
8378 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008379 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008380 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008381 }
8382
Eric Laurente65c8912012-07-20 15:57:23 -07008383 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008384}
8385
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008386// must be called with EffectModule::mLock held
8387AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008388{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008389 // the first valid handle in the list has control over the module
8390 for (size_t i = 0; i < mHandles.size(); i++) {
8391 EffectHandle *h = mHandles[i];
8392 if (h != NULL && !h->destroyed_l()) {
8393 return h;
8394 }
8395 }
8396
8397 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008398}
8399
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008400size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008401{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008402 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008403 // keep a strong reference on this EffectModule to avoid calling the
8404 // destructor before we exit
8405 sp<EffectModule> keep(this);
8406 {
8407 sp<ThreadBase> thread = mThread.promote();
8408 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008409 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008410 }
8411 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008412 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413}
8414
8415void AudioFlinger::EffectModule::updateState() {
8416 Mutex::Autolock _l(mLock);
8417
8418 switch (mState) {
8419 case RESTART:
8420 reset_l();
8421 // FALL THROUGH
8422
8423 case STARTING:
8424 // clear auxiliary effect input buffer for next accumulation
8425 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8426 memset(mConfig.inputCfg.buffer.raw,
8427 0,
8428 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8429 }
8430 start_l();
8431 mState = ACTIVE;
8432 break;
8433 case STOPPING:
8434 stop_l();
8435 mDisableWaitCnt = mMaxDisableWaitCnt;
8436 mState = STOPPED;
8437 break;
8438 case STOPPED:
8439 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8440 // turn off sequence.
8441 if (--mDisableWaitCnt == 0) {
8442 reset_l();
8443 mState = IDLE;
8444 }
8445 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008446 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008447 break;
8448 }
8449}
8450
8451void AudioFlinger::EffectModule::process()
8452{
8453 Mutex::Autolock _l(mLock);
8454
Eric Laurentec437d82011-07-26 20:54:46 -07008455 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456 mConfig.inputCfg.buffer.raw == NULL ||
8457 mConfig.outputCfg.buffer.raw == NULL) {
8458 return;
8459 }
8460
Eric Laurent8f45bd72010-08-31 13:50:07 -07008461 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008462 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8463 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008464 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008466 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008467 }
8468
8469 // do the actual processing in the effect engine
8470 int ret = (*mEffectInterface)->process(mEffectInterface,
8471 &mConfig.inputCfg.buffer,
8472 &mConfig.outputCfg.buffer);
8473
8474 // force transition to IDLE state when engine is ready
8475 if (mState == STOPPED && ret == -ENODATA) {
8476 mDisableWaitCnt = 1;
8477 }
8478
8479 // clear auxiliary effect input buffer for next accumulation
8480 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008481 memset(mConfig.inputCfg.buffer.raw, 0,
8482 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008483 }
8484 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008485 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8486 // If an insert effect is idle and input buffer is different from output buffer,
8487 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008488 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008489 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008490 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8491 int16_t *in = mConfig.inputCfg.buffer.s16;
8492 int16_t *out = mConfig.outputCfg.buffer.s16;
8493 for (size_t i = 0; i < frameCnt; i++) {
8494 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008496 }
8497 }
8498}
8499
8500void AudioFlinger::EffectModule::reset_l()
8501{
8502 if (mEffectInterface == NULL) {
8503 return;
8504 }
8505 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8506}
8507
8508status_t AudioFlinger::EffectModule::configure()
8509{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008510 if (mEffectInterface == NULL) {
8511 return NO_INIT;
8512 }
8513
8514 sp<ThreadBase> thread = mThread.promote();
8515 if (thread == 0) {
8516 return DEAD_OBJECT;
8517 }
8518
8519 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008520 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008521
8522 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008523 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008524 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008525 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008526 }
Glenn Kasten254af182012-07-03 14:59:05 -07008527 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008528 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8529 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008530 mConfig.inputCfg.samplingRate = thread->sampleRate();
8531 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8532 mConfig.inputCfg.bufferProvider.cookie = NULL;
8533 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8534 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8535 mConfig.outputCfg.bufferProvider.cookie = NULL;
8536 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8537 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8538 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8539 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008540 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008541 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008542 // - in other sessions:
8543 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8544 // other effect: overwrites output buffer: input buffer == output buffer
8545 // Auxiliary effect:
8546 // accumulates in output buffer: input buffer != output buffer
8547 // Therefore: accumulate <=> input buffer != output buffer
8548 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8549 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8550 } else {
8551 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8552 }
8553 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8554 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8555 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8556 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8557
Steve Block3856b092011-10-20 11:56:00 +01008558 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008559 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8560
Mathias Agopian65ab4712010-07-14 17:59:35 -07008561 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008562 uint32_t size = sizeof(int);
8563 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008564 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008565 sizeof(effect_config_t),
8566 &mConfig,
8567 &size,
8568 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 if (status == 0) {
8570 status = cmdStatus;
8571 }
8572
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008573 if (status == 0 &&
8574 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8575 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8576 effect_param_t *p = (effect_param_t *)buf32;
8577
8578 p->psize = sizeof(uint32_t);
8579 p->vsize = sizeof(uint32_t);
8580 size = sizeof(int);
8581 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8582
8583 uint32_t latency = 0;
8584 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8585 if (pbt != NULL) {
8586 latency = pbt->latency_l();
8587 }
8588
8589 *((int32_t *)p->data + 1)= latency;
8590 (*mEffectInterface)->command(mEffectInterface,
8591 EFFECT_CMD_SET_PARAM,
8592 sizeof(effect_param_t) + 8,
8593 &buf32,
8594 &size,
8595 &cmdStatus);
8596 }
8597
Mathias Agopian65ab4712010-07-14 17:59:35 -07008598 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8599 (1000 * mConfig.outputCfg.buffer.frameCount);
8600
8601 return status;
8602}
8603
8604status_t AudioFlinger::EffectModule::init()
8605{
8606 Mutex::Autolock _l(mLock);
8607 if (mEffectInterface == NULL) {
8608 return NO_INIT;
8609 }
8610 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008611 uint32_t size = sizeof(status_t);
8612 status_t status = (*mEffectInterface)->command(mEffectInterface,
8613 EFFECT_CMD_INIT,
8614 0,
8615 NULL,
8616 &size,
8617 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618 if (status == 0) {
8619 status = cmdStatus;
8620 }
8621 return status;
8622}
8623
Eric Laurentec35a142011-10-05 17:42:25 -07008624status_t AudioFlinger::EffectModule::start()
8625{
8626 Mutex::Autolock _l(mLock);
8627 return start_l();
8628}
8629
Mathias Agopian65ab4712010-07-14 17:59:35 -07008630status_t AudioFlinger::EffectModule::start_l()
8631{
8632 if (mEffectInterface == NULL) {
8633 return NO_INIT;
8634 }
8635 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008636 uint32_t size = sizeof(status_t);
8637 status_t status = (*mEffectInterface)->command(mEffectInterface,
8638 EFFECT_CMD_ENABLE,
8639 0,
8640 NULL,
8641 &size,
8642 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008643 if (status == 0) {
8644 status = cmdStatus;
8645 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008646 if (status == 0 &&
8647 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8648 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8649 sp<ThreadBase> thread = mThread.promote();
8650 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008651 audio_stream_t *stream = thread->stream();
8652 if (stream != NULL) {
8653 stream->add_audio_effect(stream, mEffectInterface);
8654 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008655 }
8656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008657 return status;
8658}
8659
Eric Laurentec437d82011-07-26 20:54:46 -07008660status_t AudioFlinger::EffectModule::stop()
8661{
8662 Mutex::Autolock _l(mLock);
8663 return stop_l();
8664}
8665
Mathias Agopian65ab4712010-07-14 17:59:35 -07008666status_t AudioFlinger::EffectModule::stop_l()
8667{
8668 if (mEffectInterface == NULL) {
8669 return NO_INIT;
8670 }
8671 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008672 uint32_t size = sizeof(status_t);
8673 status_t status = (*mEffectInterface)->command(mEffectInterface,
8674 EFFECT_CMD_DISABLE,
8675 0,
8676 NULL,
8677 &size,
8678 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008679 if (status == 0) {
8680 status = cmdStatus;
8681 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008682 if (status == 0 &&
8683 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8684 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8685 sp<ThreadBase> thread = mThread.promote();
8686 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008687 audio_stream_t *stream = thread->stream();
8688 if (stream != NULL) {
8689 stream->remove_audio_effect(stream, mEffectInterface);
8690 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008691 }
8692 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008693 return status;
8694}
8695
Eric Laurent25f43952010-07-28 05:40:18 -07008696status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8697 uint32_t cmdSize,
8698 void *pCmdData,
8699 uint32_t *replySize,
8700 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008701{
8702 Mutex::Autolock _l(mLock);
Glenn Kastencbe4b362012-10-18 15:51:03 -07008703 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008704
Eric Laurentec437d82011-07-26 20:54:46 -07008705 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008706 return NO_INIT;
8707 }
Eric Laurent25f43952010-07-28 05:40:18 -07008708 status_t status = (*mEffectInterface)->command(mEffectInterface,
8709 cmdCode,
8710 cmdSize,
8711 pCmdData,
8712 replySize,
8713 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008714 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008715 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008716 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008717 EffectHandle *h = mHandles[i];
8718 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008719 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8720 }
8721 }
8722 }
8723 return status;
8724}
8725
8726status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8727{
8728 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008729 return setEnabled_l(enabled);
8730}
8731
8732// must be called with EffectModule::mLock held
8733status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8734{
8735
Steve Block3856b092011-10-20 11:56:00 +01008736 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008737
8738 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008739 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8740 if (enabled && status != NO_ERROR) {
8741 return status;
8742 }
8743
Mathias Agopian65ab4712010-07-14 17:59:35 -07008744 switch (mState) {
8745 // going from disabled to enabled
8746 case IDLE:
8747 mState = STARTING;
8748 break;
8749 case STOPPED:
8750 mState = RESTART;
8751 break;
8752 case STOPPING:
8753 mState = ACTIVE;
8754 break;
8755
8756 // going from enabled to disabled
8757 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008758 mState = STOPPED;
8759 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760 case STARTING:
8761 mState = IDLE;
8762 break;
8763 case ACTIVE:
8764 mState = STOPPING;
8765 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008766 case DESTROYED:
8767 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008768 }
8769 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008770 EffectHandle *h = mHandles[i];
8771 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008772 h->setEnabled(enabled);
8773 }
8774 }
8775 }
8776 return NO_ERROR;
8777}
8778
Glenn Kastenc59c0042012-02-02 14:06:11 -08008779bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008780{
8781 switch (mState) {
8782 case RESTART:
8783 case STARTING:
8784 case ACTIVE:
8785 return true;
8786 case IDLE:
8787 case STOPPING:
8788 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008789 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790 default:
8791 return false;
8792 }
8793}
8794
Glenn Kastenc59c0042012-02-02 14:06:11 -08008795bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008796{
8797 switch (mState) {
8798 case RESTART:
8799 case ACTIVE:
8800 case STOPPING:
8801 case STOPPED:
8802 return true;
8803 case IDLE:
8804 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008805 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008806 default:
8807 return false;
8808 }
8809}
8810
Mathias Agopian65ab4712010-07-14 17:59:35 -07008811status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8812{
8813 Mutex::Autolock _l(mLock);
8814 status_t status = NO_ERROR;
8815
8816 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8817 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008818 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008819 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8820 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821 status_t cmdStatus;
8822 uint32_t volume[2];
8823 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008824 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008825 volume[0] = *left;
8826 volume[1] = *right;
8827 if (controller) {
8828 pVolume = volume;
8829 }
Eric Laurent25f43952010-07-28 05:40:18 -07008830 status = (*mEffectInterface)->command(mEffectInterface,
8831 EFFECT_CMD_SET_VOLUME,
8832 size,
8833 volume,
8834 &size,
8835 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008836 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8837 *left = volume[0];
8838 *right = volume[1];
8839 }
8840 }
8841 return status;
8842}
8843
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008844status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008845{
Eric Laurent88959252012-08-28 14:26:53 -07008846 if (device == AUDIO_DEVICE_NONE) {
8847 return NO_ERROR;
8848 }
8849
Mathias Agopian65ab4712010-07-14 17:59:35 -07008850 Mutex::Autolock _l(mLock);
8851 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008852 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurent88959252012-08-28 14:26:53 -07008853 status_t cmdStatus;
8854 uint32_t size = sizeof(status_t);
8855 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8856 EFFECT_CMD_SET_INPUT_DEVICE;
8857 status = (*mEffectInterface)->command(mEffectInterface,
8858 cmd,
8859 sizeof(uint32_t),
8860 &device,
8861 &size,
8862 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008863 }
8864 return status;
8865}
8866
Glenn Kastenf78aee72012-01-04 11:00:47 -08008867status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868{
8869 Mutex::Autolock _l(mLock);
8870 status_t status = NO_ERROR;
8871 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008872 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008873 uint32_t size = sizeof(status_t);
8874 status = (*mEffectInterface)->command(mEffectInterface,
8875 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008876 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008877 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008878 &size,
8879 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008880 if (status == NO_ERROR) {
8881 status = cmdStatus;
8882 }
8883 }
8884 return status;
8885}
8886
Eric Laurent2e9b0f22012-08-31 17:44:06 -07008887status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8888{
8889 Mutex::Autolock _l(mLock);
8890 status_t status = NO_ERROR;
8891 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8892 uint32_t size = 0;
8893 status = (*mEffectInterface)->command(mEffectInterface,
8894 EFFECT_CMD_SET_AUDIO_SOURCE,
8895 sizeof(audio_source_t),
8896 &source,
8897 &size,
8898 NULL);
8899 }
8900 return status;
8901}
8902
Eric Laurent59255e42011-07-27 19:49:51 -07008903void AudioFlinger::EffectModule::setSuspended(bool suspended)
8904{
8905 Mutex::Autolock _l(mLock);
8906 mSuspended = suspended;
8907}
Glenn Kastena3a85482012-01-04 11:01:11 -08008908
8909bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008910{
8911 Mutex::Autolock _l(mLock);
8912 return mSuspended;
8913}
8914
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008915bool AudioFlinger::EffectModule::purgeHandles()
8916{
8917 bool enabled = false;
8918 Mutex::Autolock _l(mLock);
8919 for (size_t i = 0; i < mHandles.size(); i++) {
8920 EffectHandle *handle = mHandles[i];
8921 if (handle != NULL && !handle->destroyed_l()) {
8922 handle->effect().clear();
8923 if (handle->hasControl()) {
8924 enabled = handle->enabled();
8925 }
8926 }
8927 }
8928 return enabled;
8929}
8930
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008931void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008932{
8933 const size_t SIZE = 256;
8934 char buffer[SIZE];
8935 String8 result;
8936
8937 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8938 result.append(buffer);
8939
8940 bool locked = tryLock(mLock);
8941 // failed to lock - AudioFlinger is probably deadlocked
8942 if (!locked) {
8943 result.append("\t\tCould not lock Fx mutex:\n");
8944 }
8945
8946 result.append("\t\tSession Status State Engine:\n");
8947 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8948 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8949 result.append(buffer);
8950
8951 result.append("\t\tDescriptor:\n");
8952 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8953 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
Glenn Kasten8af901c2012-11-01 11:11:38 -07008954 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],
8955 mDescriptor.uuid.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07008956 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8957 result.append(buffer);
8958 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
Glenn Kasten8af901c2012-11-01 11:11:38 -07008959 mDescriptor.type.timeLow, mDescriptor.type.timeMid,
8960 mDescriptor.type.timeHiAndVersion,
8961 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],
8962 mDescriptor.type.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07008963 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8964 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008965 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008966 mDescriptor.apiVersion,
8967 mDescriptor.flags);
8968 result.append(buffer);
8969 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8970 mDescriptor.name);
8971 result.append(buffer);
8972 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8973 mDescriptor.implementor);
8974 result.append(buffer);
8975
8976 result.append("\t\t- Input configuration:\n");
8977 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8978 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8979 (uint32_t)mConfig.inputCfg.buffer.raw,
8980 mConfig.inputCfg.buffer.frameCount,
8981 mConfig.inputCfg.samplingRate,
8982 mConfig.inputCfg.channels,
8983 mConfig.inputCfg.format);
8984 result.append(buffer);
8985
8986 result.append("\t\t- Output configuration:\n");
8987 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8988 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8989 (uint32_t)mConfig.outputCfg.buffer.raw,
8990 mConfig.outputCfg.buffer.frameCount,
8991 mConfig.outputCfg.samplingRate,
8992 mConfig.outputCfg.channels,
8993 mConfig.outputCfg.format);
8994 result.append(buffer);
8995
8996 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8997 result.append(buffer);
8998 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8999 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009000 EffectHandle *handle = mHandles[i];
9001 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002 handle->dump(buffer, SIZE);
9003 result.append(buffer);
9004 }
9005 }
9006
9007 result.append("\n");
9008
9009 write(fd, result.string(), result.length());
9010
9011 if (locked) {
9012 mLock.unlock();
9013 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014}
9015
9016// ----------------------------------------------------------------------------
9017// EffectHandle implementation
9018// ----------------------------------------------------------------------------
9019
9020#undef LOG_TAG
9021#define LOG_TAG "AudioFlinger::EffectHandle"
9022
9023AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9024 const sp<AudioFlinger::Client>& client,
9025 const sp<IEffectClient>& effectClient,
9026 int32_t priority)
9027 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009028 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009029 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030{
Steve Block3856b092011-10-20 11:56:00 +01009031 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009033 if (client == 0) {
9034 return;
9035 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009036 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9037 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9038 if (mCblkMemory != 0) {
9039 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9040
Glenn Kastena0d68332012-01-27 16:47:15 -08009041 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009042 new(mCblk) effect_param_cblk_t();
9043 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009045 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07009046 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE +
9047 sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009048 return;
9049 }
9050}
9051
9052AudioFlinger::EffectHandle::~EffectHandle()
9053{
Steve Block3856b092011-10-20 11:56:00 +01009054 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009055
9056 if (mEffect == 0) {
9057 mDestroyed = true;
9058 return;
9059 }
9060 mEffect->lock();
9061 mDestroyed = true;
9062 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009063 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009064}
9065
9066status_t AudioFlinger::EffectHandle::enable()
9067{
Steve Block3856b092011-10-20 11:56:00 +01009068 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009069 if (!mHasControl) return INVALID_OPERATION;
9070 if (mEffect == 0) return DEAD_OBJECT;
9071
Eric Laurentdb7c0792011-08-10 10:37:50 -07009072 if (mEnabled) {
9073 return NO_ERROR;
9074 }
9075
Eric Laurent59255e42011-07-27 19:49:51 -07009076 mEnabled = true;
9077
9078 sp<ThreadBase> thread = mEffect->thread().promote();
9079 if (thread != 0) {
9080 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9081 }
9082
9083 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9084 if (mEffect->suspended()) {
9085 return NO_ERROR;
9086 }
9087
Eric Laurentdb7c0792011-08-10 10:37:50 -07009088 status_t status = mEffect->setEnabled(true);
9089 if (status != NO_ERROR) {
9090 if (thread != 0) {
9091 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9092 }
9093 mEnabled = false;
9094 }
9095 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009096}
9097
9098status_t AudioFlinger::EffectHandle::disable()
9099{
Steve Block3856b092011-10-20 11:56:00 +01009100 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009101 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009102 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009103
Eric Laurentdb7c0792011-08-10 10:37:50 -07009104 if (!mEnabled) {
9105 return NO_ERROR;
9106 }
Eric Laurent59255e42011-07-27 19:49:51 -07009107 mEnabled = false;
9108
9109 if (mEffect->suspended()) {
9110 return NO_ERROR;
9111 }
9112
9113 status_t status = mEffect->setEnabled(false);
9114
9115 sp<ThreadBase> thread = mEffect->thread().promote();
9116 if (thread != 0) {
9117 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9118 }
9119
9120 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009121}
9122
9123void AudioFlinger::EffectHandle::disconnect()
9124{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009125 disconnect(true);
9126}
9127
Glenn Kasten58123c32012-02-03 10:32:24 -08009128void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009129{
Glenn Kasten58123c32012-02-03 10:32:24 -08009130 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009131 if (mEffect == 0) {
9132 return;
9133 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009134 // restore suspended effects if the disconnected handle was enabled and the last one.
9135 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009136 sp<ThreadBase> thread = mEffect->thread().promote();
9137 if (thread != 0) {
9138 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9139 }
Eric Laurent59255e42011-07-27 19:49:51 -07009140 }
9141
Mathias Agopian65ab4712010-07-14 17:59:35 -07009142 // release sp on module => module destructor can be called now
9143 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009144 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009145 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009146 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009147 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9148 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009149 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009150 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009151 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9152 mClient.clear();
9153 }
9154}
9155
Eric Laurent25f43952010-07-28 05:40:18 -07009156status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9157 uint32_t cmdSize,
9158 void *pCmdData,
9159 uint32_t *replySize,
9160 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009161{
Glenn Kastencbe4b362012-10-18 15:51:03 -07009162 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
9163 cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164
9165 // only get parameter command is permitted for applications not controlling the effect
9166 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9167 return INVALID_OPERATION;
9168 }
9169 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009170 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009171
9172 // handle commands that are not forwarded transparently to effect engine
9173 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07009174 // No need to trylock() here as this function is executed in the binder thread serving a
9175 // particular client process: no risk to block the whole media server process or mixer
9176 // threads if we are stuck here
Mathias Agopian65ab4712010-07-14 17:59:35 -07009177 Mutex::Autolock _l(mCblk->lock);
9178 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9179 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9180 mCblk->serverIndex = 0;
9181 mCblk->clientIndex = 0;
9182 return BAD_VALUE;
9183 }
9184 status_t status = NO_ERROR;
9185 while (mCblk->serverIndex < mCblk->clientIndex) {
9186 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009187 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009188 int *p = (int *)(mBuffer + mCblk->serverIndex);
9189 int size = *p++;
9190 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009191 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009192 break;
9193 }
9194 effect_param_t *param = (effect_param_t *)p;
9195 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009196 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009197 mCblk->serverIndex += size;
9198 continue;
9199 }
Eric Laurent25f43952010-07-28 05:40:18 -07009200 uint32_t psize = sizeof(effect_param_t) +
9201 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9202 param->vsize;
9203 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9204 psize,
9205 p,
9206 &rsize,
9207 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009208 // stop at first error encountered
9209 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009210 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009211 *(int *)pReplyData = reply;
9212 break;
9213 } else if (reply != NO_ERROR) {
9214 *(int *)pReplyData = reply;
9215 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009216 }
9217 mCblk->serverIndex += size;
9218 }
9219 mCblk->serverIndex = 0;
9220 mCblk->clientIndex = 0;
9221 return status;
9222 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009223 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224 return enable();
9225 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009226 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009227 return disable();
9228 }
9229
9230 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9231}
9232
Eric Laurent59255e42011-07-27 19:49:51 -07009233void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234{
Steve Block3856b092011-10-20 11:56:00 +01009235 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009236
9237 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009238 mEnabled = enabled;
9239
Mathias Agopian65ab4712010-07-14 17:59:35 -07009240 if (signal && mEffectClient != 0) {
9241 mEffectClient->controlStatusChanged(hasControl);
9242 }
9243}
9244
Eric Laurent25f43952010-07-28 05:40:18 -07009245void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9246 uint32_t cmdSize,
9247 void *pCmdData,
9248 uint32_t replySize,
9249 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009250{
9251 if (mEffectClient != 0) {
9252 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9253 }
9254}
9255
9256
9257
9258void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9259{
9260 if (mEffectClient != 0) {
9261 mEffectClient->enableStatusChanged(enabled);
9262 }
9263}
9264
9265status_t AudioFlinger::EffectHandle::onTransact(
9266 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9267{
9268 return BnEffect::onTransact(code, data, reply, flags);
9269}
9270
9271
9272void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9273{
Glenn Kastena0d68332012-01-27 16:47:15 -08009274 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009275
9276 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009277 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009278 mPriority,
9279 mHasControl,
9280 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009281 mCblk ? mCblk->clientIndex : 0,
9282 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009283 );
9284
9285 if (locked) {
9286 mCblk->lock.unlock();
9287 }
9288}
9289
9290#undef LOG_TAG
9291#define LOG_TAG "AudioFlinger::EffectChain"
9292
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009293AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009294 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009295 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009296 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9297 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009298{
Dima Zavinfce7a472011-04-19 22:30:36 -07009299 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009300 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009301 return;
9302 }
9303 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9304 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009305}
9306
9307AudioFlinger::EffectChain::~EffectChain()
9308{
9309 if (mOwnInBuffer) {
9310 delete mInBuffer;
9311 }
9312
9313}
9314
Eric Laurent59255e42011-07-27 19:49:51 -07009315// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Glenn Kasten8af901c2012-11-01 11:11:38 -07009316sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
9317 effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009318{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009319 size_t size = mEffects.size();
9320
9321 for (size_t i = 0; i < size; i++) {
9322 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009323 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009324 }
9325 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009326 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009327}
9328
Eric Laurent59255e42011-07-27 19:49:51 -07009329// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009330sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009331{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009332 size_t size = mEffects.size();
9333
9334 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009335 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9336 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009337 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009338 }
9339 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009340 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009341}
9342
Eric Laurent59255e42011-07-27 19:49:51 -07009343// getEffectFromType_l() must be called with ThreadBase::mLock held
9344sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9345 const effect_uuid_t *type)
9346{
Eric Laurent59255e42011-07-27 19:49:51 -07009347 size_t size = mEffects.size();
9348
9349 for (size_t i = 0; i < size; i++) {
9350 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009351 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009352 }
9353 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009354 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009355}
9356
Eric Laurent91b14c42012-05-30 12:30:29 -07009357void AudioFlinger::EffectChain::clearInputBuffer()
9358{
9359 Mutex::Autolock _l(mLock);
9360 sp<ThreadBase> thread = mThread.promote();
9361 if (thread == 0) {
9362 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9363 return;
9364 }
9365 clearInputBuffer_l(thread);
9366}
9367
9368// Must be called with EffectChain::mLock locked
9369void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9370{
9371 size_t numSamples = thread->frameCount() * thread->channelCount();
9372 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9373
9374}
9375
Mathias Agopian65ab4712010-07-14 17:59:35 -07009376// Must be called with EffectChain::mLock locked
9377void AudioFlinger::EffectChain::process_l()
9378{
Eric Laurentdac69112010-09-28 14:09:57 -07009379 sp<ThreadBase> thread = mThread.promote();
9380 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009381 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009382 return;
9383 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009384 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9385 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009386 // always process effects unless no more tracks are on the session and the effect tail
9387 // has been rendered
9388 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009389 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009390 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009391
Eric Laurent544fe9b2011-11-11 15:42:52 -08009392 if (!tracksOnSession && mTailBufferCount == 0) {
9393 doProcess = false;
9394 }
9395
9396 if (activeTrackCnt() == 0) {
9397 // if no track is active and the effect tail has not been rendered,
9398 // the input buffer must be cleared here as the mixer process will not do it
9399 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009400 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009401 if (mTailBufferCount > 0) {
9402 mTailBufferCount--;
9403 }
9404 }
9405 }
Eric Laurentdac69112010-09-28 14:09:57 -07009406 }
9407
Mathias Agopian65ab4712010-07-14 17:59:35 -07009408 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009409 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009410 for (size_t i = 0; i < size; i++) {
9411 mEffects[i]->process();
9412 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009413 }
9414 for (size_t i = 0; i < size; i++) {
9415 mEffects[i]->updateState();
9416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009417}
9418
Eric Laurentcab11242010-07-15 12:50:15 -07009419// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009420status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009421{
9422 effect_descriptor_t desc = effect->desc();
9423 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9424
9425 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009426 effect->setChain(this);
9427 sp<ThreadBase> thread = mThread.promote();
9428 if (thread == 0) {
9429 return NO_INIT;
9430 }
9431 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009432
9433 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9434 // Auxiliary effects are inserted at the beginning of mEffects vector as
9435 // they are processed first and accumulated in chain input buffer
9436 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009437
Mathias Agopian65ab4712010-07-14 17:59:35 -07009438 // the input buffer for auxiliary effect contains mono samples in
9439 // 32 bit format. This is to avoid saturation in AudoMixer
9440 // accumulation stage. Saturation is done in EffectModule::process() before
9441 // calling the process in effect engine
9442 size_t numSamples = thread->frameCount();
9443 int32_t *buffer = new int32_t[numSamples];
9444 memset(buffer, 0, numSamples * sizeof(int32_t));
9445 effect->setInBuffer((int16_t *)buffer);
9446 // auxiliary effects output samples to chain input buffer for further processing
9447 // by insert effects
9448 effect->setOutBuffer(mInBuffer);
9449 } else {
9450 // Insert effects are inserted at the end of mEffects vector as they are processed
9451 // after track and auxiliary effects.
9452 // Insert effect order as a function of indicated preference:
9453 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9454 // another effect is present
9455 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9456 // last effect claiming first position
9457 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9458 // first effect claiming last position
9459 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9460 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9461 // already present
9462
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009463 size_t size = mEffects.size();
9464 size_t idx_insert = size;
9465 ssize_t idx_insert_first = -1;
9466 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009467
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009468 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009469 effect_descriptor_t d = mEffects[i]->desc();
9470 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9471 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9472 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9473 // check invalid effect chaining combinations
9474 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9475 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07009476 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
9477 desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009478 return INVALID_OPERATION;
9479 }
9480 // remember position of first insert effect and by default
9481 // select this as insert position for new effect
9482 if (idx_insert == size) {
9483 idx_insert = i;
9484 }
9485 // remember position of last insert effect claiming
9486 // first position
9487 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9488 idx_insert_first = i;
9489 }
9490 // remember position of first insert effect claiming
9491 // last position
9492 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9493 idx_insert_last == -1) {
9494 idx_insert_last = i;
9495 }
9496 }
9497 }
9498
9499 // modify idx_insert from first position if needed
9500 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9501 if (idx_insert_last != -1) {
9502 idx_insert = idx_insert_last;
9503 } else {
9504 idx_insert = size;
9505 }
9506 } else {
9507 if (idx_insert_first != -1) {
9508 idx_insert = idx_insert_first + 1;
9509 }
9510 }
9511
9512 // always read samples from chain input buffer
9513 effect->setInBuffer(mInBuffer);
9514
9515 // if last effect in the chain, output samples to chain
9516 // output buffer, otherwise to chain input buffer
9517 if (idx_insert == size) {
9518 if (idx_insert != 0) {
9519 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9520 mEffects[idx_insert-1]->configure();
9521 }
9522 effect->setOutBuffer(mOutBuffer);
9523 } else {
9524 effect->setOutBuffer(mInBuffer);
9525 }
9526 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009527
Glenn Kasten8af901c2012-11-01 11:11:38 -07009528 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this,
9529 idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009530 }
9531 effect->configure();
9532 return NO_ERROR;
9533}
9534
Eric Laurentcab11242010-07-15 12:50:15 -07009535// removeEffect_l() must be called with PlaybackThread::mLock held
9536size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009537{
9538 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009539 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009540 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9541
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009542 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009543 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009544 // calling stop here will remove pre-processing effect from the audio HAL.
9545 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9546 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009547 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9548 mEffects[i]->state() == EffectModule::STOPPING) {
9549 mEffects[i]->stop();
9550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009551 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9552 delete[] effect->inBuffer();
9553 } else {
9554 if (i == size - 1 && i != 0) {
9555 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9556 mEffects[i - 1]->configure();
9557 }
9558 }
9559 mEffects.removeAt(i);
Glenn Kasten8af901c2012-11-01 11:11:38 -07009560 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(),
9561 this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009562 break;
9563 }
9564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009565
9566 return mEffects.size();
9567}
9568
Eric Laurentcab11242010-07-15 12:50:15 -07009569// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009570void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009571{
9572 size_t size = mEffects.size();
9573 for (size_t i = 0; i < size; i++) {
9574 mEffects[i]->setDevice(device);
9575 }
9576}
9577
Eric Laurentcab11242010-07-15 12:50:15 -07009578// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009579void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009580{
9581 size_t size = mEffects.size();
9582 for (size_t i = 0; i < size; i++) {
9583 mEffects[i]->setMode(mode);
9584 }
9585}
9586
Eric Laurent2e9b0f22012-08-31 17:44:06 -07009587// setAudioSource_l() must be called with PlaybackThread::mLock held
9588void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9589{
9590 size_t size = mEffects.size();
9591 for (size_t i = 0; i < size; i++) {
9592 mEffects[i]->setAudioSource(source);
9593 }
9594}
9595
Eric Laurentcab11242010-07-15 12:50:15 -07009596// setVolume_l() must be called with PlaybackThread::mLock held
9597bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009598{
9599 uint32_t newLeft = *left;
9600 uint32_t newRight = *right;
9601 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009602 int ctrlIdx = -1;
9603 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009604
Eric Laurentcab11242010-07-15 12:50:15 -07009605 // first update volume controller
9606 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009607 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009608 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9609 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009610 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009611 break;
9612 }
9613 }
9614
9615 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009616 if (hasControl) {
9617 *left = mNewLeftVolume;
9618 *right = mNewRightVolume;
9619 }
9620 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009621 }
9622
9623 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009624 mLeftVolume = newLeft;
9625 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009626
9627 // second get volume update from volume controller
9628 if (ctrlIdx >= 0) {
9629 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009630 mNewLeftVolume = newLeft;
9631 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009632 }
9633 // then indicate volume to all other effects in chain.
9634 // Pass altered volume to effects before volume controller
9635 // and requested volume to effects after controller
9636 uint32_t lVol = newLeft;
9637 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009638
Mathias Agopian65ab4712010-07-14 17:59:35 -07009639 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009640 if ((int)i == ctrlIdx) continue;
9641 // this also works for ctrlIdx == -1 when there is no volume controller
9642 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009643 lVol = *left;
9644 rVol = *right;
9645 }
9646 mEffects[i]->setVolume(&lVol, &rVol, false);
9647 }
9648 *left = newLeft;
9649 *right = newRight;
9650
9651 return hasControl;
9652}
9653
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009654void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009655{
9656 const size_t SIZE = 256;
9657 char buffer[SIZE];
9658 String8 result;
9659
9660 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9661 result.append(buffer);
9662
9663 bool locked = tryLock(mLock);
9664 // failed to lock - AudioFlinger is probably deadlocked
9665 if (!locked) {
9666 result.append("\tCould not lock mutex:\n");
9667 }
9668
Eric Laurentcab11242010-07-15 12:50:15 -07009669 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9670 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009671 mEffects.size(),
9672 (uint32_t)mInBuffer,
9673 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009674 mActiveTrackCnt);
9675 result.append(buffer);
9676 write(fd, result.string(), result.size());
9677
9678 for (size_t i = 0; i < mEffects.size(); ++i) {
9679 sp<EffectModule> effect = mEffects[i];
9680 if (effect != 0) {
9681 effect->dump(fd, args);
9682 }
9683 }
9684
9685 if (locked) {
9686 mLock.unlock();
9687 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009688}
9689
Eric Laurent59255e42011-07-27 19:49:51 -07009690// must be called with ThreadBase::mLock held
9691void AudioFlinger::EffectChain::setEffectSuspended_l(
9692 const effect_uuid_t *type, bool suspend)
9693{
9694 sp<SuspendedEffectDesc> desc;
9695 // use effect type UUID timelow as key as there is no real risk of identical
9696 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009697 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009698 if (suspend) {
9699 if (index >= 0) {
9700 desc = mSuspendedEffects.valueAt(index);
9701 } else {
9702 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009703 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009704 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009705 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009706 }
9707 if (desc->mRefCount++ == 0) {
9708 sp<EffectModule> effect = getEffectIfEnabled(type);
9709 if (effect != 0) {
9710 desc->mEffect = effect;
9711 effect->setSuspended(true);
9712 effect->setEnabled(false);
9713 }
9714 }
9715 } else {
9716 if (index < 0) {
9717 return;
9718 }
9719 desc = mSuspendedEffects.valueAt(index);
9720 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009721 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009722 desc->mRefCount = 1;
9723 }
9724 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009725 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009726 if (desc->mEffect != 0) {
9727 sp<EffectModule> effect = desc->mEffect.promote();
9728 if (effect != 0) {
9729 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009730 effect->lock();
9731 EffectHandle *handle = effect->controlHandle_l();
9732 if (handle != NULL && !handle->destroyed_l()) {
9733 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009734 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009735 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009736 }
9737 desc->mEffect.clear();
9738 }
9739 mSuspendedEffects.removeItemsAt(index);
9740 }
9741 }
9742}
9743
9744// must be called with ThreadBase::mLock held
9745void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9746{
9747 sp<SuspendedEffectDesc> desc;
9748
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009749 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009750 if (suspend) {
9751 if (index >= 0) {
9752 desc = mSuspendedEffects.valueAt(index);
9753 } else {
9754 desc = new SuspendedEffectDesc();
9755 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009756 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009757 }
9758 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009759 Vector< sp<EffectModule> > effects;
9760 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009761 for (size_t i = 0; i < effects.size(); i++) {
9762 setEffectSuspended_l(&effects[i]->desc().type, true);
9763 }
9764 }
9765 } else {
9766 if (index < 0) {
9767 return;
9768 }
9769 desc = mSuspendedEffects.valueAt(index);
9770 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009771 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009772 desc->mRefCount = 1;
9773 }
9774 if (--desc->mRefCount == 0) {
9775 Vector<const effect_uuid_t *> types;
9776 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9777 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9778 continue;
9779 }
9780 types.add(&mSuspendedEffects.valueAt(i)->mType);
9781 }
9782 for (size_t i = 0; i < types.size(); i++) {
9783 setEffectSuspended_l(types[i], false);
9784 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07009785 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
9786 mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009787 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9788 }
9789 }
9790}
9791
Eric Laurent6bffdb82011-09-23 08:40:41 -07009792
9793// The volume effect is used for automated tests only
9794#ifndef OPENSL_ES_H_
9795static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9796 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9797const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9798#endif //OPENSL_ES_H_
9799
Eric Laurentdb7c0792011-08-10 10:37:50 -07009800bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9801{
9802 // auxiliary effects and visualizer are never suspended on output mix
9803 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9804 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009805 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9806 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009807 return false;
9808 }
9809 return true;
9810}
9811
Glenn Kasten8af901c2012-11-01 11:11:38 -07009812void AudioFlinger::EffectChain::getSuspendEligibleEffects(
9813 Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009814{
Glenn Kastend0539712012-01-30 12:56:03 -08009815 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009816 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009817 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9818 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009819 }
Eric Laurent59255e42011-07-27 19:49:51 -07009820 }
Eric Laurent59255e42011-07-27 19:49:51 -07009821}
9822
9823sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9824 const effect_uuid_t *type)
9825{
Glenn Kasten090f0192012-01-30 13:00:02 -08009826 sp<EffectModule> effect = getEffectFromType_l(type);
9827 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009828}
9829
9830void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9831 bool enabled)
9832{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009833 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009834 if (enabled) {
9835 if (index < 0) {
9836 // if the effect is not suspend check if all effects are suspended
9837 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9838 if (index < 0) {
9839 return;
9840 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009841 if (!isEffectEligibleForSuspend(effect->desc())) {
9842 return;
9843 }
Eric Laurent59255e42011-07-27 19:49:51 -07009844 setEffectSuspended_l(&effect->desc().type, enabled);
9845 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009846 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009847 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009848 return;
9849 }
Eric Laurent59255e42011-07-27 19:49:51 -07009850 }
Steve Block3856b092011-10-20 11:56:00 +01009851 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009852 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009853 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9854 // if effect is requested to suspended but was not yet enabled, supend it now.
9855 if (desc->mEffect == 0) {
9856 desc->mEffect = effect;
9857 effect->setEnabled(false);
9858 effect->setSuspended(true);
9859 }
9860 } else {
9861 if (index < 0) {
9862 return;
9863 }
Steve Block3856b092011-10-20 11:56:00 +01009864 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009865 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009866 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9867 desc->mEffect.clear();
9868 effect->setSuspended(false);
9869 }
9870}
9871
Mathias Agopian65ab4712010-07-14 17:59:35 -07009872#undef LOG_TAG
9873#define LOG_TAG "AudioFlinger"
9874
9875// ----------------------------------------------------------------------------
9876
9877status_t AudioFlinger::onTransact(
9878 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9879{
9880 return BnAudioFlinger::onTransact(code, data, reply, flags);
9881}
9882
Mathias Agopian65ab4712010-07-14 17:59:35 -07009883}; // namespace android