blob: 0c1ab3ce5e9c918696d1a9a71911709742262149 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070079#include <media/nbaio/AudioStreamOutSink.h>
80#include <media/nbaio/MonoPipe.h>
81#include <media/nbaio/MonoPipeReader.h>
82#include <media/nbaio/Pipe.h>
83#include <media/nbaio/PipeReader.h>
84#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070085
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Glenn Kasten3ed29202012-08-07 15:24:44 -0700168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
170// Currently the client uses double-buffering by default, but doesn't tell us about that.
171// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
173// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700174// See the client's minBufCount and mNotificationFramesAct calculations for details.
175static const int kFastTrackMultiplier = 2;
176
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177// ----------------------------------------------------------------------------
178
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700179#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800180// To collect the amplifier usage
181static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800182 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
183 if (service == NULL) {
184 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800185 return;
186 }
187
188 service->addBatteryData(params);
189}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700190#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800191
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700193{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700194 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 int rc;
196
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700197 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
198 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
199 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
200 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202 }
203 rc = audio_hw_device_open(mod, dev);
204 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
205 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
206 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700208 }
209 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
210 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
211 rc = BAD_VALUE;
212 goto out;
213 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700214 return 0;
215
216out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 *dev = NULL;
218 return rc;
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221// ----------------------------------------------------------------------------
222
223AudioFlinger::AudioFlinger()
224 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800225 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700226 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 mMasterMute(false),
229 mNextUniqueId(1),
230 mMode(AUDIO_MODE_INVALID),
231 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700233}
234
235void AudioFlinger::onFirstRef()
236{
Dima Zavin799a70e2011-04-18 16:57:27 -0700237 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700238
Eric Laurent93575202011-01-18 18:39:02 -0800239 Mutex::Autolock _l(mLock);
240
Dima Zavin799a70e2011-04-18 16:57:27 -0700241 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800242 char val_str[PROPERTY_VALUE_MAX] = { 0 };
243 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
244 uint32_t int_val;
245 if (1 == sscanf(val_str, "%u", &int_val)) {
246 mStandbyTimeInNsecs = milliseconds(int_val);
247 ALOGI("Using %u mSec as standby time.", int_val);
248 } else {
249 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
250 ALOGI("Using default %u mSec as standby time.",
251 (uint32_t)(mStandbyTimeInNsecs / 1000000));
252 }
253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254
Eric Laurenta4c5a552012-03-29 10:12:40 -0700255 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256}
257
258AudioFlinger::~AudioFlinger()
259{
260 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700261 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700262 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
264 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700265 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700266 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700268
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800269 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
270 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
272 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274}
275
Eric Laurenta4c5a552012-03-29 10:12:40 -0700276static const char * const audio_interfaces[] = {
277 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278 AUDIO_HARDWARE_MODULE_ID_A2DP,
279 AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
John Grossmanee578c02012-07-23 17:05:46 -0700283AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
284 audio_module_handle_t module,
285 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700286{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700287 // if module is 0, the request comes from an old policy manager and we should load
288 // well known modules
289 if (module == 0) {
290 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292 loadHwModule_l(audio_interfaces[i]);
293 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700294 // then try to find a module supporting the requested device.
295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
297 audio_hw_device_t *dev = audioHwDevice->hwDevice();
298 if ((dev->get_supported_devices != NULL) &&
299 (dev->get_supported_devices(dev) & devices) == devices)
300 return audioHwDevice;
301 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700302 } else {
303 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700304 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
305 if (audioHwDevice != NULL) {
306 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700307 }
308 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700309
Dima Zavin799a70e2011-04-18 16:57:27 -0700310 return NULL;
311}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314{
315 const size_t SIZE = 256;
316 char buffer[SIZE];
317 String8 result;
318
319 result.append("Clients:\n");
320 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800321 sp<Client> client = mClients.valueAt(i).promote();
322 if (client != 0) {
323 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
324 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 }
326 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327
328 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800329 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700330 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
331 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800332 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700333 result.append(buffer);
334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336}
337
338
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700339void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340{
341 const size_t SIZE = 256;
342 char buffer[SIZE];
343 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800344 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345
John Grossman4ff14ba2012-02-08 16:37:41 -0800346 snprintf(buffer, SIZE, "Hardware status: %d\n"
347 "Standby Time mSec: %u\n",
348 hardwareStatus,
349 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 result.append(buffer);
351 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700354void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355{
356 const size_t SIZE = 256;
357 char buffer[SIZE];
358 String8 result;
359 snprintf(buffer, SIZE, "Permission Denial: "
360 "can't dump AudioFlinger from pid=%d, uid=%d\n",
361 IPCThreadState::self()->getCallingPid(),
362 IPCThreadState::self()->getCallingUid());
363 result.append(buffer);
364 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365}
366
367static bool tryLock(Mutex& mutex)
368{
369 bool locked = false;
370 for (int i = 0; i < kDumpLockRetries; ++i) {
371 if (mutex.tryLock() == NO_ERROR) {
372 locked = true;
373 break;
374 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800375 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 }
377 return locked;
378}
379
380status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
381{
Glenn Kasten44deb052012-02-05 18:09:08 -0800382 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 dumpPermissionDenial(fd, args);
384 } else {
385 // get state of hardware lock
386 bool hardwareLocked = tryLock(mHardwareLock);
387 if (!hardwareLocked) {
388 String8 result(kHardwareLockedString);
389 write(fd, result.string(), result.size());
390 } else {
391 mHardwareLock.unlock();
392 }
393
394 bool locked = tryLock(mLock);
395
396 // failed to lock - AudioFlinger is probably deadlocked
397 if (!locked) {
398 String8 result(kDeadlockedString);
399 write(fd, result.string(), result.size());
400 }
401
402 dumpClients(fd, args);
403 dumpInternals(fd, args);
404
405 // dump playback threads
406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
407 mPlaybackThreads.valueAt(i)->dump(fd, args);
408 }
409
410 // dump record threads
411 for (size_t i = 0; i < mRecordThreads.size(); i++) {
412 mRecordThreads.valueAt(i)->dump(fd, args);
413 }
414
Dima Zavin799a70e2011-04-18 16:57:27 -0700415 // dump all hardware devs
416 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700417 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700418 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700420
421 // dump the serially shared record tee sink
422 if (mRecordTeeSource != 0) {
423 dumpTee(fd, mRecordTeeSource);
424 }
425
Glenn Kastend65d73c2012-06-22 17:21:07 -0700426 if (locked) {
427 mLock.unlock();
428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429 }
430 return NO_ERROR;
431}
432
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800433sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
434{
435 // If pid is already in the mClients wp<> map, then use that entry
436 // (for which promote() is always != 0), otherwise create a new entry and Client.
437 sp<Client> client = mClients.valueFor(pid).promote();
438 if (client == 0) {
439 client = new Client(this, pid);
440 mClients.add(pid, client);
441 }
442
443 return client;
444}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445
446// IAudioFlinger interface
447
448
449sp<IAudioTrack> AudioFlinger::createTrack(
450 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800451 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800453 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700454 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -0800455 size_t frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800456 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800458 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800459 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 int *sessionId,
461 status_t *status)
462{
463 sp<PlaybackThread::Track> track;
464 sp<TrackHandle> trackHandle;
465 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 status_t lStatus;
467 int lSessionId;
468
Glenn Kasten263709e2012-01-06 08:40:01 -0800469 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
470 // but if someone uses binder directly they could bypass that and cause us to crash
471 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000472 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 lStatus = BAD_VALUE;
474 goto Exit;
475 }
476
Glenn Kasten60a83922012-06-21 12:56:37 -0700477 // client is responsible for conversion of 8-bit PCM to 16-bit PCM,
478 // and we don't yet support 8.24 or 32-bit PCM
479 if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) {
480 ALOGE("createTrack() invalid format %d", format);
481 lStatus = BAD_VALUE;
482 goto Exit;
483 }
484
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 {
486 Mutex::Autolock _l(mLock);
487 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700488 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000490 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 lStatus = BAD_VALUE;
492 goto Exit;
493 }
494
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800495 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496
Steve Block3856b092011-10-20 11:56:00 +0100497 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700498 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700499 // check if an effect chain with the same session ID is present on another
500 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700501 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700502 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
503 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700504 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700505 if (sessions & PlaybackThread::EFFECT_SESSION) {
506 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700507 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700508 }
Eric Laurentde070132010-07-13 04:45:46 -0700509 }
510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 lSessionId = *sessionId;
512 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700513 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700514 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 if (sessionId != NULL) {
516 *sessionId = lSessionId;
517 }
518 }
Steve Block3856b092011-10-20 11:56:00 +0100519 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520
521 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800522 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700523
524 // move effect chain to this output thread if an effect on same session was waiting
525 // for a track to be created
526 if (lStatus == NO_ERROR && effectThread != NULL) {
527 Mutex::Autolock _dl(thread->mLock);
528 Mutex::Autolock _sl(effectThread->mLock);
529 moveEffectChain_l(lSessionId, effectThread, thread, true);
530 }
Eric Laurenta011e352012-03-29 15:51:43 -0700531
532 // Look for sync events awaiting for a session to be used.
533 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
534 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
535 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700536 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700537 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700538 } else {
539 mPendingSyncEvents[i]->cancel();
540 }
Eric Laurenta011e352012-03-29 15:51:43 -0700541 mPendingSyncEvents.removeAt(i);
542 i--;
543 }
544 }
545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 }
547 if (lStatus == NO_ERROR) {
548 trackHandle = new TrackHandle(track);
549 } else {
550 // remove local strong reference to Client before deleting the Track so that the Client
551 // destructor is called by the TrackBase destructor with mLock held
552 client.clear();
553 track.clear();
554 }
555
556Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700557 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 *status = lStatus;
559 }
560 return trackHandle;
561}
562
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800563uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700564{
565 Mutex::Autolock _l(mLock);
566 PlaybackThread *thread = checkPlaybackThread_l(output);
567 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000568 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569 return 0;
570 }
571 return thread->sampleRate();
572}
573
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800574int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575{
576 Mutex::Autolock _l(mLock);
577 PlaybackThread *thread = checkPlaybackThread_l(output);
578 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000579 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 return 0;
581 }
582 return thread->channelCount();
583}
584
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800585audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586{
587 Mutex::Autolock _l(mLock);
588 PlaybackThread *thread = checkPlaybackThread_l(output);
589 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000590 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800591 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 }
593 return thread->format();
594}
595
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800596size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597{
598 Mutex::Autolock _l(mLock);
599 PlaybackThread *thread = checkPlaybackThread_l(output);
600 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000601 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 return 0;
603 }
Glenn Kasten58912562012-04-03 10:45:00 -0700604 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
605 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 return thread->frameCount();
607}
608
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800609uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610{
611 Mutex::Autolock _l(mLock);
612 PlaybackThread *thread = checkPlaybackThread_l(output);
613 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000614 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 return 0;
616 }
617 return thread->latency();
618}
619
620status_t AudioFlinger::setMasterVolume(float value)
621{
Eric Laurenta1884f92011-08-23 08:25:03 -0700622 status_t ret = initCheck();
623 if (ret != NO_ERROR) {
624 return ret;
625 }
626
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 // check calling permissions
628 if (!settingsAllowed()) {
629 return PERMISSION_DENIED;
630 }
631
Eric Laurenta4c5a552012-03-29 10:12:40 -0700632 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700633 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700634
John Grossmanee578c02012-07-23 17:05:46 -0700635 // Set master volume in the HALs which support it.
636 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
637 AutoMutex lock(mHardwareLock);
638 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800639
John Grossmanee578c02012-07-23 17:05:46 -0700640 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
641 if (dev->canSetMasterVolume()) {
642 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800643 }
John Grossmanee578c02012-07-23 17:05:46 -0700644 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646
John Grossmanee578c02012-07-23 17:05:46 -0700647 // Now set the master volume in each playback thread. Playback threads
648 // assigned to HALs which do not have master volume support will apply
649 // master volume during the mix operation. Threads with HALs which do
650 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800651 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700652 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653
654 return NO_ERROR;
655}
656
Glenn Kastenf78aee72012-01-04 11:00:47 -0800657status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658{
Eric Laurenta1884f92011-08-23 08:25:03 -0700659 status_t ret = initCheck();
660 if (ret != NO_ERROR) {
661 return ret;
662 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663
664 // check calling permissions
665 if (!settingsAllowed()) {
666 return PERMISSION_DENIED;
667 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800668 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000669 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 return BAD_VALUE;
671 }
672
673 { // scope for the lock
674 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700675 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700677 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 mHardwareStatus = AUDIO_HW_IDLE;
679 }
680
681 if (NO_ERROR == ret) {
682 Mutex::Autolock _l(mLock);
683 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800684 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700685 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 }
687
688 return ret;
689}
690
691status_t AudioFlinger::setMicMute(bool state)
692{
Eric Laurenta1884f92011-08-23 08:25:03 -0700693 status_t ret = initCheck();
694 if (ret != NO_ERROR) {
695 return ret;
696 }
697
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 // check calling permissions
699 if (!settingsAllowed()) {
700 return PERMISSION_DENIED;
701 }
702
703 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700704 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700706 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 mHardwareStatus = AUDIO_HW_IDLE;
708 return ret;
709}
710
711bool AudioFlinger::getMicMute() const
712{
Eric Laurenta1884f92011-08-23 08:25:03 -0700713 status_t ret = initCheck();
714 if (ret != NO_ERROR) {
715 return false;
716 }
717
Dima Zavinfce7a472011-04-19 22:30:36 -0700718 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800719 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700720 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700722 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 mHardwareStatus = AUDIO_HW_IDLE;
724 return state;
725}
726
727status_t AudioFlinger::setMasterMute(bool muted)
728{
John Grossmand8f178d2012-07-20 14:51:35 -0700729 status_t ret = initCheck();
730 if (ret != NO_ERROR) {
731 return ret;
732 }
733
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734 // check calling permissions
735 if (!settingsAllowed()) {
736 return PERMISSION_DENIED;
737 }
738
John Grossmanee578c02012-07-23 17:05:46 -0700739 Mutex::Autolock _l(mLock);
740 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700741
John Grossmanee578c02012-07-23 17:05:46 -0700742 // Set master mute in the HALs which support it.
743 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
744 AutoMutex lock(mHardwareLock);
745 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700746
John Grossmanee578c02012-07-23 17:05:46 -0700747 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
748 if (dev->canSetMasterMute()) {
749 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700750 }
John Grossmanee578c02012-07-23 17:05:46 -0700751 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700752 }
753
John Grossmanee578c02012-07-23 17:05:46 -0700754 // Now set the master mute in each playback thread. Playback threads
755 // assigned to HALs which do not have master mute support will apply master
756 // mute during the mix operation. Threads with HALs which do support master
757 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800758 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700759 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760
761 return NO_ERROR;
762}
763
764float AudioFlinger::masterVolume() const
765{
Glenn Kasten98067102011-12-13 11:47:54 -0800766 Mutex::Autolock _l(mLock);
767 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768}
769
770bool AudioFlinger::masterMute() const
771{
Glenn Kasten98067102011-12-13 11:47:54 -0800772 Mutex::Autolock _l(mLock);
773 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774}
775
John Grossman4ff14ba2012-02-08 16:37:41 -0800776float AudioFlinger::masterVolume_l() const
777{
John Grossman4ff14ba2012-02-08 16:37:41 -0800778 return mMasterVolume;
779}
780
John Grossmand8f178d2012-07-20 14:51:35 -0700781bool AudioFlinger::masterMute_l() const
782{
John Grossmanee578c02012-07-23 17:05:46 -0700783 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700784}
785
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800786status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
787 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788{
789 // check calling permissions
790 if (!settingsAllowed()) {
791 return PERMISSION_DENIED;
792 }
793
Glenn Kasten263709e2012-01-06 08:40:01 -0800794 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000795 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 return BAD_VALUE;
797 }
798
799 AutoMutex lock(mLock);
800 PlaybackThread *thread = NULL;
801 if (output) {
802 thread = checkPlaybackThread_l(output);
803 if (thread == NULL) {
804 return BAD_VALUE;
805 }
806 }
807
808 mStreamTypes[stream].volume = value;
809
810 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800811 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700812 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
814 } else {
815 thread->setStreamVolume(stream, value);
816 }
817
818 return NO_ERROR;
819}
820
Glenn Kastenfff6d712012-01-12 16:38:12 -0800821status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822{
823 // check calling permissions
824 if (!settingsAllowed()) {
825 return PERMISSION_DENIED;
826 }
827
Glenn Kasten263709e2012-01-06 08:40:01 -0800828 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700829 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000830 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831 return BAD_VALUE;
832 }
833
Eric Laurent93575202011-01-18 18:39:02 -0800834 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 mStreamTypes[stream].mute = muted;
836 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700837 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838
839 return NO_ERROR;
840}
841
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800842float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843{
Glenn Kasten263709e2012-01-06 08:40:01 -0800844 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0.0f;
846 }
847
848 AutoMutex lock(mLock);
849 float volume;
850 if (output) {
851 PlaybackThread *thread = checkPlaybackThread_l(output);
852 if (thread == NULL) {
853 return 0.0f;
854 }
855 volume = thread->streamVolume(stream);
856 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800857 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 }
859
860 return volume;
861}
862
Glenn Kastenfff6d712012-01-12 16:38:12 -0800863bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864{
Glenn Kasten263709e2012-01-06 08:40:01 -0800865 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 return true;
867 }
868
Glenn Kasten6637baa2012-01-09 09:40:36 -0800869 AutoMutex lock(mLock);
870 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871}
872
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800873status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700874{
Glenn Kasten827e5f12012-11-02 10:00:06 -0700875 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
876 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700877 // check calling permissions
878 if (!settingsAllowed()) {
879 return PERMISSION_DENIED;
880 }
881
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882 // ioHandle == 0 means the parameters are global to the audio hardware interface
883 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700884 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700885 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800886 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700887 AutoMutex lock(mHardwareLock);
888 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
889 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
890 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
891 status_t result = dev->set_parameters(dev, keyValuePairs.string());
892 final_result = result ?: final_result;
893 }
894 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800895 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700896 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
897 AudioParameter param = AudioParameter(keyValuePairs);
898 String8 value;
899 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700900 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
901 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700902 for (size_t i = 0; i < mRecordThreads.size(); i++) {
903 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -0700904 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -0700905 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
906 // collect all of the thread's session IDs
907 KeyedVector<int, bool> ids = thread->sessionIds();
908 // suspend effects associated with those session IDs
909 for (size_t j = 0; j < ids.size(); ++j) {
910 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700911 thread->setEffectSuspended(FX_IID_AEC,
912 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700913 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700914 thread->setEffectSuspended(FX_IID_NS,
915 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700916 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700917 }
918 }
Eric Laurentbee53372011-08-29 12:42:48 -0700919 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700920 }
921 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700922 String8 screenState;
923 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
924 bool isOff = screenState == "off";
925 if (isOff != (gScreenState & 1)) {
926 gScreenState = ((gScreenState & ~1) + 2) | isOff;
927 }
928 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700929 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 }
931
932 // hold a strong ref on thread in case closeOutput() or closeInput() is called
933 // and the thread is exited once the lock is released
934 sp<ThreadBase> thread;
935 {
936 Mutex::Autolock _l(mLock);
937 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700938 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800940 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700941 // indicate output device change to all input threads for pre processing
942 AudioParameter param = AudioParameter(keyValuePairs);
943 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700944 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
945 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700946 for (size_t i = 0; i < mRecordThreads.size(); i++) {
947 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
948 }
949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 }
951 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800952 if (thread != 0) {
953 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 }
955 return BAD_VALUE;
956}
957
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800958String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959{
Glenn Kasten827e5f12012-11-02 10:00:06 -0700960 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
961 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962
Eric Laurenta4c5a552012-03-29 10:12:40 -0700963 Mutex::Autolock _l(mLock);
964
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700966 String8 out_s8;
967
Dima Zavin799a70e2011-04-18 16:57:27 -0700968 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800969 char *s;
970 {
971 AutoMutex lock(mHardwareLock);
972 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700973 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800974 s = dev->get_parameters(dev, keys.string());
975 mHardwareStatus = AUDIO_HW_IDLE;
976 }
John Grossmanef7740b2012-02-09 11:28:36 -0800977 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700978 free(s);
979 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700980 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 }
982
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
984 if (playbackThread != NULL) {
985 return playbackThread->getParameters(keys);
986 }
987 RecordThread *recordThread = checkRecordThread_l(ioHandle);
988 if (recordThread != NULL) {
989 return recordThread->getParameters(keys);
990 }
991 return String8("");
992}
993
Glenn Kastendd8104c2012-07-02 12:42:44 -0700994size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
995 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996{
Eric Laurenta1884f92011-08-23 08:25:03 -0700997 status_t ret = initCheck();
998 if (ret != NO_ERROR) {
999 return 0;
1000 }
1001
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001002 AutoMutex lock(mHardwareLock);
1003 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001004 struct audio_config config = {
1005 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001006 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001007 format: format,
1008 };
John Grossmanee578c02012-07-23 17:05:46 -07001009 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1010 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001011 mHardwareStatus = AUDIO_HW_IDLE;
1012 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013}
1014
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001015unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 Mutex::Autolock _l(mLock);
1018
1019 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1020 if (recordThread != NULL) {
1021 return recordThread->getInputFramesLost();
1022 }
1023 return 0;
1024}
1025
1026status_t AudioFlinger::setVoiceVolume(float value)
1027{
Eric Laurenta1884f92011-08-23 08:25:03 -07001028 status_t ret = initCheck();
1029 if (ret != NO_ERROR) {
1030 return ret;
1031 }
1032
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 // check calling permissions
1034 if (!settingsAllowed()) {
1035 return PERMISSION_DENIED;
1036 }
1037
1038 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001039 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001040 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001041 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 mHardwareStatus = AUDIO_HW_IDLE;
1043
1044 return ret;
1045}
1046
Glenn Kasten26c77552012-11-16 12:01:44 -08001047status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001048 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049{
1050 status_t status;
1051
1052 Mutex::Autolock _l(mLock);
1053
1054 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1055 if (playbackThread != NULL) {
1056 return playbackThread->getRenderPosition(halFrames, dspFrames);
1057 }
1058
1059 return BAD_VALUE;
1060}
1061
1062void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1063{
1064
1065 Mutex::Autolock _l(mLock);
1066
Glenn Kastenbb001922012-02-03 11:10:26 -08001067 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 if (mNotificationClients.indexOfKey(pid) < 0) {
1069 sp<NotificationClient> notificationClient = new NotificationClient(this,
1070 client,
1071 pid);
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073
1074 mNotificationClients.add(pid, notificationClient);
1075
1076 sp<IBinder> binder = client->asBinder();
1077 binder->linkToDeath(notificationClient);
1078
1079 // the config change is always sent from playback or record threads to avoid deadlock
1080 // with AudioSystem::gLock
1081 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001082 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 }
1084
1085 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001086 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 }
1088 }
1089}
1090
1091void AudioFlinger::removeNotificationClient(pid_t pid)
1092{
1093 Mutex::Autolock _l(mLock);
1094
Glenn Kastena3b09252012-01-20 09:19:01 -08001095 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001096
Steve Block3856b092011-10-20 11:56:00 +01001097 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001098 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001099 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001100 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001101 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001102 ALOGV(" pid %d @ %d", ref->mPid, i);
1103 if (ref->mPid == pid) {
1104 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001105 mAudioSessionRefs.removeAt(i);
1106 delete ref;
1107 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001108 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001109 } else {
1110 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001111 }
1112 }
1113 if (removed) {
1114 purgeStaleEffects_l();
1115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116}
1117
1118// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001119void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120{
1121 size_t size = mNotificationClients.size();
1122 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001123 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1124 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 }
1126}
1127
1128// removeClient_l() must be called with AudioFlinger::mLock held
1129void AudioFlinger::removeClient_l(pid_t pid)
1130{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001131 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001132 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 mClients.removeItem(pid);
1134}
1135
Eric Laurent717e1282012-06-29 16:36:52 -07001136// getEffectThread_l() must be called with AudioFlinger::mLock held
1137sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1138{
1139 sp<PlaybackThread> thread;
1140
1141 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1142 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1143 ALOG_ASSERT(thread == 0);
1144 thread = mPlaybackThreads.valueAt(i);
1145 }
1146 }
1147
1148 return thread;
1149}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150
1151// ----------------------------------------------------------------------------
1152
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001153AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001154 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001155 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001156 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001157 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001158 // mChannelMask
1159 mChannelCount(0),
1160 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1161 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001162 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1163 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001164 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001165 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166{
1167}
1168
1169AudioFlinger::ThreadBase::~ThreadBase()
1170{
1171 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001172 // do not lock the mutex in destructor
1173 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001174 if (mPowerManager != 0) {
1175 sp<IBinder> binder = mPowerManager->asBinder();
1176 binder->unlinkToDeath(mDeathRecipient);
1177 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178}
1179
1180void AudioFlinger::ThreadBase::exit()
1181{
Steve Block3856b092011-10-20 11:56:00 +01001182 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001183 // do any cleanup required for exit to succeed
1184 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001186 // This lock prevents the following race in thread (uniprocessor for illustration):
1187 // if (!exitPending()) {
1188 // // context switch from here to exit()
1189 // // exit() calls requestExit(), what exitPending() observes
1190 // // exit() calls signal(), which is dropped since no waiters
1191 // // context switch back from exit() to here
1192 // mWaitWorkCV.wait(...);
1193 // // now thread is hung
1194 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001195 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001197 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001199 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1200 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 requestExitAndWait();
1202}
1203
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1205{
1206 status_t status;
1207
Steve Block3856b092011-10-20 11:56:00 +01001208 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 Mutex::Autolock _l(mLock);
1210
1211 mNewParameters.add(keyValuePairs);
1212 mWaitWorkCV.signal();
1213 // wait condition with timeout in case the thread loop has exited
1214 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001215 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 status = mParamStatus;
1217 mWaitWorkCV.signal();
1218 } else {
1219 status = TIMED_OUT;
1220 }
1221 return status;
1222}
1223
Eric Laurent896adcd2012-09-13 11:18:23 -07001224void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225{
1226 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001227 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228}
1229
Eric Laurent896adcd2012-09-13 11:18:23 -07001230// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1231void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232{
Eric Laurent896adcd2012-09-13 11:18:23 -07001233 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1234 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001235 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
1236 param);
Eric Laurent896adcd2012-09-13 11:18:23 -07001237 mWaitWorkCV.signal();
1238}
1239
1240// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1241void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1242{
1243 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1244 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1245 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1246 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 mWaitWorkCV.signal();
1248}
1249
1250void AudioFlinger::ThreadBase::processConfigEvents()
1251{
1252 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001253 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001254 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001255 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 mConfigEvents.removeAt(0);
1257 // release mLock before locking AudioFlinger mLock: lock order is always
1258 // AudioFlinger then ThreadBase to avoid cross deadlock
1259 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001260 switch(event->type()) {
1261 case CFG_EVENT_PRIO: {
1262 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1263 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1264 if (err != 0) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001265 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
1266 "error %d",
Eric Laurent896adcd2012-09-13 11:18:23 -07001267 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1268 }
1269 } break;
1270 case CFG_EVENT_IO: {
1271 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1272 mAudioFlinger->mLock.lock();
1273 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1274 mAudioFlinger->mLock.unlock();
1275 } break;
1276 default:
1277 ALOGE("processConfigEvents() unknown event type %d", event->type());
1278 break;
1279 }
1280 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 mLock.lock();
1282 }
1283 mLock.unlock();
1284}
1285
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001286void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287{
1288 const size_t SIZE = 256;
1289 char buffer[SIZE];
1290 String8 result;
1291
1292 bool locked = tryLock(mLock);
1293 if (!locked) {
1294 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1295 write(fd, buffer, strlen(buffer));
1296 }
1297
Eric Laurent612bbb52012-03-14 15:03:26 -07001298 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1299 result.append(buffer);
1300 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1301 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1303 result.append(buffer);
Glenn Kasten3b16c762012-11-14 08:44:39 -08001304 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001306 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1307 result.append(buffer);
1308 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309 result.append(buffer);
1310 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1311 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001312 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1313 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001314 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1315 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001316 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 result.append(buffer);
1318
1319 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1320 result.append(buffer);
1321 result.append(" Index Command");
1322 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1323 snprintf(buffer, SIZE, "\n %02d ", i);
1324 result.append(buffer);
1325 result.append(mNewParameters[i]);
1326 }
1327
1328 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1329 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001331 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001332 result.append(buffer);
1333 }
1334 result.append("\n");
1335
1336 write(fd, result.string(), result.size());
1337
1338 if (locked) {
1339 mLock.unlock();
1340 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001341}
1342
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001343void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001344{
1345 const size_t SIZE = 256;
1346 char buffer[SIZE];
1347 String8 result;
1348
1349 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1350 write(fd, buffer, strlen(buffer));
1351
1352 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1353 sp<EffectChain> chain = mEffectChains[i];
1354 if (chain != 0) {
1355 chain->dump(fd, args);
1356 }
1357 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001358}
1359
Eric Laurentfeb0db62011-07-22 09:04:31 -07001360void AudioFlinger::ThreadBase::acquireWakeLock()
1361{
1362 Mutex::Autolock _l(mLock);
1363 acquireWakeLock_l();
1364}
1365
1366void AudioFlinger::ThreadBase::acquireWakeLock_l()
1367{
1368 if (mPowerManager == 0) {
1369 // use checkService() to avoid blocking if power service is not up yet
1370 sp<IBinder> binder =
1371 defaultServiceManager()->checkService(String16("power"));
1372 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001373 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001374 } else {
1375 mPowerManager = interface_cast<IPowerManager>(binder);
1376 binder->linkToDeath(mDeathRecipient);
1377 }
1378 }
1379 if (mPowerManager != 0) {
1380 sp<IBinder> binder = new BBinder();
1381 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1382 binder,
1383 String16(mName));
1384 if (status == NO_ERROR) {
1385 mWakeLockToken = binder;
1386 }
Steve Block3856b092011-10-20 11:56:00 +01001387 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001388 }
1389}
1390
1391void AudioFlinger::ThreadBase::releaseWakeLock()
1392{
1393 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001394 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001395}
1396
1397void AudioFlinger::ThreadBase::releaseWakeLock_l()
1398{
1399 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001400 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001401 if (mPowerManager != 0) {
1402 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1403 }
1404 mWakeLockToken.clear();
1405 }
1406}
1407
1408void AudioFlinger::ThreadBase::clearPowerManager()
1409{
1410 Mutex::Autolock _l(mLock);
1411 releaseWakeLock_l();
1412 mPowerManager.clear();
1413}
1414
1415void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1416{
1417 sp<ThreadBase> thread = mThread.promote();
1418 if (thread != 0) {
1419 thread->clearPowerManager();
1420 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001421 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001422}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001423
Eric Laurent59255e42011-07-27 19:49:51 -07001424void AudioFlinger::ThreadBase::setEffectSuspended(
1425 const effect_uuid_t *type, bool suspend, int sessionId)
1426{
1427 Mutex::Autolock _l(mLock);
1428 setEffectSuspended_l(type, suspend, sessionId);
1429}
1430
1431void AudioFlinger::ThreadBase::setEffectSuspended_l(
1432 const effect_uuid_t *type, bool suspend, int sessionId)
1433{
Glenn Kasten090f0192012-01-30 13:00:02 -08001434 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001435 if (chain != 0) {
1436 if (type != NULL) {
1437 chain->setEffectSuspended_l(type, suspend);
1438 } else {
1439 chain->setEffectSuspendedAll_l(suspend);
1440 }
1441 }
1442
1443 updateSuspendedSessions_l(type, suspend, sessionId);
1444}
1445
1446void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1447{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001448 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001449 if (index < 0) {
1450 return;
1451 }
1452
Glenn Kasten0a7af182012-07-09 16:09:19 -07001453 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1454 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001455
1456 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001457 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001458 for (int j = 0; j < desc->mRefCount; j++) {
1459 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1460 chain->setEffectSuspendedAll_l(true);
1461 } else {
Steve Block3856b092011-10-20 11:56:00 +01001462 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001463 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001464 chain->setEffectSuspended_l(&desc->mType, true);
1465 }
1466 }
1467 }
1468}
1469
Eric Laurent59255e42011-07-27 19:49:51 -07001470void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1471 bool suspend,
1472 int sessionId)
1473{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001474 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001475
1476 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1477
1478 if (suspend) {
1479 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001480 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001481 } else {
1482 mSuspendedSessions.add(sessionId, sessionEffects);
1483 }
1484 } else {
1485 if (index < 0) {
1486 return;
1487 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001488 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001489 }
1490
1491
1492 int key = EffectChain::kKeyForSuspendAll;
1493 if (type != NULL) {
1494 key = type->timeLow;
1495 }
1496 index = sessionEffects.indexOfKey(key);
1497
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001498 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001499 if (suspend) {
1500 if (index >= 0) {
1501 desc = sessionEffects.valueAt(index);
1502 } else {
1503 desc = new SuspendedSessionDesc();
1504 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001505 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001506 }
1507 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001508 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001509 }
1510 desc->mRefCount++;
1511 } else {
1512 if (index < 0) {
1513 return;
1514 }
1515 desc = sessionEffects.valueAt(index);
1516 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001517 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001518 sessionEffects.removeItemsAt(index);
1519 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001520 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001521 sessionId);
1522 mSuspendedSessions.removeItem(sessionId);
1523 }
1524 }
1525 }
1526 if (!sessionEffects.isEmpty()) {
1527 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1528 }
1529}
1530
1531void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1532 bool enabled,
1533 int sessionId)
1534{
1535 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001536 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1537}
Eric Laurent59255e42011-07-27 19:49:51 -07001538
Eric Laurenta85a74a2011-10-19 11:44:54 -07001539void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1540 bool enabled,
1541 int sessionId)
1542{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001543 if (mType != RECORD) {
1544 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1545 // another session. This gives the priority to well behaved effect control panels
1546 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001547 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1548 // global effects
1549 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001550 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1551 }
1552 }
Eric Laurent59255e42011-07-27 19:49:51 -07001553
1554 sp<EffectChain> chain = getEffectChain_l(sessionId);
1555 if (chain != 0) {
1556 chain->checkSuspendOnEffectEnabled(effect, enabled);
1557 }
1558}
1559
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560// ----------------------------------------------------------------------------
1561
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001562AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1563 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001564 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001565 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001566 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001567 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001568 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001569 // mStreamTypes[] initialized in constructor body
1570 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001571 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001572 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001573 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001574 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001575 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001576 // index 0 is reserved for normal mixer's submix
1577 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578{
Glenn Kasten480b4682012-02-28 12:30:08 -08001579 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001580
John Grossmanee578c02012-07-23 17:05:46 -07001581 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1582 // it would be safer to explicitly pass initial masterVolume/masterMute as
1583 // parameter.
1584 //
1585 // If the HAL we are using has support for master volume or master mute,
1586 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1587 // and the mute set to false).
1588 mMasterVolume = audioFlinger->masterVolume_l();
1589 mMasterMute = audioFlinger->masterMute_l();
1590 if (mOutput && mOutput->audioHwDev) {
1591 if (mOutput->audioHwDev->canSetMasterVolume()) {
1592 mMasterVolume = 1.0;
1593 }
1594
1595 if (mOutput->audioHwDev->canSetMasterMute()) {
1596 mMasterMute = false;
1597 }
1598 }
1599
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 readOutputParameters();
1601
Glenn Kasten263709e2012-01-06 08:40:01 -08001602 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001603 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1604 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1605 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001606 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1607 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001609 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1610 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611}
1612
1613AudioFlinger::PlaybackThread::~PlaybackThread()
1614{
1615 delete [] mMixBuffer;
1616}
1617
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001618void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619{
1620 dumpInternals(fd, args);
1621 dumpTracks(fd, args);
1622 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623}
1624
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001625void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626{
1627 const size_t SIZE = 256;
1628 char buffer[SIZE];
1629 String8 result;
1630
Glenn Kasten58912562012-04-03 10:45:00 -07001631 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1632 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1633 const stream_type_t *st = &mStreamTypes[i];
1634 if (i > 0) {
1635 result.appendFormat(", ");
1636 }
1637 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1638 if (st->mute) {
1639 result.append("M");
1640 }
1641 }
1642 result.append("\n");
1643 write(fd, result.string(), result.length());
1644 result.clear();
1645
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1647 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001648 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 for (size_t i = 0; i < mTracks.size(); ++i) {
1650 sp<Track> track = mTracks[i];
1651 if (track != 0) {
1652 track->dump(buffer, SIZE);
1653 result.append(buffer);
1654 }
1655 }
1656
1657 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1658 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001659 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001661 sp<Track> track = mActiveTracks[i].promote();
1662 if (track != 0) {
1663 track->dump(buffer, SIZE);
1664 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 }
1666 }
1667 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001668
1669 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1670 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1671 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1672 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673}
1674
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001675void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676{
1677 const size_t SIZE = 256;
1678 char buffer[SIZE];
1679 String8 result;
1680
1681 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1682 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001683 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1684 ns2ms(systemTime() - mLastWriteTime));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 result.append(buffer);
1686 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1687 result.append(buffer);
1688 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1689 result.append(buffer);
1690 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1691 result.append(buffer);
1692 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1693 result.append(buffer);
1694 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1695 result.append(buffer);
1696 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001697 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698
1699 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700}
1701
1702// Thread virtuals
1703status_t AudioFlinger::PlaybackThread::readyToRun()
1704{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001705 status_t status = initCheck();
1706 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001707 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001708 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001709 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001711 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712}
1713
1714void AudioFlinger::PlaybackThread::onFirstRef()
1715{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001716 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717}
1718
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001719// ThreadBase virtuals
1720void AudioFlinger::PlaybackThread::preExit()
1721{
1722 ALOGV(" preExit()");
1723 // FIXME this is using hard-coded strings but in the future, this functionality will be
1724 // converted to use audio HAL extensions required to support tunneling
1725 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1726}
1727
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001729sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001731 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001733 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001734 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08001735 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736 const sp<IMemory>& sharedBuffer,
1737 int sessionId,
Glenn Kastene0b07172012-11-06 15:03:34 -08001738 IAudioFlinger::track_flags_t *flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001739 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 status_t *status)
1741{
1742 sp<Track> track;
1743 status_t lStatus;
1744
Glenn Kastene0b07172012-11-06 15:03:34 -08001745 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
Glenn Kasten73d22752012-03-19 13:38:30 -07001746
1747 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0b07172012-11-06 15:03:34 -08001748 if (*flags & IAudioFlinger::TRACK_FAST) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001749 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001750 // not timed
1751 (!isTimed) &&
1752 // either of these use cases:
1753 (
1754 // use case 1: shared buffer with any frame count
1755 (
1756 (sharedBuffer != 0)
1757 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001758 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001759 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001760 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001761 ((frameCount == 0) ||
Glenn Kastenb6037442012-11-14 13:42:25 -08001762 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001763 )
1764 ) &&
1765 // PCM data
1766 audio_is_linear_pcm(format) &&
1767 // mono or stereo
1768 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1769 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001770#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001771 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001772 (sampleRate == mSampleRate) &&
1773#endif
1774 // normal mixer has an associated fast mixer
1775 hasFastMixer() &&
1776 // there are sufficient fast track slots available
1777 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001778 // FIXME test that MixerThread for this fast track has a capable output HAL
1779 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001780 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001781 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1782 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001783 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001784 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001785 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001786 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001787 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001788 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten3b16c762012-11-14 08:44:39 -08001789 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten58912562012-04-03 10:45:00 -07001790 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1791 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1792 audio_is_linear_pcm(format),
1793 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kastene0b07172012-11-06 15:03:34 -08001794 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001795 // For compatibility with AudioTrack calculation, buffer depth is forced
1796 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1797 // This is probably too conservative, but legacy application code may depend on it.
1798 // If you change this calculation, also review the start threshold which is related.
1799 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1800 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1801 if (minBufCount < 2) {
1802 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001803 }
Glenn Kastene33054e2012-11-14 12:54:39 -08001804 size_t minFrameCount = mNormalFrameCount * minBufCount;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001805 if (frameCount < minFrameCount) {
1806 frameCount = minFrameCount;
1807 }
1808 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001809 }
1810
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001812 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1813 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kasten3b16c762012-11-14 08:44:39 -08001814 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001815 "for output %p with format %d",
1816 sampleRate, format, channelMask, mOutput, mFormat);
1817 lStatus = BAD_VALUE;
1818 goto Exit;
1819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 }
1821 } else {
1822 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1823 if (sampleRate > mSampleRate*2) {
Glenn Kasten3b16c762012-11-14 08:44:39 -08001824 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 lStatus = BAD_VALUE;
1826 goto Exit;
1827 }
1828 }
1829
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001830 lStatus = initCheck();
1831 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001832 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 goto Exit;
1834 }
1835
1836 { // scope for mLock
1837 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001838
1839 // all tracks in same audio session must share the same routing strategy otherwise
1840 // conflicts will happen when tracks are moved from one output to another by audio policy
1841 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001842 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001843 for (size_t i = 0; i < mTracks.size(); ++i) {
1844 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001845 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001846 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001847 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001848 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001849 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001850 lStatus = BAD_VALUE;
1851 goto Exit;
1852 }
1853 }
1854 }
1855
John Grossman4ff14ba2012-02-08 16:37:41 -08001856 if (!isTimed) {
1857 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kastene0b07172012-11-06 15:03:34 -08001858 channelMask, frameCount, sharedBuffer, sessionId, *flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001859 } else {
1860 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1861 channelMask, frameCount, sharedBuffer, sessionId);
1862 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001863 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 lStatus = NO_MEMORY;
1865 goto Exit;
1866 }
1867 mTracks.add(track);
1868
1869 sp<EffectChain> chain = getEffectChain_l(sessionId);
1870 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001871 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001873 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001874 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001876
Glenn Kastene0b07172012-11-06 15:03:34 -08001877 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001878 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1879 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1880 // so ask activity manager to do this on our behalf
1881 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001882 }
1883 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001884
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 lStatus = NO_ERROR;
1886
1887Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001888 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 *status = lStatus;
1890 }
1891 return track;
1892}
1893
Glenn Kasten26c77552012-11-16 12:01:44 -08001894uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurente737cda2012-05-22 18:55:44 -07001895{
1896 if (mFastMixer != NULL) {
1897 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1898 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1899 }
1900 return latency;
1901}
1902
Glenn Kasten26c77552012-11-16 12:01:44 -08001903uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurente737cda2012-05-22 18:55:44 -07001904{
1905 return latency;
1906}
1907
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908uint32_t AudioFlinger::PlaybackThread::latency() const
1909{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001910 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001911 return latency_l();
1912}
1913uint32_t AudioFlinger::PlaybackThread::latency_l() const
1914{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001915 if (initCheck() == NO_ERROR) {
Glenn Kasten26c77552012-11-16 12:01:44 -08001916 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001917 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 return 0;
1919 }
1920}
1921
Glenn Kasten6637baa2012-01-09 09:40:36 -08001922void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001924 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001925 // Don't apply master volume in SW if our HAL can do it for us.
1926 if (mOutput && mOutput->audioHwDev &&
1927 mOutput->audioHwDev->canSetMasterVolume()) {
1928 mMasterVolume = 1.0;
1929 } else {
1930 mMasterVolume = value;
1931 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932}
1933
Glenn Kasten6637baa2012-01-09 09:40:36 -08001934void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001936 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001937 // Don't apply master mute in SW if our HAL can do it for us.
1938 if (mOutput && mOutput->audioHwDev &&
1939 mOutput->audioHwDev->canSetMasterMute()) {
1940 mMasterMute = false;
1941 } else {
1942 mMasterMute = muted;
1943 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944}
1945
Glenn Kasten6637baa2012-01-09 09:40:36 -08001946void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001948 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950}
1951
Glenn Kasten6637baa2012-01-09 09:40:36 -08001952void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001954 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956}
1957
Glenn Kastenfff6d712012-01-12 16:38:12 -08001958float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001960 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 return mStreamTypes[stream].volume;
1962}
1963
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964// addTrack_l() must be called with ThreadBase::mLock held
1965status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1966{
1967 status_t status = ALREADY_EXISTS;
1968
1969 // set retry count for buffer fill
1970 track->mRetryCount = kMaxTrackStartupRetries;
1971 if (mActiveTracks.indexOf(track) < 0) {
1972 // the track is newly added, make sure it fills up all its
1973 // buffers before playing. This is to ensure the client will
1974 // effectively get the latency it requested.
1975 track->mFillingUpStatus = Track::FS_FILLING;
1976 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001977 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 mActiveTracks.add(track);
1979 if (track->mainBuffer() != mMixBuffer) {
1980 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1981 if (chain != 0) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001982 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1983 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001984 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 }
1986 }
1987
1988 status = NO_ERROR;
1989 }
1990
Steve Block3856b092011-10-20 11:56:00 +01001991 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 mWaitWorkCV.broadcast();
1993
1994 return status;
1995}
1996
1997// destroyTrack_l() must be called with ThreadBase::mLock held
1998void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1999{
2000 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002001 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002003 removeTrack_l(track);
2004 }
2005}
2006
2007void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2008{
Eric Laurent29864602012-05-08 18:57:51 -07002009 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002010 mTracks.remove(track);
2011 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002012 // redundant as track is about to be destroyed, for dumpsys only
2013 track->mName = -1;
2014 if (track->isFastTrack()) {
2015 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002016 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002017 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2018 mFastTrackAvailMask |= 1 << index;
2019 // redundant as track is about to be destroyed, for dumpsys only
2020 track->mFastIndex = -1;
2021 }
Eric Laurentb469b942011-05-09 12:09:06 -07002022 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2023 if (chain != 0) {
2024 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 }
2026}
2027
2028String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2029{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002030 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002031 char *s;
2032
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002033 Mutex::Autolock _l(mLock);
2034 if (initCheck() != NO_ERROR) {
2035 return out_s8;
2036 }
2037
Dima Zavin799a70e2011-04-18 16:57:27 -07002038 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002039 out_s8 = String8(s);
2040 free(s);
2041 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042}
2043
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002044// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2046 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002047 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002049 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
2050 param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051
2052 switch (event) {
2053 case AudioSystem::OUTPUT_OPENED:
2054 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002055 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 desc.samplingRate = mSampleRate;
2057 desc.format = mFormat;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002058 desc.frameCount = mNormalFrameCount; // FIXME see
2059 // AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 desc.latency = latency();
2061 param2 = &desc;
2062 break;
2063
2064 case AudioSystem::STREAM_CONFIG_CHANGED:
2065 param2 = &param;
2066 case AudioSystem::OUTPUT_CLOSED:
2067 default:
2068 break;
2069 }
2070 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2071}
2072
2073void AudioFlinger::PlaybackThread::readOutputParameters()
2074{
Dima Zavin799a70e2011-04-18 16:57:27 -07002075 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002076 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2077 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002078 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002079 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002080 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002081 if (mFrameCount & 15) {
2082 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2083 mFrameCount);
2084 }
2085
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002086 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002087 double multiplier = 1.0;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002088 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2089 kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002090 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002091 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2092 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2093 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2094 maxNormalFrameCount = maxNormalFrameCount & ~15;
2095 if (maxNormalFrameCount < minNormalFrameCount) {
2096 maxNormalFrameCount = minNormalFrameCount;
2097 }
2098 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2099 if (multiplier <= 1.0) {
2100 multiplier = 1.0;
2101 } else if (multiplier <= 2.0) {
2102 if (2 * mFrameCount <= maxNormalFrameCount) {
2103 multiplier = 2.0;
2104 } else {
2105 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2106 }
2107 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002108 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
2109 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
2110 // track, but we sometimes have to do this to satisfy the maximum frame count
2111 // constraint)
Glenn Kasten4adcede2012-05-14 12:26:02 -07002112 // FIXME this rounding up should not be done if no HAL SRC
2113 uint32_t truncMult = (uint32_t) multiplier;
2114 if ((truncMult & 1)) {
2115 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2116 ++truncMult;
2117 }
2118 }
2119 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002120 }
Glenn Kasten58912562012-04-03 10:45:00 -07002121 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002122 mNormalFrameCount = multiplier * mFrameCount;
2123 // round up to nearest 16 frames to satisfy AudioMixer
2124 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002125 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
2126 mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127
Glenn Kastene9dd0172012-01-27 18:08:45 -08002128 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002129 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2130 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131
Eric Laurentde070132010-07-13 04:45:46 -07002132 // force reconfiguration of effect chains and engines to take new buffer size and audio
2133 // parameters into account
2134 // Note that mLock is not held when readOutputParameters() is called from the constructor
2135 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2136 // matter.
2137 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2138 Vector< sp<EffectChain> > effectChains = mEffectChains;
2139 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002140 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142}
2143
Eric Laurente737cda2012-05-22 18:55:44 -07002144
Glenn Kasten26c77552012-11-16 12:01:44 -08002145status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146{
Glenn Kastena0d68332012-01-27 16:47:15 -08002147 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 return BAD_VALUE;
2149 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002150 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002151 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 return INVALID_OPERATION;
2153 }
Glenn Kasten26c77552012-11-16 12:01:44 -08002154 size_t framesWritten = mBytesWritten / mFrameSize;
2155 *halFrames = framesWritten;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156
Eric Laurent1afc26d2012-09-23 15:20:50 -07002157 if (isSuspended()) {
2158 // return an estimation of rendered frames when the output is suspended
Glenn Kasten26c77552012-11-16 12:01:44 -08002159 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2160 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002161 return NO_ERROR;
2162 } else {
2163 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165}
2166
Glenn Kasten106e8a42012-08-02 13:37:12 -07002167uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168{
2169 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002170 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002172 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 }
2174
2175 for (size_t i = 0; i < mTracks.size(); ++i) {
2176 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002177 if (sessionId == track->sessionId() &&
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08002178 !(track->mCblk->flags & CBLK_INVALID)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002179 result |= TRACK_SESSION;
2180 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181 }
2182 }
2183
Eric Laurent39e94f82010-07-28 01:32:47 -07002184 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185}
2186
Eric Laurentde070132010-07-13 04:45:46 -07002187uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2188{
Dima Zavinfce7a472011-04-19 22:30:36 -07002189 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002190 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002191 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2192 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002193 }
2194 for (size_t i = 0; i < mTracks.size(); i++) {
2195 sp<Track> track = mTracks[i];
2196 if (sessionId == track->sessionId() &&
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08002197 !(track->mCblk->flags & CBLK_INVALID)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002198 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002199 }
2200 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002201 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002202}
2203
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204
Glenn Kastenaed850d2012-01-26 09:46:34 -08002205AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002206{
2207 Mutex::Autolock _l(mLock);
2208 return mOutput;
2209}
2210
2211AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2212{
2213 Mutex::Autolock _l(mLock);
2214 AudioStreamOut *output = mOutput;
2215 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002216 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2217 // must push a NULL and wait for ack
2218 mOutputSink.clear();
2219 mPipeSink.clear();
2220 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002221 return output;
2222}
2223
2224// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002225audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002226{
2227 if (mOutput == NULL) {
2228 return NULL;
2229 }
2230 return &mOutput->stream->common;
2231}
2232
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002233uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002234{
Eric Laurentab9071b2012-06-04 13:45:29 -07002235 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002236}
2237
Eric Laurenta011e352012-03-29 15:51:43 -07002238status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2239{
2240 if (!isValidSyncEvent(event)) {
2241 return BAD_VALUE;
2242 }
2243
2244 Mutex::Autolock _l(mLock);
2245
2246 for (size_t i = 0; i < mTracks.size(); ++i) {
2247 sp<Track> track = mTracks[i];
2248 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002249 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002250 return NO_ERROR;
2251 }
2252 }
2253
2254 return NAME_NOT_FOUND;
2255}
2256
Glenn Kasten106e8a42012-08-02 13:37:12 -07002257bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002258{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002259 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002260}
2261
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002262void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2263 const Vector< sp<Track> >& tracksToRemove)
Eric Laurent44a957f2012-05-15 15:26:05 -07002264{
2265 size_t count = tracksToRemove.size();
2266 if (CC_UNLIKELY(count)) {
2267 for (size_t i = 0 ; i < count ; i++) {
2268 const sp<Track>& track = tracksToRemove.itemAt(i);
2269 if ((track->sharedBuffer() != 0) &&
2270 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2271 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2272 }
2273 }
2274 }
2275
2276}
2277
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278// ----------------------------------------------------------------------------
2279
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002280AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002281 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002282 : PlaybackThread(audioFlinger, output, id, device, type),
2283 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002284 // mFastMixer below
2285 mFastMixerFutex(0)
2286 // mOutputSink below
2287 // mPipeSink below
2288 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002290 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten60a83922012-06-21 12:56:37 -07002291 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%u, "
Glenn Kasten58912562012-04-03 10:45:00 -07002292 "mFrameCount=%d, mNormalFrameCount=%d",
2293 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2294 mNormalFrameCount);
2295 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2296
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002298 if (mChannelCount != FCC_2) {
2299 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300 }
Glenn Kasten58912562012-04-03 10:45:00 -07002301
2302 // create an NBAIO sink for the HAL output stream, and negotiate
2303 mOutputSink = new AudioStreamOutSink(output->stream);
2304 size_t numCounterOffers = 0;
2305 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2306 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2307 ALOG_ASSERT(index == 0);
2308
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002309 // initialize fast mixer depending on configuration
2310 bool initFastMixer;
2311 switch (kUseFastMixer) {
2312 case FastMixer_Never:
2313 initFastMixer = false;
2314 break;
2315 case FastMixer_Always:
2316 initFastMixer = true;
2317 break;
2318 case FastMixer_Static:
2319 case FastMixer_Dynamic:
2320 initFastMixer = mFrameCount < mNormalFrameCount;
2321 break;
2322 }
2323 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002324
2325 // create a MonoPipe to connect our submix to FastMixer
2326 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002327 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2328 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2329 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2330 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002331 const NBAIO_Format offers[1] = {format};
2332 size_t numCounterOffers = 0;
2333 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2334 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002335 monoPipe->setAvgFrames((mScreenState & 1) ?
2336 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002337 mPipeSink = monoPipe;
2338
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002339#ifdef TEE_SINK_FRAMES
2340 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2341 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2342 numCounterOffers = 0;
2343 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2344 ALOG_ASSERT(index == 0);
2345 mTeeSink = teeSink;
2346 PipeReader *teeSource = new PipeReader(*teeSink);
2347 numCounterOffers = 0;
2348 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2349 ALOG_ASSERT(index == 0);
2350 mTeeSource = teeSource;
2351#endif
2352
Glenn Kasten58912562012-04-03 10:45:00 -07002353 // create fast mixer and configure it initially with just one fast track for our submix
2354 mFastMixer = new FastMixer();
2355 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002356#ifdef STATE_QUEUE_DUMP
2357 sq->setObserverDump(&mStateQueueObserverDump);
2358 sq->setMutatorDump(&mStateQueueMutatorDump);
2359#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002360 FastMixerState *state = sq->begin();
2361 FastTrack *fastTrack = &state->mFastTracks[0];
2362 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2363 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2364 fastTrack->mVolumeProvider = NULL;
2365 fastTrack->mGeneration++;
2366 state->mFastTracksGen++;
2367 state->mTrackMask = 1;
2368 // fast mixer will use the HAL output sink
2369 state->mOutputSink = mOutputSink.get();
2370 state->mOutputSinkGen++;
2371 state->mFrameCount = mFrameCount;
2372 state->mCommand = FastMixerState::COLD_IDLE;
2373 // already done in constructor initialization list
2374 //mFastMixerFutex = 0;
2375 state->mColdFutexAddr = &mFastMixerFutex;
2376 state->mColdGen++;
2377 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002378 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002379 sq->end();
2380 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2381
2382 // start the fast mixer
2383 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002384 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002385 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002386 if (err != 0) {
2387 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002388 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002389 }
Glenn Kasten58912562012-04-03 10:45:00 -07002390
Glenn Kastenc15d6652012-05-30 14:52:57 -07002391#ifdef AUDIO_WATCHDOG
2392 // create and start the watchdog
2393 mAudioWatchdog = new AudioWatchdog();
2394 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2395 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2396 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002397 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002398 if (err != 0) {
2399 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002400 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002401 }
2402#endif
2403
Glenn Kasten58912562012-04-03 10:45:00 -07002404 } else {
2405 mFastMixer = NULL;
2406 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002407
2408 switch (kUseFastMixer) {
2409 case FastMixer_Never:
2410 case FastMixer_Dynamic:
2411 mNormalSink = mOutputSink;
2412 break;
2413 case FastMixer_Always:
2414 mNormalSink = mPipeSink;
2415 break;
2416 case FastMixer_Static:
2417 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2418 break;
2419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420}
2421
2422AudioFlinger::MixerThread::~MixerThread()
2423{
Glenn Kasten58912562012-04-03 10:45:00 -07002424 if (mFastMixer != NULL) {
2425 FastMixerStateQueue *sq = mFastMixer->sq();
2426 FastMixerState *state = sq->begin();
2427 if (state->mCommand == FastMixerState::COLD_IDLE) {
2428 int32_t old = android_atomic_inc(&mFastMixerFutex);
2429 if (old == -1) {
2430 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2431 }
2432 }
2433 state->mCommand = FastMixerState::EXIT;
2434 sq->end();
2435 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2436 mFastMixer->join();
2437 // Though the fast mixer thread has exited, it's state queue is still valid.
2438 // We'll use that extract the final state which contains one remaining fast track
2439 // corresponding to our sub-mix.
2440 state = sq->begin();
2441 ALOG_ASSERT(state->mTrackMask == 1);
2442 FastTrack *fastTrack = &state->mFastTracks[0];
2443 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2444 delete fastTrack->mBufferProvider;
2445 sq->end(false /*didModify*/);
2446 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002447#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002448 if (mAudioWatchdog != 0) {
2449 mAudioWatchdog->requestExit();
2450 mAudioWatchdog->requestExitAndWait();
2451 mAudioWatchdog.clear();
2452 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002453#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002454 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002455 delete mAudioMixer;
2456}
2457
Glenn Kasten83efdd02012-02-24 07:21:32 -08002458class CpuStats {
2459public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002460 CpuStats();
2461 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002462#ifdef DEBUG_CPU_USAGE
2463private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002464 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2465 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2466
2467 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2468
2469 int mCpuNum; // thread's current CPU number
2470 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002471#endif
2472};
2473
Glenn Kasten190a46f2012-03-06 11:27:10 -08002474CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002475#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002476 : mCpuNum(-1), mCpukHz(-1)
2477#endif
2478{
2479}
2480
2481void CpuStats::sample(const String8 &title) {
2482#ifdef DEBUG_CPU_USAGE
2483 // get current thread's delta CPU time in wall clock ns
2484 double wcNs;
2485 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2486
2487 // record sample for wall clock statistics
2488 if (valid) {
2489 mWcStats.sample(wcNs);
2490 }
2491
2492 // get the current CPU number
2493 int cpuNum = sched_getcpu();
2494
2495 // get the current CPU frequency in kHz
2496 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2497
2498 // check if either CPU number or frequency changed
2499 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2500 mCpuNum = cpuNum;
2501 mCpukHz = cpukHz;
2502 // ignore sample for purposes of cycles
2503 valid = false;
2504 }
2505
2506 // if no change in CPU number or frequency, then record sample for cycle statistics
2507 if (valid && mCpukHz > 0) {
2508 double cycles = wcNs * cpukHz * 0.000001;
2509 mHzStats.sample(cycles);
2510 }
2511
2512 unsigned n = mWcStats.n();
2513 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002514 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002515 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002516 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2517 double perLoop = elapsed / (double) n;
2518 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002519 double perLoop1k = perLoop * 0.001;
2520 double mean = mWcStats.mean();
2521 double stddev = mWcStats.stddev();
2522 double minimum = mWcStats.minimum();
2523 double maximum = mWcStats.maximum();
2524 double meanCycles = mHzStats.mean();
2525 double stddevCycles = mHzStats.stddev();
2526 double minCycles = mHzStats.minimum();
2527 double maxCycles = mHzStats.maximum();
2528 mCpuUsage.resetElapsed();
2529 mWcStats.reset();
2530 mHzStats.reset();
2531 ALOGD("CPU usage for %s over past %.1f secs\n"
2532 " (%u mixer loops at %.1f mean ms per loop):\n"
2533 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2534 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2535 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2536 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002537 elapsed * .000000001, n, perLoop * .000001,
2538 mean * .001,
2539 stddev * .001,
2540 minimum * .001,
2541 maximum * .001,
2542 mean / perLoop100,
2543 stddev / perLoop100,
2544 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002545 maximum / perLoop100,
2546 meanCycles / perLoop1k,
2547 stddevCycles / perLoop1k,
2548 minCycles / perLoop1k,
2549 maxCycles / perLoop1k);
2550
Glenn Kasten83efdd02012-02-24 07:21:32 -08002551 }
2552 }
2553#endif
2554};
2555
Glenn Kasten37d825e2012-02-24 07:21:48 -08002556void AudioFlinger::PlaybackThread::checkSilentMode_l()
2557{
2558 if (!mMasterMute) {
2559 char value[PROPERTY_VALUE_MAX];
2560 if (property_get("ro.audio.silent", value, "0") > 0) {
2561 char *endptr;
2562 unsigned long ul = strtoul(value, &endptr, 0);
2563 if (*endptr == '\0' && ul != 0) {
2564 ALOGD("Silence is golden");
2565 // The setprop command will not allow a property to be changed after
2566 // the first time it is set, so we don't have to worry about un-muting.
2567 setMasterMute_l(true);
2568 }
2569 }
2570 }
2571}
2572
Glenn Kasten000f0e32012-03-01 17:10:56 -08002573bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574{
2575 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002576
Glenn Kasten000f0e32012-03-01 17:10:56 -08002577 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002578
2579 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002581
Glenn Kasten000f0e32012-03-01 17:10:56 -08002582 // DUPLICATING
2583 // FIXME could this be made local to while loop?
2584 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002585
Glenn Kasten66fcab92012-02-24 14:59:21 -08002586 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002587 sleepTime = idleSleepTime;
2588
Glenn Kasten9f34a362012-03-20 16:46:41 -07002589 if (mType == MIXER) {
2590 sleepTimeShift = 0;
2591 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002592
Glenn Kasten83efdd02012-02-24 07:21:32 -08002593 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002594 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595
Eric Laurentfeb0db62011-07-22 09:04:31 -07002596 acquireWakeLock();
2597
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598 while (!exitPending())
2599 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002600 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002601
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002602 Vector< sp<EffectChain> > effectChains;
2603
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 processConfigEvents();
2605
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 { // scope for mLock
2607
2608 Mutex::Autolock _l(mLock);
2609
2610 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002611 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612 }
2613
Glenn Kastenfa26a852012-03-06 11:28:04 -08002614 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002615
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002617 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002618 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002620
2621 threadLoop_standby();
2622
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624 }
2625
Glenn Kasten3e074702012-02-28 18:40:35 -08002626 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627 // we're about to wait, flush the binder command buffer
2628 IPCThreadState::self()->flushCommands();
2629
Glenn Kastenfa26a852012-03-06 11:28:04 -08002630 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002631
Glenn Kastend65d73c2012-06-22 17:21:07 -07002632 if (exitPending()) {
2633 break;
2634 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635
Eric Laurentfeb0db62011-07-22 09:04:31 -07002636 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002638 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002640 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002641 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642
Eric Laurentda747442012-04-25 18:53:13 -07002643 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002644 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002645 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002646
Glenn Kasten37d825e2012-02-24 07:21:48 -08002647 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648
Glenn Kasten000f0e32012-03-01 17:10:56 -08002649 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002651 if (mType == MIXER) {
2652 sleepTimeShift = 0;
2653 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002654
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 continue;
2656 }
2657 }
2658
Glenn Kasten81028042012-04-30 18:15:12 -07002659 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002660 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661
2662 // prevent any changes in effect chain list and in each effect chain
2663 // during mixing and effect process as the audio buffers could be deleted
2664 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002665 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667
Glenn Kastenfec279f2012-03-08 07:47:15 -08002668 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002669 threadLoop_mix();
2670 } else {
2671 threadLoop_sleepTime();
2672 }
2673
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002674 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002675 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002676 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002677 }
2678
2679 // only process effects if we're going to write
2680 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002681 for (size_t i = 0; i < effectChains.size(); i ++) {
2682 effectChains[i]->process_l();
2683 }
2684 }
2685
2686 // enable changes in effect chain
2687 unlockEffectChains(effectChains);
2688
2689 // sleepTime == 0 means we must write to audio hardware
2690 if (sleepTime == 0) {
2691
2692 threadLoop_write();
2693
2694if (mType == MIXER) {
2695 // write blocked detection
2696 nsecs_t now = systemTime();
2697 nsecs_t delta = now - mLastWriteTime;
2698 if (!mStandby && delta > maxPeriod) {
2699 mNumDelayedWrites++;
2700 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002701#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002702 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002703#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002704 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2705 ns2ms(delta), mNumDelayedWrites, this);
2706 lastWarning = now;
2707 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002708 }
2709}
2710
2711 mStandby = false;
2712 } else {
2713 usleep(sleepTime);
2714 }
2715
Glenn Kasten58912562012-04-03 10:45:00 -07002716 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002717 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002718 // same lock. This will also mutate and push a new fast mixer state.
2719 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002720 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002721
Glenn Kastenfa26a852012-03-06 11:28:04 -08002722 // FIXME I don't understand the need for this here;
2723 // it was in the original code but maybe the
2724 // assignment in saveOutputTracks() makes this unnecessary?
2725 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002726
2727 // Effect chains will be actually deleted here if they were removed from
2728 // mEffectChains list during mixing or effects processing
2729 effectChains.clear();
2730
2731 // FIXME Note that the above .clear() is no longer necessary since effectChains
2732 // is now local to this block, but will keep it for now (at least until merge done).
2733 }
2734
Glenn Kasten9f34a362012-03-20 16:46:41 -07002735 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2736 if (mType == MIXER || mType == DIRECT) {
2737 // put output stream into standby mode
2738 if (!mStandby) {
2739 mOutput->stream->common.standby(&mOutput->stream->common);
2740 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002741 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002742
2743 releaseWakeLock();
2744
2745 ALOGV("Thread %p type %d exiting", this, mType);
2746 return false;
2747}
2748
Glenn Kasten58912562012-04-03 10:45:00 -07002749void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2750{
Glenn Kasten58912562012-04-03 10:45:00 -07002751 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2752}
2753
2754void AudioFlinger::MixerThread::threadLoop_write()
2755{
2756 // FIXME we should only do one push per cycle; confirm this is true
2757 // Start the fast mixer if it's not already running
2758 if (mFastMixer != NULL) {
2759 FastMixerStateQueue *sq = mFastMixer->sq();
2760 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002761 if (state->mCommand != FastMixerState::MIX_WRITE &&
2762 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002763 if (state->mCommand == FastMixerState::COLD_IDLE) {
2764 int32_t old = android_atomic_inc(&mFastMixerFutex);
2765 if (old == -1) {
2766 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2767 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002768#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002769 if (mAudioWatchdog != 0) {
2770 mAudioWatchdog->resume();
2771 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002772#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002773 }
2774 state->mCommand = FastMixerState::MIX_WRITE;
2775 sq->end();
2776 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002777 if (kUseFastMixer == FastMixer_Dynamic) {
2778 mNormalSink = mPipeSink;
2779 }
Glenn Kasten58912562012-04-03 10:45:00 -07002780 } else {
2781 sq->end(false /*didModify*/);
2782 }
2783 }
2784 PlaybackThread::threadLoop_write();
2785}
2786
Glenn Kasten000f0e32012-03-01 17:10:56 -08002787// shared by MIXER and DIRECT, overridden by DUPLICATING
2788void AudioFlinger::PlaybackThread::threadLoop_write()
2789{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002790 // FIXME rewrite to reduce number of system calls
2791 mLastWriteTime = systemTime();
2792 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002793 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002794
Eric Laurent67c0a582012-05-01 19:31:12 -07002795 // If an NBAIO sink is present, use it to write the normal mixer's submix
2796 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002797#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002798 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002799#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002800 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002801#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002802 // update the setpoint when gScreenState changes
2803 uint32_t screenState = gScreenState;
2804 if (screenState != mScreenState) {
2805 mScreenState = screenState;
2806 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2807 if (pipe != NULL) {
2808 pipe->setAvgFrames((mScreenState & 1) ?
2809 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2810 }
2811 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002812 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002813#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002814 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002815#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002816 if (framesWritten > 0) {
2817 bytesWritten = framesWritten << mBitShift;
2818 } else {
2819 bytesWritten = framesWritten;
2820 }
2821 // otherwise use the HAL / AudioStreamOut directly
2822 } else {
2823 // Direct output thread.
2824 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002825 }
2826
Glenn Kastend65d73c2012-06-22 17:21:07 -07002827 if (bytesWritten > 0) {
2828 mBytesWritten += mixBufferSize;
2829 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002830 mNumWrites++;
2831 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002832}
2833
Glenn Kasten58912562012-04-03 10:45:00 -07002834void AudioFlinger::MixerThread::threadLoop_standby()
2835{
2836 // Idle the fast mixer if it's currently running
2837 if (mFastMixer != NULL) {
2838 FastMixerStateQueue *sq = mFastMixer->sq();
2839 FastMixerState *state = sq->begin();
2840 if (!(state->mCommand & FastMixerState::IDLE)) {
2841 state->mCommand = FastMixerState::COLD_IDLE;
2842 state->mColdFutexAddr = &mFastMixerFutex;
2843 state->mColdGen++;
2844 mFastMixerFutex = 0;
2845 sq->end();
2846 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2847 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002848 if (kUseFastMixer == FastMixer_Dynamic) {
2849 mNormalSink = mOutputSink;
2850 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002851#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002852 if (mAudioWatchdog != 0) {
2853 mAudioWatchdog->pause();
2854 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002855#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002856 } else {
2857 sq->end(false /*didModify*/);
2858 }
2859 }
2860 PlaybackThread::threadLoop_standby();
2861}
2862
Glenn Kasten000f0e32012-03-01 17:10:56 -08002863// shared by MIXER and DIRECT, overridden by DUPLICATING
2864void AudioFlinger::PlaybackThread::threadLoop_standby()
2865{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002866 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002867 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002868}
2869
2870void AudioFlinger::MixerThread::threadLoop_mix()
2871{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002872 // obtain the presentation timestamp of the next output buffer
2873 int64_t pts;
2874 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002875
John Grossman2c3b2da2012-08-02 17:08:54 -07002876 if (mNormalSink != 0) {
2877 status = mNormalSink->getNextWriteTimestamp(&pts);
2878 } else {
2879 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002880 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002881
Glenn Kasten952eeb22012-03-06 11:30:57 -08002882 if (status != NO_ERROR) {
2883 pts = AudioBufferProvider::kInvalidPTS;
2884 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002885
Glenn Kasten952eeb22012-03-06 11:30:57 -08002886 // mix buffers...
2887 mAudioMixer->process(pts);
2888 // increase sleep time progressively when application underrun condition clears.
2889 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2890 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2891 // such that we would underrun the audio HAL.
2892 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2893 sleepTimeShift--;
2894 }
2895 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002896 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002897 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002898}
2899
2900void AudioFlinger::MixerThread::threadLoop_sleepTime()
2901{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002902 // If no tracks are ready, sleep once for the duration of an output
2903 // buffer size, then write 0s to the output
2904 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002905 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002906 sleepTime = activeSleepTime >> sleepTimeShift;
2907 if (sleepTime < kMinThreadSleepTimeUs) {
2908 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002910 // reduce sleep time in case of consecutive application underruns to avoid
2911 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2912 // duration we would end up writing less data than needed by the audio HAL if
2913 // the condition persists.
2914 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2915 sleepTimeShift++;
2916 }
2917 } else {
2918 sleepTime = idleSleepTime;
2919 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002920 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002921 memset (mMixBuffer, 0, mixBufferSize);
2922 sleepTime = 0;
Glenn Kasten26c77552012-11-16 12:01:44 -08002923 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002924 "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002925 }
2926 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927}
2928
2929// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002930AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002931 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932{
2933
Glenn Kasten29c23c32012-01-26 13:37:52 -08002934 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002936 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 size_t mixedTracks = 0;
2938 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002939 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002940 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002941 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942
2943 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002944 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945
Eric Laurent571d49c2010-08-11 05:20:11 -07002946 if (masterMute) {
2947 masterVolume = 0;
2948 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002950 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002952 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002953 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 masterVolume = (float)((v + (1 << 23)) >> 24);
2955 chain.clear();
2956 }
2957
Glenn Kasten288ed212012-04-25 17:52:27 -07002958 // prepare a new state to push
2959 FastMixerStateQueue *sq = NULL;
2960 FastMixerState *state = NULL;
2961 bool didModify = false;
2962 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2963 if (mFastMixer != NULL) {
2964 sq = mFastMixer->sq();
2965 state = sq->begin();
2966 }
2967
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002969 sp<Track> t = mActiveTracks[i].promote();
Glenn Kastend65d73c2012-06-22 17:21:07 -07002970 if (t == 0) {
2971 continue;
2972 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002974 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002976
Glenn Kasten288ed212012-04-25 17:52:27 -07002977 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002978 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002979
2980 // It's theoretically possible (though unlikely) for a fast track to be created
2981 // and then removed within the same normal mix cycle. This is not a problem, as
2982 // the track never becomes active so it's fast mixer slot is never touched.
2983 // The converse, of removing an (active) track and then creating a new track
2984 // at the identical fast mixer slot within the same normal mix cycle,
2985 // is impossible because the slot isn't marked available until the end of each cycle.
2986 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002987 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2988 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002989 FastTrack *fastTrack = &state->mFastTracks[j];
2990
2991 // Determine whether the track is currently in underrun condition,
2992 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002993 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2994 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002995 uint32_t recentFull = (underruns.mBitFields.mFull -
2996 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2997 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2998 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2999 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3000 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3001 uint32_t recentUnderruns = recentPartial + recentEmpty;
3002 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003003 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003004 // or stopped which can occur when flush() is called while active
3005 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003006 track->mUnderrunCount += recentUnderruns;
3007 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003008
Glenn Kastend08f48c2012-05-01 18:14:02 -07003009 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003010 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003011 bool isActive = true;
3012 switch (track->mState) {
3013 case TrackBase::STOPPING_1:
3014 // track stays active in STOPPING_1 state until first underrun
3015 if (recentUnderruns > 0) {
3016 track->mState = TrackBase::STOPPING_2;
3017 }
3018 break;
3019 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003020 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003021 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003022 break;
3023 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003024 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003025 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003026 break;
3027 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003028 if (recentFull > 0 || recentPartial > 0) {
3029 // track has provided at least some frames recently: reset retry count
3030 track->mRetryCount = kMaxTrackRetries;
3031 }
3032 if (recentUnderruns == 0) {
3033 // no recent underruns: stay active
3034 break;
3035 }
3036 // there has recently been an underrun of some kind
3037 if (track->sharedBuffer() == 0) {
3038 // were any of the recent underruns "empty" (no frames available)?
3039 if (recentEmpty == 0) {
3040 // no, then ignore the partial underruns as they are allowed indefinitely
3041 break;
3042 }
3043 // there has recently been an "empty" underrun: decrement the retry counter
3044 if (--(track->mRetryCount) > 0) {
3045 break;
3046 }
3047 // indicate to client process that the track was disabled because of underrun;
3048 // it will then automatically call start() when data is available
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08003049 android_atomic_or(CBLK_DISABLED, &track->mCblk->flags);
Glenn Kasten09474df2012-05-10 14:48:07 -07003050 // remove from active list, but state remains ACTIVE [confusing but true]
3051 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003052 break;
3053 }
3054 // fall through
3055 case TrackBase::STOPPING_2:
3056 case TrackBase::PAUSED:
3057 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003058 case TrackBase::STOPPED:
3059 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003060 // Check for presentation complete if track is inactive
3061 // We have consumed all the buffers of this track.
3062 // This would be incomplete if we auto-paused on underrun
3063 {
3064 size_t audioHALFrames =
3065 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Glenn Kasten26c77552012-11-16 12:01:44 -08003066 size_t framesWritten = mBytesWritten / mFrameSize;
Glenn Kasten291f8242012-10-18 15:51:31 -07003067 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003068 // track stays in active list until presentation is complete
3069 break;
3070 }
3071 }
3072 if (track->isStopping_2()) {
3073 track->mState = TrackBase::STOPPED;
3074 }
3075 if (track->isStopped()) {
3076 // Can't reset directly, as fast mixer is still polling this track
3077 // track->reset();
3078 // So instead mark this track as needing to be reset after push with ack
3079 resetMask |= 1 << i;
3080 }
3081 isActive = false;
3082 break;
3083 case TrackBase::IDLE:
3084 default:
3085 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003086 }
3087
3088 if (isActive) {
3089 // was it previously inactive?
3090 if (!(state->mTrackMask & (1 << j))) {
3091 ExtendedAudioBufferProvider *eabp = track;
3092 VolumeProvider *vp = track;
3093 fastTrack->mBufferProvider = eabp;
3094 fastTrack->mVolumeProvider = vp;
3095 fastTrack->mSampleRate = track->mSampleRate;
3096 fastTrack->mChannelMask = track->mChannelMask;
3097 fastTrack->mGeneration++;
3098 state->mTrackMask |= 1 << j;
3099 didModify = true;
3100 // no acknowledgement required for newly active tracks
3101 }
3102 // cache the combined master volume and stream type volume for fast mixer; this
3103 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3104 track->mCachedVolume = track->isMuted() ?
3105 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3106 ++fastTracks;
3107 } else {
3108 // was it previously active?
3109 if (state->mTrackMask & (1 << j)) {
3110 fastTrack->mBufferProvider = NULL;
3111 fastTrack->mGeneration++;
3112 state->mTrackMask &= ~(1 << j);
3113 didModify = true;
3114 // If any fast tracks were removed, we must wait for acknowledgement
3115 // because we're about to decrement the last sp<> on those tracks.
3116 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003117 } else {
3118 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003119 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003120 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003121 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003122 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003123 }
3124 continue;
3125 }
3126
3127 { // local variable scope to avoid goto warning
3128
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 audio_track_cblk_t* cblk = track->cblk();
3130
3131 // The first time a track is added we wait
3132 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003133 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003134 // make sure that we have enough frames to mix one full buffer.
3135 // enforce this condition only once to enable draining the buffer in case the client
3136 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003137 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003138 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003139 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003140 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003141 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten3b16c762012-11-14 08:44:39 -08003142 if (t->sampleRate() == mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003143 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003144 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003145 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003146 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003147 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003148 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003149 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3150 // the minimum track buffer size is normally twice the number of frames necessary
3151 // to fill one buffer and the resampler should not leave more than one buffer worth
3152 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003153 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003154 }
3155 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003156 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 !track->isPaused() && !track->isTerminated())
3158 {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003159 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server,
3160 this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161
3162 mixedTracks++;
3163
3164 // track->mainBuffer() != mMixBuffer means there is an effect chain
3165 // connected to the track
3166 chain.clear();
3167 if (track->mainBuffer() != mMixBuffer) {
3168 chain = getEffectChain_l(track->sessionId());
3169 // Delegate volume control to effect in track effect chain if needed
3170 if (chain != 0) {
3171 tracksWithEffect++;
3172 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003173 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3174 "session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003175 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 }
3177 }
3178
3179
3180 int param = AudioMixer::VOLUME;
3181 if (track->mFillingUpStatus == Track::FS_FILLED) {
3182 // no ramp for the first volume setting
3183 track->mFillingUpStatus = Track::FS_ACTIVE;
3184 if (track->mState == TrackBase::RESUMING) {
3185 track->mState = TrackBase::ACTIVE;
3186 param = AudioMixer::RAMP_VOLUME;
3187 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003188 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 } else if (cblk->server != 0) {
3190 // If the track is stopped before the first frame was mixed,
3191 // do not apply ramp
3192 param = AudioMixer::RAMP_VOLUME;
3193 }
3194
3195 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003196 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003197 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003198 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003199 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 if (track->isPausing()) {
3201 track->setPaused();
3202 }
3203 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003204
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003206 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003208 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003209 vl = vlr & 0xFFFF;
3210 vr = vlr >> 16;
3211 // track volumes come from shared memory, so can't be trusted and must be clamped
3212 if (vl > MAX_GAIN_INT) {
3213 ALOGV("Track left volume out of range: %04X", vl);
3214 vl = MAX_GAIN_INT;
3215 }
3216 if (vr > MAX_GAIN_INT) {
3217 ALOGV("Track right volume out of range: %04X", vr);
3218 vr = MAX_GAIN_INT;
3219 }
3220 // now apply the master volume and stream type volume
3221 vl = (uint32_t)(v * vl) << 12;
3222 vr = (uint32_t)(v * vr) << 12;
3223 // assuming master volume and stream type volume each go up to 1.0,
3224 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225
Glenn Kasten05632a52012-01-03 14:22:33 -08003226 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3227 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003228 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003229 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003230 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003231 }
3232 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003234 // Delegate volume control to effect in track effect chain if needed
3235 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3236 // Do not ramp volume if volume is controlled by effect
3237 param = AudioMixer::VOLUME;
3238 track->mHasVolumeController = true;
3239 } else {
3240 // force no volume ramp when volume controller was just disabled or removed
3241 // from effect chain to avoid volume spike
3242 if (track->mHasVolumeController) {
3243 param = AudioMixer::VOLUME;
3244 }
3245 track->mHasVolumeController = false;
3246 }
3247
3248 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003249 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003250 vl = (vl + (1 << 11)) >> 12;
Glenn Kastend65d73c2012-06-22 17:21:07 -07003251 if (vl > MAX_GAIN_INT) {
3252 vl = MAX_GAIN_INT;
3253 }
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003254 vr = (vr + (1 << 11)) >> 12;
Glenn Kastend65d73c2012-06-22 17:21:07 -07003255 if (vr > MAX_GAIN_INT) {
3256 vr = MAX_GAIN_INT;
3257 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003258
Glenn Kastend65d73c2012-06-22 17:21:07 -07003259 if (va > MAX_GAIN_INT) {
3260 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003264 mAudioMixer->setBufferProvider(name, track);
3265 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003267 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3268 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3269 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003271 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 AudioMixer::TRACK,
3273 AudioMixer::FORMAT, (void *)track->format());
3274 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003275 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003277 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003279 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 AudioMixer::RESAMPLE,
3281 AudioMixer::SAMPLE_RATE,
3282 (void *)(cblk->sampleRate));
3283 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003284 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 AudioMixer::TRACK,
3286 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3287 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003288 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 AudioMixer::TRACK,
3290 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3291
3292 // reset retry count
3293 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003294
Eric Laurent27741442012-01-17 19:20:12 -08003295 // If one track is ready, set the mixer ready if:
3296 // - the mixer was not ready during previous round OR
3297 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003298 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003299 mixerStatus != MIXER_TRACKS_ENABLED) {
3300 mixerStatus = MIXER_TRACKS_READY;
3301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003303 // clear effect chain input buffer if an active track underruns to avoid sending
3304 // previous audio buffer again to effects
3305 chain = getEffectChain_l(track->sessionId());
3306 if (chain != 0) {
3307 chain->clearInputBuffer();
3308 }
3309
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003310 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user,
3311 cblk->server, this);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003312 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003313 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 // We have consumed all the buffers of this track.
3315 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003316 // TODO: use actual buffer filling status instead of latency when available from
3317 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003318 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Glenn Kasten26c77552012-11-16 12:01:44 -08003319 size_t framesWritten = mBytesWritten / mFrameSize;
Glenn Kasten291f8242012-10-18 15:51:31 -07003320 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003321 if (track->isStopped()) {
3322 track->reset();
3323 }
Eric Laurenta011e352012-03-29 15:51:43 -07003324 tracksToRemove->add(track);
3325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003327 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 // No buffers for this track. Give it a few chances to
3329 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003330 if (--(track->mRetryCount) <= 0) {
3331 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003333 // indicate to client process that the track was disabled because of underrun;
3334 // it will then automatically call start() when data is available
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08003335 android_atomic_or(CBLK_DISABLED, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003336 // If one track is not ready, mark the mixer also not ready if:
3337 // - the mixer was ready during previous round OR
3338 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003339 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003340 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 mixerStatus = MIXER_TRACKS_ENABLED;
3342 }
3343 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003344 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 }
Glenn Kasten58912562012-04-03 10:45:00 -07003346
3347 } // local variable scope to avoid goto warning
3348track_is_ready: ;
3349
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 }
3351
Glenn Kasten288ed212012-04-25 17:52:27 -07003352 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003353 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003354 if (didModify) {
3355 state->mFastTracksGen++;
3356 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3357 if (kUseFastMixer == FastMixer_Dynamic &&
3358 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3359 state->mCommand = FastMixerState::COLD_IDLE;
3360 state->mColdFutexAddr = &mFastMixerFutex;
3361 state->mColdGen++;
3362 mFastMixerFutex = 0;
3363 if (kUseFastMixer == FastMixer_Dynamic) {
3364 mNormalSink = mOutputSink;
3365 }
3366 // If we go into cold idle, need to wait for acknowledgement
3367 // so that fast mixer stops doing I/O.
3368 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003369 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003370 }
3371 sq->end();
3372 }
3373 if (sq != NULL) {
3374 sq->end(didModify);
3375 sq->push(block);
3376 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003377#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003378 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3379 mAudioWatchdog->pause();
3380 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003381#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003382
3383 // Now perform the deferred reset on fast tracks that have stopped
3384 while (resetMask != 0) {
3385 size_t i = __builtin_ctz(resetMask);
3386 ALOG_ASSERT(i < count);
3387 resetMask &= ~(1 << i);
3388 sp<Track> t = mActiveTracks[i].promote();
Glenn Kastend65d73c2012-06-22 17:21:07 -07003389 if (t == 0) {
3390 continue;
3391 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003392 Track* track = t.get();
3393 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3394 track->reset();
3395 }
Glenn Kasten58912562012-04-03 10:45:00 -07003396
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 // remove all the tracks that need to be...
3398 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003399 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 for (size_t i=0 ; i<count ; i++) {
3401 const sp<Track>& track = tracksToRemove->itemAt(i);
3402 mActiveTracks.remove(track);
3403 if (track->mainBuffer() != mMixBuffer) {
3404 chain = getEffectChain_l(track->sessionId());
3405 if (chain != 0) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003406 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3407 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003408 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409 }
3410 }
3411 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003412 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 }
3414 }
3415 }
3416
3417 // mix buffer must be cleared if all tracks are connected to an
3418 // effect chain as in this case the mixer will not write to
3419 // mix buffer and track effects will accumulate into it
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003420 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3421 (mixedTracks == 0 && fastTracks > 0)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003422 // FIXME as a performance optimization, should remember previous zero status
3423 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424 }
3425
Glenn Kasten58912562012-04-03 10:45:00 -07003426 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003427 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003428 if (fastTracks > 0) {
3429 mixerStatus = MIXER_TRACKS_READY;
3430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431 return mixerStatus;
3432}
3433
Glenn Kasten66fcab92012-02-24 14:59:21 -08003434/*
3435The derived values that are cached:
3436 - mixBufferSize from frame count * frame size
3437 - activeSleepTime from activeSleepTimeUs()
3438 - idleSleepTime from idleSleepTimeUs()
3439 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3440 - maxPeriod from frame count and sample rate (MIXER only)
3441
3442The parameters that affect these derived values are:
3443 - frame count
3444 - frame size
3445 - sample rate
3446 - device type: A2DP or not
3447 - device latency
3448 - format: PCM or not
3449 - active sleep time
3450 - idle sleep time
3451*/
3452
3453void AudioFlinger::PlaybackThread::cacheParameters_l()
3454{
Glenn Kasten58912562012-04-03 10:45:00 -07003455 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003456 activeSleepTime = activeSleepTimeUs();
3457 idleSleepTime = idleSleepTimeUs();
3458}
3459
Eric Laurent22167852012-06-20 12:26:32 -07003460void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461{
Steve Block3856b092011-10-20 11:56:00 +01003462 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003463 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003465
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 size_t size = mTracks.size();
3467 for (size_t i = 0; i < size; i++) {
3468 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003469 if (t->streamType() == streamType) {
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08003470 android_atomic_or(CBLK_INVALID, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 }
3473 }
3474}
3475
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003477int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003479 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480}
3481
3482// deleteTrackName_l() must be called with ThreadBase::mLock held
3483void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3484{
Steve Block3856b092011-10-20 11:56:00 +01003485 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 mAudioMixer->deleteTrackName(name);
3487}
3488
3489// checkForNewParameters_l() must be called with ThreadBase::mLock held
3490bool AudioFlinger::MixerThread::checkForNewParameters_l()
3491{
Glenn Kasten58912562012-04-03 10:45:00 -07003492 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3493 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 bool reconfig = false;
3495
3496 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003497
3498 if (mFastMixer != NULL) {
3499 FastMixerStateQueue *sq = mFastMixer->sq();
3500 FastMixerState *state = sq->begin();
3501 if (!(state->mCommand & FastMixerState::IDLE)) {
3502 previousCommand = state->mCommand;
3503 state->mCommand = FastMixerState::HOT_IDLE;
3504 sq->end();
3505 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3506 } else {
3507 sq->end(false /*didModify*/);
3508 }
3509 }
3510
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 status_t status = NO_ERROR;
3512 String8 keyValuePair = mNewParameters[0];
3513 AudioParameter param = AudioParameter(keyValuePair);
3514 int value;
3515
3516 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3517 reconfig = true;
3518 }
3519 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003520 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003521 status = BAD_VALUE;
3522 } else {
3523 reconfig = true;
3524 }
3525 }
3526 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003527 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003528 status = BAD_VALUE;
3529 } else {
3530 reconfig = true;
3531 }
3532 }
3533 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3534 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003535 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536 // if frame count is changed after track creation
3537 if (!mTracks.isEmpty()) {
3538 status = INVALID_OPERATION;
3539 } else {
3540 reconfig = true;
3541 }
3542 }
3543 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003544#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003545 // when changing the audio output device, call addBatteryData to notify
3546 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003547 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003548 uint32_t params = 0;
3549 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003550 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003551 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3552 }
3553
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003554 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003555 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003556 // check if any other device (except speaker) is on
3557 if (value & deviceWithoutSpeaker ) {
3558 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3559 }
3560
3561 if (params != 0) {
3562 addBatteryData(params);
3563 }
3564 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003565#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003566
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 // forward device change to effects that have requested to be
3568 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003569 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003571 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003572 }
3573 }
3574
3575 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003576 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003577 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003579 mOutput->stream->common.standby(&mOutput->stream->common);
3580 mStandby = true;
3581 mBytesWritten = 0;
3582 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003583 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584 }
3585 if (status == NO_ERROR && reconfig) {
3586 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003587 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3588 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003590 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003592 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Glenn Kastend65d73c2012-06-22 17:21:07 -07003593 if (name < 0) {
3594 break;
3595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 mTracks[i]->mName = name;
3597 // limit track sample rate to 2 x new output sample rate
3598 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3599 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3600 }
3601 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003602 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 }
3604 }
3605
3606 mNewParameters.removeAt(0);
3607
3608 mParamStatus = status;
3609 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003610 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3611 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003612 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613 }
Glenn Kasten58912562012-04-03 10:45:00 -07003614
3615 if (!(previousCommand & FastMixerState::IDLE)) {
3616 ALOG_ASSERT(mFastMixer != NULL);
3617 FastMixerStateQueue *sq = mFastMixer->sq();
3618 FastMixerState *state = sq->begin();
3619 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3620 state->mCommand = previousCommand;
3621 sq->end();
3622 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3623 }
3624
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 return reconfig;
3626}
3627
Glenn Kastend06785b2012-09-30 12:29:28 -07003628void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629{
Glenn Kastend06785b2012-09-30 12:29:28 -07003630 NBAIO_Source *teeSource = source.get();
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003631 if (teeSource != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07003632 char teeTime[16];
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003633 struct timeval tv;
3634 gettimeofday(&tv, NULL);
3635 struct tm tm;
3636 localtime_r(&tv.tv_sec, &tm);
Glenn Kastend06785b2012-09-30 12:29:28 -07003637 strftime(teeTime, sizeof(teeTime), "%T", &tm);
3638 char teePath[64];
3639 sprintf(teePath, "/data/misc/media/%s_%d.wav", teeTime, id);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003640 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3641 if (teeFd >= 0) {
3642 char wavHeader[44];
3643 memcpy(wavHeader,
3644 "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",
3645 sizeof(wavHeader));
3646 NBAIO_Format format = teeSource->format();
3647 unsigned channelCount = Format_channelCount(format);
3648 ALOG_ASSERT(channelCount <= FCC_2);
Glenn Kasten3b16c762012-11-14 08:44:39 -08003649 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003650 wavHeader[22] = channelCount; // number of channels
3651 wavHeader[24] = sampleRate; // sample rate
3652 wavHeader[25] = sampleRate >> 8;
3653 wavHeader[32] = channelCount * 2; // block alignment
3654 write(teeFd, wavHeader, sizeof(wavHeader));
3655 size_t total = 0;
3656 bool firstRead = true;
3657 for (;;) {
3658#define TEE_SINK_READ 1024
3659 short buffer[TEE_SINK_READ * FCC_2];
3660 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003661 ssize_t actual = teeSource->read(buffer, count,
3662 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003663 bool wasFirstRead = firstRead;
3664 firstRead = false;
3665 if (actual <= 0) {
3666 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3667 continue;
3668 }
3669 break;
3670 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003671 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003672 write(teeFd, buffer, actual * channelCount * sizeof(short));
3673 total += actual;
3674 }
3675 lseek(teeFd, (off_t) 4, SEEK_SET);
3676 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3677 write(teeFd, &temp, sizeof(temp));
3678 lseek(teeFd, (off_t) 40, SEEK_SET);
3679 temp = total * channelCount * sizeof(short);
3680 write(teeFd, &temp, sizeof(temp));
3681 close(teeFd);
3682 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3683 } else {
3684 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3685 }
3686 }
Glenn Kastend06785b2012-09-30 12:29:28 -07003687}
3688
3689void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3690{
3691 const size_t SIZE = 256;
3692 char buffer[SIZE];
3693 String8 result;
3694
3695 PlaybackThread::dumpInternals(fd, args);
3696
3697 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3698 result.append(buffer);
3699 write(fd, result.string(), result.size());
3700
3701 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3702 FastMixerDumpState copy = mFastMixerDumpState;
3703 copy.dump(fd);
3704
3705#ifdef STATE_QUEUE_DUMP
3706 // Similar for state queue
3707 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3708 observerCopy.dump(fd);
3709 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3710 mutatorCopy.dump(fd);
3711#endif
3712
3713 // Write the tee output to a .wav file
3714 dumpTee(fd, mTeeSource, mId);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003715
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003716#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003717 if (mAudioWatchdog != 0) {
3718 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3719 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3720 wdCopy.dump(fd);
3721 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003722#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723}
3724
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003725uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726{
Glenn Kasten58912562012-04-03 10:45:00 -07003727 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728}
3729
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003730uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003731{
Glenn Kasten58912562012-04-03 10:45:00 -07003732 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003733}
3734
Glenn Kasten66fcab92012-02-24 14:59:21 -08003735void AudioFlinger::MixerThread::cacheParameters_l()
3736{
3737 PlaybackThread::cacheParameters_l();
3738
3739 // FIXME: Relaxed timing because of a certain device that can't meet latency
3740 // Should be reduced to 2x after the vendor fixes the driver issue
3741 // increase threshold again due to low power audio mode. The way this warning
3742 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003743 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003744}
3745
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003747AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003748 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003749 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003750 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003751{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752}
3753
3754AudioFlinger::DirectOutputThread::~DirectOutputThread()
3755{
3756}
3757
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003758AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3759 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003760)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003762 sp<Track> trackToRemove;
3763
Glenn Kastenfec279f2012-03-08 07:47:15 -08003764 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765
Glenn Kasten952eeb22012-03-06 11:30:57 -08003766 // find out which tracks need to be processed
3767 if (mActiveTracks.size() != 0) {
3768 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003769 // The track died recently
Glenn Kastend65d73c2012-06-22 17:21:07 -07003770 if (t == 0) {
3771 return MIXER_IDLE;
3772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 Track* const track = t.get();
3775 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776
Glenn Kasten952eeb22012-03-06 11:30:57 -08003777 // The first time a track is added we wait
3778 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003779 uint32_t minFrames;
3780 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3781 minFrames = mNormalFrameCount;
3782 } else {
3783 minFrames = 1;
3784 }
3785 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003786 !track->isPaused() && !track->isTerminated())
3787 {
Glenn Kasten26dd66e2012-10-18 15:51:03 -07003788 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789
Glenn Kasten952eeb22012-03-06 11:30:57 -08003790 if (track->mFillingUpStatus == Track::FS_FILLED) {
3791 track->mFillingUpStatus = Track::FS_ACTIVE;
3792 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003793 if (track->mState == TrackBase::RESUMING) {
3794 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003795 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003796 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003797
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 // compute volume for this track
3799 float left, right;
3800 if (track->isMuted() || mMasterMute || track->isPausing() ||
3801 mStreamTypes[track->streamType()].mute) {
3802 left = right = 0;
3803 if (track->isPausing()) {
3804 track->setPaused();
3805 }
3806 } else {
3807 float typeVolume = mStreamTypes[track->streamType()].volume;
3808 float v = mMasterVolume * typeVolume;
3809 uint32_t vlr = cblk->getVolumeLR();
3810 float v_clamped = v * (vlr & 0xFFFF);
Glenn Kastend65d73c2012-06-22 17:21:07 -07003811 if (v_clamped > MAX_GAIN) {
3812 v_clamped = MAX_GAIN;
3813 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003814 left = v_clamped/MAX_GAIN;
3815 v_clamped = v * (vlr >> 16);
Glenn Kastend65d73c2012-06-22 17:21:07 -07003816 if (v_clamped > MAX_GAIN) {
3817 v_clamped = MAX_GAIN;
3818 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003819 right = v_clamped/MAX_GAIN;
3820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821
Glenn Kasten952eeb22012-03-06 11:30:57 -08003822 if (left != mLeftVolFloat || right != mRightVolFloat) {
3823 mLeftVolFloat = left;
3824 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825
Glenn Kasten952eeb22012-03-06 11:30:57 -08003826 // Convert volumes from float to 8.24
3827 uint32_t vl = (uint32_t)(left * (1 << 24));
3828 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829
Glenn Kasten952eeb22012-03-06 11:30:57 -08003830 // Delegate volume control to effect in track effect chain if needed
3831 // only one effect chain can be present on DirectOutputThread, so if
3832 // there is one, the track is connected to it
3833 if (!mEffectChains.isEmpty()) {
3834 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003835 mEffectChains[0]->setVolume_l(&vl, &vr);
3836 left = (float)vl / (1 << 24);
3837 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003838 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003839 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003840 }
3841
3842 // reset retry count
3843 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003844 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003845 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003846 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003847 // clear effect chain input buffer if an active track underruns to avoid sending
3848 // previous audio buffer again to effects
3849 if (!mEffectChains.isEmpty()) {
3850 mEffectChains[0]->clearInputBuffer();
3851 }
3852
Glenn Kasten26dd66e2012-10-18 15:51:03 -07003853 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003854 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003855 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003856 // We have consumed all the buffers of this track.
3857 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003858 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003859 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Glenn Kasten26c77552012-11-16 12:01:44 -08003860 size_t framesWritten = mBytesWritten / mFrameSize;
Glenn Kasten291f8242012-10-18 15:51:31 -07003861 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003862 if (track->isStopped()) {
3863 track->reset();
3864 }
Eric Laurenta011e352012-03-29 15:51:43 -07003865 trackToRemove = track;
3866 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003867 } else {
3868 // No buffers for this track. Give it a few chances to
3869 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003870 if (--(track->mRetryCount) <= 0) {
3871 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003872 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003873 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003874 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875 }
3876 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003877 }
3878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003880 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003881 // remove all the tracks that need to be...
3882 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003883 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003884 mActiveTracks.remove(trackToRemove);
3885 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003886 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003887 trackToRemove->sessionId());
3888 mEffectChains[0]->decActiveTrackCnt();
3889 }
3890 if (trackToRemove->isTerminated()) {
3891 removeTrack_l(trackToRemove);
3892 }
3893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894
Glenn Kastenfec279f2012-03-08 07:47:15 -08003895 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003896}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897
Glenn Kasten000f0e32012-03-01 17:10:56 -08003898void AudioFlinger::DirectOutputThread::threadLoop_mix()
3899{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003900 AudioBufferProvider::Buffer buffer;
3901 size_t frameCount = mFrameCount;
3902 int8_t *curBuf = (int8_t *)mMixBuffer;
3903 // output audio to hardware
3904 while (frameCount) {
3905 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003906 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003907 if (CC_UNLIKELY(buffer.raw == NULL)) {
3908 memset(curBuf, 0, frameCount * mFrameSize);
3909 break;
3910 }
3911 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3912 frameCount -= buffer.frameCount;
3913 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003914 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003915 }
3916 sleepTime = 0;
3917 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003918 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003919
Glenn Kasten000f0e32012-03-01 17:10:56 -08003920}
3921
3922void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3923{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003924 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003925 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003926 sleepTime = activeSleepTime;
3927 } else {
3928 sleepTime = idleSleepTime;
3929 }
3930 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003931 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003932 sleepTime = 0;
3933 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934}
3935
3936// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003937int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3938 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939{
3940 return 0;
3941}
3942
3943// deleteTrackName_l() must be called with ThreadBase::mLock held
3944void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3945{
3946}
3947
3948// checkForNewParameters_l() must be called with ThreadBase::mLock held
3949bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3950{
3951 bool reconfig = false;
3952
3953 while (!mNewParameters.isEmpty()) {
3954 status_t status = NO_ERROR;
3955 String8 keyValuePair = mNewParameters[0];
3956 AudioParameter param = AudioParameter(keyValuePair);
3957 int value;
3958
3959 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3960 // do not accept frame count changes if tracks are open as the track buffer
3961 // size depends on frame count and correct behavior would not be garantied
3962 // if frame count is changed after track creation
3963 if (!mTracks.isEmpty()) {
3964 status = INVALID_OPERATION;
3965 } else {
3966 reconfig = true;
3967 }
3968 }
3969 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003970 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003971 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003973 mOutput->stream->common.standby(&mOutput->stream->common);
3974 mStandby = true;
3975 mBytesWritten = 0;
3976 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003977 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 }
3979 if (status == NO_ERROR && reconfig) {
3980 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07003981 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003982 }
3983 }
3984
3985 mNewParameters.removeAt(0);
3986
3987 mParamStatus = status;
3988 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003989 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3990 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003991 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 }
3993 return reconfig;
3994}
3995
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003996uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997{
3998 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003999 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004000 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 } else {
4002 time = 10000;
4003 }
4004 return time;
4005}
4006
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004007uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008{
4009 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004010 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004011 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012 } else {
4013 time = 10000;
4014 }
4015 return time;
4016}
4017
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004018uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004019{
4020 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004021 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004022 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4023 } else {
4024 time = 10000;
4025 }
4026 return time;
4027}
4028
Glenn Kasten66fcab92012-02-24 14:59:21 -08004029void AudioFlinger::DirectOutputThread::cacheParameters_l()
4030{
4031 PlaybackThread::cacheParameters_l();
4032
4033 // use shorter standby delay as on normal output to release
4034 // hardware resources as soon as possible
4035 standbyDelay = microseconds(activeSleepTime*2);
4036}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004037
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038// ----------------------------------------------------------------------------
4039
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004040AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004041 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004042 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4043 DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004044 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046 addOutputTrack(mainThread);
4047}
4048
4049AudioFlinger::DuplicatingThread::~DuplicatingThread()
4050{
4051 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4052 mOutputTracks[i]->destroy();
4053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054}
4055
Glenn Kasten000f0e32012-03-01 17:10:56 -08004056void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004058 // mix buffers...
4059 if (outputsReady(outputTracks)) {
4060 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4061 } else {
4062 memset(mMixBuffer, 0, mixBufferSize);
4063 }
4064 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004065 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004066 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004067}
4068
4069void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4070{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004071 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004072 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004073 sleepTime = activeSleepTime;
4074 } else {
4075 sleepTime = idleSleepTime;
4076 }
4077 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004078 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4079 writeFrames = mNormalFrameCount;
4080 memset(mMixBuffer, 0, mixBufferSize);
4081 } else {
4082 // flush remaining overflow buffers in output tracks
4083 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004084 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004085 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004086 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004087}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088
Glenn Kasten000f0e32012-03-01 17:10:56 -08004089void AudioFlinger::DuplicatingThread::threadLoop_write()
4090{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004091 for (size_t i = 0; i < outputTracks.size(); i++) {
4092 outputTracks[i]->write(mMixBuffer, writeFrames);
4093 }
4094 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004095}
Glenn Kasten688a6402012-02-29 07:57:06 -08004096
Glenn Kasten000f0e32012-03-01 17:10:56 -08004097void AudioFlinger::DuplicatingThread::threadLoop_standby()
4098{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004099 // DuplicatingThread implements standby by stopping all tracks
4100 for (size_t i = 0; i < outputTracks.size(); i++) {
4101 outputTracks[i]->stop();
4102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103}
4104
Glenn Kastenfa26a852012-03-06 11:28:04 -08004105void AudioFlinger::DuplicatingThread::saveOutputTracks()
4106{
4107 outputTracks = mOutputTracks;
4108}
4109
4110void AudioFlinger::DuplicatingThread::clearOutputTracks()
4111{
4112 outputTracks.clear();
4113}
4114
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4116{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004117 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004118 // FIXME explain this formula
Glenn Kastene33054e2012-11-14 12:54:39 -08004119 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004120 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121 this,
4122 mSampleRate,
4123 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004124 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125 frameCount);
4126 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004127 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004129 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004130 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131 }
4132}
4133
4134void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4135{
4136 Mutex::Autolock _l(mLock);
4137 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004138 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 mOutputTracks[i]->destroy();
4140 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004141 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 return;
4143 }
4144 }
Steve Block3856b092011-10-20 11:56:00 +01004145 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146}
4147
Glenn Kasten438b0362012-03-06 11:24:48 -08004148// caller must hold mLock
4149void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150{
4151 mWaitTimeMs = UINT_MAX;
4152 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4153 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004154 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4156 if (waitTimeMs < mWaitTimeMs) {
4157 mWaitTimeMs = waitTimeMs;
4158 }
4159 }
4160 }
4161}
4162
4163
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004164bool AudioFlinger::DuplicatingThread::outputsReady(
4165 const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166{
4167 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004168 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169 if (thread == 0) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004170 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4171 outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 return false;
4173 }
4174 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004175 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004177 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4178 thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 return false;
4180 }
4181 }
4182 return true;
4183}
4184
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004185uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186{
4187 return (mWaitTimeMs * 1000) / 2;
4188}
4189
Glenn Kasten66fcab92012-02-24 14:59:21 -08004190void AudioFlinger::DuplicatingThread::cacheParameters_l()
4191{
4192 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4193 updateWaitTime_l();
4194
4195 MixerThread::cacheParameters_l();
4196}
4197
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198// ----------------------------------------------------------------------------
4199
4200// TrackBase constructor must be called with AudioFlinger::mLock held
4201AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004202 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 const sp<Client>& client,
4204 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004205 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004206 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08004207 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208 const sp<IMemory>& sharedBuffer,
4209 int sessionId)
4210 : RefBase(),
4211 mThread(thread),
4212 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004213 mCblk(NULL),
4214 // mBuffer
4215 // mBufferEnd
Glenn Kasten9f2016d2012-11-13 09:58:55 -08004216 mStepCount(0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004218 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 mFormat(format),
Glenn Kasten60a83922012-06-21 12:56:37 -07004220 mChannelMask(channelMask),
4221 mChannelCount(popcount(channelMask)),
4222 mFrameSize(audio_is_linear_pcm(format) ?
4223 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
Glenn Kastenb6037442012-11-14 13:42:25 -08004224 mFrameCount(frameCount),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004225 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226 mSessionId(sessionId)
4227{
Glenn Kasten287fedb2012-11-05 13:39:09 -08004228 // client == 0 implies sharedBuffer == 0
4229 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
4230
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004231 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
4232 sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233
Steve Blockb8a80522011-12-20 16:23:08 +00004234 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004235 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten60a83922012-06-21 12:56:37 -07004236 size_t bufferSize = frameCount * mFrameSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004237 if (sharedBuffer == 0) {
4238 size += bufferSize;
4239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240
Glenn Kasten287fedb2012-11-05 13:39:09 -08004241 if (client != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242 mCblkMemory = client->heap()->allocate(size);
4243 if (mCblkMemory != 0) {
4244 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kasten287fedb2012-11-05 13:39:09 -08004245 // can't assume mCblk != NULL
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004247 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248 client->heap()->dump("AudioTrack");
4249 return;
4250 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004251 } else {
4252 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten287fedb2012-11-05 13:39:09 -08004253 // assume mCblk != NULL
4254 }
4255
4256 // construct the shared structure in-place.
4257 if (mCblk != NULL) {
Glenn Kastenea7939a2012-03-14 12:56:26 -07004258 new(mCblk) audio_track_cblk_t();
4259 // clear all buffers
Glenn Kastenb6037442012-11-14 13:42:25 -08004260 mCblk->frameCount_ = frameCount;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004261 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004262// uncomment the following lines to quickly test 32-bit wraparound
Glenn Kasten287fedb2012-11-05 13:39:09 -08004263// mCblk->user = 0xffff0000;
4264// mCblk->server = 0xffff0000;
4265// mCblk->userBase = 0xffff0000;
4266// mCblk->serverBase = 0xffff0000;
Glenn Kasten287fedb2012-11-05 13:39:09 -08004267 if (sharedBuffer == 0) {
4268 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
Glenn Kasten60a83922012-06-21 12:56:37 -07004269 memset(mBuffer, 0, bufferSize);
Glenn Kasten287fedb2012-11-05 13:39:09 -08004270 // Force underrun condition to avoid false underrun callback until first data is
4271 // written to buffer (other flags are cleared)
4272 mCblk->flags = CBLK_UNDERRUN;
4273 } else {
4274 mBuffer = sharedBuffer->pointer();
4275 }
Glenn Kastenea7939a2012-03-14 12:56:26 -07004276 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278}
4279
4280AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4281{
Glenn Kastena0d68332012-01-27 16:47:15 -08004282 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004283 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004285 } else {
4286 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287 }
4288 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004289 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004290 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004291 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004293 // If the client's reference count drops to zero, the associated destructor
4294 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4295 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 mClient.clear();
4297 }
4298}
4299
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004300// AudioBufferProvider interface
4301// getNextBuffer() = 0;
4302// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4304{
Glenn Kastene0feee32011-12-13 11:53:26 -08004305 buffer->raw = NULL;
Glenn Kasten9f2016d2012-11-13 09:58:55 -08004306 mStepCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004307 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004308 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 buffer->frameCount = 0;
4310}
4311
4312bool AudioFlinger::ThreadBase::TrackBase::step() {
4313 bool result;
4314 audio_track_cblk_t* cblk = this->cblk();
4315
Glenn Kastenb6037442012-11-14 13:42:25 -08004316 result = cblk->stepServer(mStepCount, mFrameCount, isOut());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004318 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004319 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 }
4321 return result;
4322}
4323
4324void AudioFlinger::ThreadBase::TrackBase::reset() {
4325 audio_track_cblk_t* cblk = this->cblk();
4326
4327 cblk->user = 0;
4328 cblk->server = 0;
4329 cblk->userBase = 0;
4330 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004331 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004332 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333}
4334
Glenn Kasten3b16c762012-11-14 08:44:39 -08004335uint32_t AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4336 return mCblk->sampleRate;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337}
4338
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4340 audio_track_cblk_t* cblk = this->cblk();
Glenn Kasten60a83922012-06-21 12:56:37 -07004341 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase) * mFrameSize;
4342 int8_t *bufferEnd = bufferStart + frames * mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343
4344 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004345 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4346 "TrackBase::getBuffer buffer out of range:\n"
4347 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
Glenn Kasten60a83922012-06-21 12:56:37 -07004348 " server %u, serverBase %u, user %u, userBase %u, frameSize %u",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Glenn Kasten60a83922012-06-21 12:56:37 -07004350 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351
4352 return bufferStart;
4353}
4354
Eric Laurenta011e352012-03-29 15:51:43 -07004355status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4356{
4357 mSyncEvents.add(event);
4358 return NO_ERROR;
4359}
4360
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361// ----------------------------------------------------------------------------
4362
4363// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4364AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004365 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004367 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004369 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004370 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08004371 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004373 int sessionId,
4374 IAudioFlinger::track_flags_t flags)
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004375 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
4376 sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004377 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004378 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004379 // mRetryCount initialized later when needed
4380 mSharedBuffer(sharedBuffer),
4381 mStreamType(streamType),
4382 mName(-1), // see note below
4383 mMainBuffer(thread->mixBuffer()),
4384 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004385 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004386 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004387 mFlags(flags),
4388 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004389 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004390 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391{
4392 if (mCblk != NULL) {
Glenn Kasten893a0542012-05-30 10:32:06 -07004393 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004394 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004395 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004396 if (mName < 0) {
4397 ALOGE("no more track names available");
4398 return;
4399 }
4400 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004401 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten58912562012-04-03 10:45:00 -07004402 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4403 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004404 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004405 // FIXME This is too eager. We allocate a fast track index before the
4406 // fast track becomes active. Since fast tracks are a scarce resource,
4407 // this means we are potentially denying other more important fast tracks from
4408 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004409 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004410 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004411 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004412 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004413 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004416 ALOGV("Track constructor name %d, calling pid %d", mName,
4417 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004418}
4419
4420AudioFlinger::PlaybackThread::Track::~Track()
4421{
Steve Block3856b092011-10-20 11:56:00 +01004422 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423}
4424
4425void AudioFlinger::PlaybackThread::Track::destroy()
4426{
4427 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4428 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004429 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 // we must acquire a strong reference on this Track before locking mLock
4431 // here so that the destructor is called only when exiting this function.
4432 // On the other hand, as long as Track::destroy() is only called by
4433 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4434 // this Track with its member mTrack.
4435 sp<Track> keep(this);
4436 { // scope for mLock
4437 sp<ThreadBase> thread = mThread.promote();
4438 if (thread != 0) {
4439 if (!isOutputTrack()) {
4440 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004441 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004442
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004443#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004444 // to track the speaker usage
4445 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004446#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 }
4448 AudioSystem::releaseOutput(thread->id());
4449 }
4450 Mutex::Autolock _l(thread->mLock);
4451 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4452 playbackThread->destroyTrack_l(this);
4453 }
4454 }
4455}
4456
Glenn Kasten288ed212012-04-25 17:52:27 -07004457/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4458{
Glenn Kasten9f2016d2012-11-13 09:58:55 -08004459 result.append(" Name Client Type Fmt Chn mask Session StpCnt fCount S M F SRate "
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004460 "L dB R dB Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004461}
4462
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4464{
Glenn Kasten83d86532012-01-17 14:39:34 -08004465 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004466 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004467 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004468 } else {
4469 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4470 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004471 track_state state = mState;
4472 char stateChar;
4473 switch (state) {
4474 case IDLE:
4475 stateChar = 'I';
4476 break;
4477 case TERMINATED:
4478 stateChar = 'T';
4479 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004480 case STOPPING_1:
4481 stateChar = 's';
4482 break;
4483 case STOPPING_2:
4484 stateChar = '5';
4485 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004486 case STOPPED:
4487 stateChar = 'S';
4488 break;
4489 case RESUMING:
4490 stateChar = 'R';
4491 break;
4492 case ACTIVE:
4493 stateChar = 'A';
4494 break;
4495 case PAUSING:
4496 stateChar = 'p';
4497 break;
4498 case PAUSED:
4499 stateChar = 'P';
4500 break;
Eric Laurent29864602012-05-08 18:57:51 -07004501 case FLUSHED:
4502 stateChar = 'F';
4503 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004504 default:
4505 stateChar = '?';
4506 break;
4507 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004508 char nowInUnderrun;
4509 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4510 case UNDERRUN_FULL:
4511 nowInUnderrun = ' ';
4512 break;
4513 case UNDERRUN_PARTIAL:
4514 nowInUnderrun = '<';
4515 break;
4516 case UNDERRUN_EMPTY:
4517 nowInUnderrun = '*';
4518 break;
4519 default:
4520 nowInUnderrun = '?';
4521 break;
4522 }
Glenn Kastene213c862012-04-25 13:46:15 -07004523 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4524 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004525 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 mStreamType,
4527 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004528 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004529 mSessionId,
Glenn Kasten9f2016d2012-11-13 09:58:55 -08004530 mStepCount,
Glenn Kastenb6037442012-11-14 13:42:25 -08004531 mFrameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004532 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 mMute,
4534 mFillingUpStatus,
4535 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004536 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4537 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 mCblk->server,
4539 mCblk->user,
4540 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004541 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004542 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004543 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004544 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545}
4546
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004547// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004548status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004549 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004551 audio_track_cblk_t* cblk = this->cblk();
4552 uint32_t framesReady;
4553 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004555 // Check if last stepServer failed, try to step now
4556 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004557 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4558 // Since the fast mixer is higher priority than client callback thread,
4559 // it does not result in priority inversion for client.
4560 // But a non-blocking solution would be preferable to avoid
4561 // fast mixer being unable to tryLock(), and
4562 // to avoid the extra context switches if the client wakes up,
4563 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004564 if (!step()) goto getNextBuffer_exit;
4565 ALOGV("stepServer recovered");
4566 mStepServerFailed = false;
4567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568
Glenn Kasten288ed212012-04-25 17:52:27 -07004569 // FIXME Same as above
Glenn Kasten864585d2012-11-06 16:15:41 -08004570 framesReady = cblk->framesReadyOut();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004572 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 uint32_t s = cblk->server;
Glenn Kastenb6037442012-11-14 13:42:25 -08004574 uint32_t bufferEnd = cblk->serverBase + mFrameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575
4576 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4577 if (framesReq > framesReady) {
4578 framesReq = framesReady;
4579 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004580 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581 framesReq = bufferEnd - s;
4582 }
4583
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004584 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004585 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588
4589getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004590 buffer->raw = NULL;
4591 buffer->frameCount = 0;
4592 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4593 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594}
4595
Glenn Kasten288ed212012-04-25 17:52:27 -07004596// Note that framesReady() takes a mutex on the control block using tryLock().
4597// This could result in priority inversion if framesReady() is called by the normal mixer,
4598// as the normal mixer thread runs at lower
4599// priority than the client's callback thread: there is a short window within framesReady()
4600// during which the normal mixer could be preempted, and the client callback would block.
4601// Another problem can occur if framesReady() is called by the fast mixer:
4602// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4603// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4604size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten864585d2012-11-06 16:15:41 -08004605 return mCblk->framesReadyOut();
John Grossman4ff14ba2012-02-08 16:37:41 -08004606}
4607
Glenn Kasten288ed212012-04-25 17:52:27 -07004608// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609bool AudioFlinger::PlaybackThread::Track::isReady() const {
Glenn Kastend65d73c2012-06-22 17:21:07 -07004610 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
4611 return true;
4612 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613
Glenn Kastenb6037442012-11-14 13:42:25 -08004614 if (framesReady() >= mFrameCount ||
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08004615 (mCblk->flags & CBLK_FORCEREADY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004616 mFillingUpStatus = FS_FILLED;
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08004617 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004618 return true;
4619 }
4620 return false;
4621}
4622
Glenn Kasten3acbd052012-02-28 10:39:56 -08004623status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004624 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625{
4626 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004627 ALOGV("start(%d), calling pid %d session %d",
4628 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004629
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 sp<ThreadBase> thread = mThread.promote();
4631 if (thread != 0) {
4632 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004633 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 // here the track could be either new, or restarted
4635 // in both cases "unstop" the track
4636 if (mState == PAUSED) {
4637 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004638 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 } else {
4640 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004641 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 }
4643
4644 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4645 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004646 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004647 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004648
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004649#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004650 // to track the speaker usage
4651 if (status == NO_ERROR) {
4652 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4653 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004654#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655 }
4656 if (status == NO_ERROR) {
4657 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4658 playbackThread->addTrack_l(this);
4659 } else {
4660 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004661 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 }
4663 } else {
4664 status = BAD_VALUE;
4665 }
4666 return status;
4667}
4668
4669void AudioFlinger::PlaybackThread::Track::stop()
4670{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004671 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672 sp<ThreadBase> thread = mThread.promote();
4673 if (thread != 0) {
4674 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004675 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004676 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 // If the track is not active (PAUSED and buffers full), flush buffers
4678 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4679 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4680 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004681 mState = STOPPED;
4682 } else if (!isFastTrack()) {
4683 mState = STOPPED;
4684 } else {
4685 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4686 // and then to STOPPED and reset() when presentation is complete
4687 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004689 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
4690 playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 }
4692 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4693 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004694 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004696
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004697#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004698 // to track the speaker usage
4699 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004700#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004701 }
4702 }
4703}
4704
4705void AudioFlinger::PlaybackThread::Track::pause()
4706{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004707 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004708 sp<ThreadBase> thread = mThread.promote();
4709 if (thread != 0) {
4710 Mutex::Autolock _l(thread->mLock);
4711 if (mState == ACTIVE || mState == RESUMING) {
4712 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004713 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004714 if (!isOutputTrack()) {
4715 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004716 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004717 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004718
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004719#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004720 // to track the speaker usage
4721 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004722#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 }
4724 }
4725 }
4726}
4727
4728void AudioFlinger::PlaybackThread::Track::flush()
4729{
Steve Block3856b092011-10-20 11:56:00 +01004730 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004731 sp<ThreadBase> thread = mThread.promote();
4732 if (thread != 0) {
4733 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004734 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kasten4bd7e542012-11-15 14:13:16 -08004735 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 return;
4737 }
4738 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004739 // FLUSHED state
4740 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004741 // do not reset the track if it is still in the process of being stopped or paused.
4742 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004743 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004744 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004745 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4746 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4747 reset();
4748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004749 }
4750}
4751
4752void AudioFlinger::PlaybackThread::Track::reset()
4753{
4754 // Do not reset twice to avoid discarding data written just after a flush and before
4755 // the audioflinger thread detects the track is stopped.
4756 if (!mResetDone) {
4757 TrackBase::reset();
4758 // Force underrun condition to avoid false underrun callback until first data is
4759 // written to buffer
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08004760 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
4761 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004762 mFillingUpStatus = FS_FILLING;
4763 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004764 if (mState == FLUSHED) {
4765 mState = IDLE;
4766 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767 }
4768}
4769
4770void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4771{
4772 mMute = muted;
4773}
4774
Mathias Agopian65ab4712010-07-14 17:59:35 -07004775status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4776{
4777 status_t status = DEAD_OBJECT;
4778 sp<ThreadBase> thread = mThread.promote();
4779 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004780 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004781 sp<AudioFlinger> af = mClient->audioFlinger();
4782
4783 Mutex::Autolock _l(af->mLock);
4784
4785 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004786
Eric Laurent109347d2012-07-02 12:31:03 -07004787 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004788 Mutex::Autolock _dl(playbackThread->mLock);
4789 Mutex::Autolock _sl(srcThread->mLock);
4790 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4791 if (chain == 0) {
4792 return INVALID_OPERATION;
4793 }
4794
4795 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4796 if (effect == 0) {
4797 return INVALID_OPERATION;
4798 }
4799 srcThread->removeEffect_l(effect);
4800 playbackThread->addEffect_l(effect);
4801 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4802 if (effect->state() == EffectModule::ACTIVE ||
4803 effect->state() == EffectModule::STOPPING) {
4804 effect->start();
4805 }
4806
4807 sp<EffectChain> dstChain = effect->chain().promote();
4808 if (dstChain == 0) {
4809 srcThread->addEffect_l(effect);
4810 return INVALID_OPERATION;
4811 }
4812 AudioSystem::unregisterEffect(effect->id());
4813 AudioSystem::registerEffect(&effect->desc(),
4814 srcThread->id(),
4815 dstChain->strategy(),
4816 AUDIO_SESSION_OUTPUT_MIX,
4817 effect->id());
4818 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004819 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004820 }
4821 return status;
4822}
4823
4824void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4825{
4826 mAuxEffectId = EffectId;
4827 mAuxBuffer = buffer;
4828}
4829
Eric Laurenta011e352012-03-29 15:51:43 -07004830bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4831 size_t audioHalFrames)
4832{
4833 // a track is considered presented when the total number of frames written to audio HAL
4834 // corresponds to the number of frames written when presentationComplete() is called for the
4835 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4836 if (mPresentationCompleteFrames == 0) {
4837 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4838 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4839 mPresentationCompleteFrames, audioHalFrames);
4840 }
4841 if (framesWritten >= mPresentationCompleteFrames) {
4842 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4843 mSessionId, framesWritten);
4844 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004845 return true;
4846 }
4847 return false;
4848}
4849
4850void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4851{
4852 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4853 if (mSyncEvents[i]->type() == type) {
4854 mSyncEvents[i]->trigger();
4855 mSyncEvents.removeAt(i);
4856 i--;
4857 }
4858 }
4859}
4860
Glenn Kasten58912562012-04-03 10:45:00 -07004861// implement VolumeBufferProvider interface
4862
4863uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4864{
4865 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4866 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4867 uint32_t vlr = mCblk->getVolumeLR();
4868 uint32_t vl = vlr & 0xFFFF;
4869 uint32_t vr = vlr >> 16;
4870 // track volumes come from shared memory, so can't be trusted and must be clamped
4871 if (vl > MAX_GAIN_INT) {
4872 vl = MAX_GAIN_INT;
4873 }
4874 if (vr > MAX_GAIN_INT) {
4875 vr = MAX_GAIN_INT;
4876 }
4877 // now apply the cached master volume and stream type volume;
4878 // this is trusted but lacks any synchronization or barrier so may be stale
4879 float v = mCachedVolume;
4880 vl *= v;
4881 vr *= v;
4882 // re-combine into U4.16
4883 vlr = (vr << 16) | (vl & 0xFFFF);
4884 // FIXME look at mute, pause, and stop flags
4885 return vlr;
4886}
Eric Laurenta011e352012-03-29 15:51:43 -07004887
Eric Laurent29864602012-05-08 18:57:51 -07004888status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4889{
4890 if (mState == TERMINATED || mState == PAUSED ||
4891 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4892 (mState == STOPPED)))) {
4893 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4894 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4895 event->cancel();
4896 return INVALID_OPERATION;
4897 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004898 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004899 return NO_ERROR;
4900}
4901
Glenn Kasten864585d2012-11-06 16:15:41 -08004902bool AudioFlinger::PlaybackThread::Track::isOut() const
4903{
4904 return true;
4905}
4906
John Grossman4ff14ba2012-02-08 16:37:41 -08004907// timed audio tracks
4908
4909sp<AudioFlinger::PlaybackThread::TimedTrack>
4910AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004911 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004912 const sp<Client>& client,
4913 audio_stream_type_t streamType,
4914 uint32_t sampleRate,
4915 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004916 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08004917 size_t frameCount,
John Grossman4ff14ba2012-02-08 16:37:41 -08004918 const sp<IMemory>& sharedBuffer,
4919 int sessionId) {
4920 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004921 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004922
Glenn Kastena0356762012-03-19 10:38:51 -07004923 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004924 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4925 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004926}
4927
4928AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004929 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004930 const sp<Client>& client,
4931 audio_stream_type_t streamType,
4932 uint32_t sampleRate,
4933 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004934 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08004935 size_t frameCount,
John Grossman4ff14ba2012-02-08 16:37:41 -08004936 const sp<IMemory>& sharedBuffer,
4937 int sessionId)
4938 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004939 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004940 mQueueHeadInFlight(false),
4941 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004942 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004943 mTimedSilenceBuffer(NULL),
4944 mTimedSilenceBufferSize(0),
4945 mTimedAudioOutputOnTime(false),
4946 mMediaTimeTransformValid(false)
4947{
4948 LocalClock lc;
4949 mLocalTimeFreq = lc.getLocalFreq();
4950
4951 mLocalTimeToSampleTransform.a_zero = 0;
4952 mLocalTimeToSampleTransform.b_zero = 0;
4953 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4954 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4955 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4956 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004957
4958 mMediaTimeToSampleTransform.a_zero = 0;
4959 mMediaTimeToSampleTransform.b_zero = 0;
4960 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4961 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4962 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4963 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004964}
4965
4966AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4967 mClient->releaseTimedTrack();
4968 delete [] mTimedSilenceBuffer;
4969}
4970
4971status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4972 size_t size, sp<IMemory>* buffer) {
4973
4974 Mutex::Autolock _l(mTimedBufferQueueLock);
4975
4976 trimTimedBufferQueue_l();
4977
4978 // lazily initialize the shared memory heap for timed buffers
4979 if (mTimedMemoryDealer == NULL) {
4980 const int kTimedBufferHeapSize = 512 << 10;
4981
4982 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4983 "AudioFlingerTimed");
4984 if (mTimedMemoryDealer == NULL)
4985 return NO_MEMORY;
4986 }
4987
4988 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4989 if (newBuffer == NULL) {
4990 newBuffer = mTimedMemoryDealer->allocate(size);
4991 if (newBuffer == NULL)
4992 return NO_MEMORY;
4993 }
4994
4995 *buffer = newBuffer;
4996 return NO_ERROR;
4997}
4998
4999// caller must hold mTimedBufferQueueLock
5000void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5001 int64_t mediaTimeNow;
5002 {
5003 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5004 if (!mMediaTimeTransformValid)
5005 return;
5006
5007 int64_t targetTimeNow;
5008 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5009 ? mCCHelper.getCommonTime(&targetTimeNow)
5010 : mCCHelper.getLocalTime(&targetTimeNow);
5011
5012 if (OK != res)
5013 return;
5014
5015 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5016 &mediaTimeNow)) {
5017 return;
5018 }
5019 }
5020
John Grossman1c345192012-03-27 14:00:17 -07005021 size_t trimEnd;
5022 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005023 int64_t bufEnd;
5024
John Grossmanc95cfbb2012-04-12 11:53:11 -07005025 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5026 // We have a next buffer. Just use its PTS as the PTS of the frame
5027 // following the last frame in this buffer. If the stream is sparse
5028 // (ie, there are deliberate gaps left in the stream which should be
5029 // filled with silence by the TimedAudioTrack), then this can result
5030 // in one extra buffer being left un-trimmed when it could have
5031 // been. In general, this is not typical, and we would rather
5032 // optimized away the TS calculation below for the more common case
5033 // where PTSes are contiguous.
5034 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5035 } else {
5036 // We have no next buffer. Compute the PTS of the frame following
5037 // the last frame in this buffer by computing the duration of of
5038 // this frame in media time units and adding it to the PTS of the
5039 // buffer.
5040 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
Glenn Kasten83a03822012-11-12 07:58:20 -08005041 / mFrameSize;
John Grossmanc95cfbb2012-04-12 11:53:11 -07005042
5043 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5044 &bufEnd)) {
5045 ALOGE("Failed to convert frame count of %lld to media time"
5046 " duration" " (scale factor %d/%u) in %s",
5047 frameCount,
5048 mMediaTimeToSampleTransform.a_to_b_numer,
5049 mMediaTimeToSampleTransform.a_to_b_denom,
5050 __PRETTY_FUNCTION__);
5051 break;
5052 }
5053 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005054 }
John Grossman9fbdee12012-03-26 17:51:46 -07005055
5056 if (bufEnd > mediaTimeNow)
5057 break;
5058
5059 // Is the buffer we want to use in the middle of a mix operation right
5060 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5061 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005062 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005063 mTrimQueueHeadOnRelease = true;
5064 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005065 }
5066
John Grossman9fbdee12012-03-26 17:51:46 -07005067 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005068 if (trimStart < trimEnd) {
5069 // Update the bookkeeping for framesReady()
5070 for (size_t i = trimStart; i < trimEnd; ++i) {
5071 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5072 }
5073
5074 // Now actually remove the buffers from the queue.
5075 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005076 }
5077}
5078
John Grossman1c345192012-03-27 14:00:17 -07005079void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5080 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005081 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5082 "%s called (reason \"%s\"), but timed buffer queue has no"
5083 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005084
5085 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5086 mTimedBufferQueue.removeAt(0);
5087}
5088
5089void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5090 const TimedBuffer& buf,
5091 const char* logTag) {
5092 uint32_t bufBytes = buf.buffer()->size();
5093 uint32_t consumedAlready = buf.position();
5094
Eric Laurentb388e532012-04-14 13:32:48 -07005095 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005096 "Bad bookkeeping while updating frames pending. Timed buffer is"
5097 " only %u bytes long, but claims to have consumed %u"
5098 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005099 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005100
Glenn Kasten83a03822012-11-12 07:58:20 -08005101 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005102 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5103 "Bad bookkeeping while updating frames pending. Should have at"
5104 " least %u queued frames, but we think we have only %u. (update"
5105 " reason: \"%s\")",
5106 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005107
5108 mFramesPendingInQueue -= bufFrames;
5109}
5110
John Grossman4ff14ba2012-02-08 16:37:41 -08005111status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5112 const sp<IMemory>& buffer, int64_t pts) {
5113
5114 {
5115 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5116 if (!mMediaTimeTransformValid)
5117 return INVALID_OPERATION;
5118 }
5119
5120 Mutex::Autolock _l(mTimedBufferQueueLock);
5121
Glenn Kasten83a03822012-11-12 07:58:20 -08005122 uint32_t bufFrames = buffer->size() / mFrameSize;
John Grossman1c345192012-03-27 14:00:17 -07005123 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005124 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5125
5126 return NO_ERROR;
5127}
5128
5129status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5130 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5131
John Grossman1c345192012-03-27 14:00:17 -07005132 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5133 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5134 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005135
5136 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5137 target == TimedAudioTrack::COMMON_TIME)) {
5138 return BAD_VALUE;
5139 }
5140
5141 Mutex::Autolock lock(mMediaTimeTransformLock);
5142 mMediaTimeTransform = xform;
5143 mMediaTimeTransformTarget = target;
5144 mMediaTimeTransformValid = true;
5145
5146 return NO_ERROR;
5147}
5148
5149#define min(a, b) ((a) < (b) ? (a) : (b))
5150
5151// implementation of getNextBuffer for tracks whose buffers have timestamps
5152status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5153 AudioBufferProvider::Buffer* buffer, int64_t pts)
5154{
5155 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005156 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005157 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005158 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005159 return INVALID_OPERATION;
5160 }
5161
John Grossman4ff14ba2012-02-08 16:37:41 -08005162 Mutex::Autolock _l(mTimedBufferQueueLock);
5163
John Grossman9fbdee12012-03-26 17:51:46 -07005164 ALOG_ASSERT(!mQueueHeadInFlight,
5165 "getNextBuffer called without releaseBuffer!");
5166
John Grossman4ff14ba2012-02-08 16:37:41 -08005167 while (true) {
5168
5169 // if we have no timed buffers, then fail
5170 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005171 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005172 buffer->frameCount = 0;
5173 return NOT_ENOUGH_DATA;
5174 }
5175
5176 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5177
5178 // calculate the PTS of the head of the timed buffer queue expressed in
5179 // local time
5180 int64_t headLocalPTS;
5181 {
5182 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5183
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005184 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005185
5186 if (mMediaTimeTransform.a_to_b_denom == 0) {
5187 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005188 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005189 return NO_ERROR;
5190 }
5191
5192 int64_t transformedPTS;
5193 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5194 &transformedPTS)) {
5195 // the transform failed. this shouldn't happen, but if it does
5196 // then just drop this buffer
5197 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005198 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005199 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005200 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005201 return NO_ERROR;
5202 }
5203
5204 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5205 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5206 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005207 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005208 buffer->frameCount = 0;
5209 return INVALID_OPERATION;
5210 }
5211 } else {
5212 headLocalPTS = transformedPTS;
5213 }
5214 }
5215
5216 // adjust the head buffer's PTS to reflect the portion of the head buffer
5217 // that has already been consumed
5218 int64_t effectivePTS = headLocalPTS +
Glenn Kasten83a03822012-11-12 07:58:20 -08005219 ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate());
John Grossman4ff14ba2012-02-08 16:37:41 -08005220
5221 // Calculate the delta in samples between the head of the input buffer
5222 // queue and the start of the next output buffer that will be written.
5223 // If the transformation fails because of over or underflow, it means
5224 // that the sample's position in the output stream is so far out of
5225 // whack that it should just be dropped.
5226 int64_t sampleDelta;
5227 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5228 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005229 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5230 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005231 continue;
5232 }
5233 if (!mLocalTimeToSampleTransform.doForwardTransform(
5234 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005235 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005236 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005237 continue;
5238 }
5239
John Grossman1c345192012-03-27 14:00:17 -07005240 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5241 " sampleDelta=[%d.%08x]",
5242 head.pts(), head.position(), pts,
5243 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5244 + (sampleDelta >> 32)),
5245 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005246
5247 // if the delta between the ideal placement for the next input sample and
5248 // the current output position is within this threshold, then we will
5249 // concatenate the next input samples to the previous output
5250 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005251 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005252
5253 // if this is the first buffer of audio that we're emitting from this track
5254 // then it should be almost exactly on time.
5255 const int64_t kSampleStartupThreshold = 1LL << 32;
5256
5257 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005258 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005259 // the next input is close enough to being on time, so concatenate it
5260 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005261 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005262
John Grossman1c345192012-03-27 14:00:17 -07005263 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5264 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005265 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005266 }
5267
5268 // Looks like our output is not on time. Reset our on timed status.
5269 // Next time we mix samples from our input queue, then should be within
5270 // the StartupThreshold.
5271 mTimedAudioOutputOnTime = false;
5272 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005273 // the gap between the current output position and the proper start of
5274 // the next input sample is too big, so fill it with silence
5275 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5276
John Grossman9fbdee12012-03-26 17:51:46 -07005277 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005278 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5279 return NO_ERROR;
5280 } else {
5281 // the next input sample is late
5282 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5283 size_t onTimeSamplePosition =
Glenn Kasten83a03822012-11-12 07:58:20 -08005284 head.position() + lateFrames * mFrameSize;
John Grossman4ff14ba2012-02-08 16:37:41 -08005285
5286 if (onTimeSamplePosition > head.buffer()->size()) {
5287 // all the remaining samples in the head are too late, so
5288 // drop it and move on
5289 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005290 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005291 continue;
5292 } else {
5293 // skip over the late samples
5294 head.setPosition(onTimeSamplePosition);
5295
5296 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005297 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005298
5299 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5300 return NO_ERROR;
5301 }
5302 }
5303 }
5304}
5305
5306// Yield samples from the timed buffer queue head up to the given output
5307// buffer's capacity.
5308//
5309// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005310void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005311 AudioBufferProvider::Buffer* buffer) {
5312
5313 const TimedBuffer& head = mTimedBufferQueue[0];
5314
5315 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5316 head.position());
5317
5318 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
Glenn Kasten83a03822012-11-12 07:58:20 -08005319 mFrameSize);
John Grossman4ff14ba2012-02-08 16:37:41 -08005320 size_t framesRequested = buffer->frameCount;
5321 buffer->frameCount = min(framesLeftInHead, framesRequested);
5322
John Grossman9fbdee12012-03-26 17:51:46 -07005323 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005324 mTimedAudioOutputOnTime = true;
5325}
5326
5327// Yield samples of silence up to the given output buffer's capacity
5328//
5329// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005330void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005331 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5332
5333 // lazily allocate a buffer filled with silence
Glenn Kasten83a03822012-11-12 07:58:20 -08005334 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005335 delete [] mTimedSilenceBuffer;
Glenn Kasten83a03822012-11-12 07:58:20 -08005336 mTimedSilenceBufferSize = numFrames * mFrameSize;
John Grossman4ff14ba2012-02-08 16:37:41 -08005337 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5338 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5339 }
5340
5341 buffer->raw = mTimedSilenceBuffer;
5342 size_t framesRequested = buffer->frameCount;
5343 buffer->frameCount = min(numFrames, framesRequested);
5344
5345 mTimedAudioOutputOnTime = false;
5346}
5347
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005348// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005349void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5350 AudioBufferProvider::Buffer* buffer) {
5351
5352 Mutex::Autolock _l(mTimedBufferQueueLock);
5353
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005354 // If the buffer which was just released is part of the buffer at the head
5355 // of the queue, be sure to update the amt of the buffer which has been
5356 // consumed. If the buffer being returned is not part of the head of the
5357 // queue, its either because the buffer is part of the silence buffer, or
5358 // because the head of the timed queue was trimmed after the mixer called
5359 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005360 if (buffer->raw == mTimedSilenceBuffer) {
5361 ALOG_ASSERT(!mQueueHeadInFlight,
5362 "Queue head in flight during release of silence buffer!");
5363 goto done;
5364 }
5365
5366 ALOG_ASSERT(mQueueHeadInFlight,
5367 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5368 " head in flight.");
5369
5370 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005371 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005372
5373 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005374 void* end = reinterpret_cast<void*>(
5375 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5376 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005377
John Grossman9fbdee12012-03-26 17:51:46 -07005378 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5379 "released buffer not within the head of the timed buffer"
5380 " queue; qHead = [%p, %p], released buffer = %p",
5381 start, end, buffer->raw);
5382
5383 head.setPosition(head.position() +
Glenn Kasten83a03822012-11-12 07:58:20 -08005384 (buffer->frameCount * mFrameSize));
John Grossman9fbdee12012-03-26 17:51:46 -07005385 mQueueHeadInFlight = false;
5386
John Grossman1c345192012-03-27 14:00:17 -07005387 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5388 "Bad bookkeeping during releaseBuffer! Should have at"
5389 " least %u queued frames, but we think we have only %u",
5390 buffer->frameCount, mFramesPendingInQueue);
5391
5392 mFramesPendingInQueue -= buffer->frameCount;
5393
John Grossman9fbdee12012-03-26 17:51:46 -07005394 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5395 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005396 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005397 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005398 }
John Grossman9fbdee12012-03-26 17:51:46 -07005399 } else {
5400 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5401 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005402 }
5403
John Grossman9fbdee12012-03-26 17:51:46 -07005404done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005405 buffer->raw = 0;
5406 buffer->frameCount = 0;
5407}
5408
Glenn Kasten288ed212012-04-25 17:52:27 -07005409size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005410 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005411 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005412}
5413
5414AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5415 : mPTS(0), mPosition(0) {}
5416
5417AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5418 const sp<IMemory>& buffer, int64_t pts)
5419 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5420
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421// ----------------------------------------------------------------------------
5422
5423// RecordTrack constructor must be called with AudioFlinger::mLock held
5424AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005425 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 const sp<Client>& client,
5427 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005428 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005429 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08005430 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 int sessionId)
5432 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005433 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 mOverflow(false)
5435{
Glenn Kasten83a03822012-11-12 07:58:20 -08005436 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437}
5438
5439AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5440{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005441 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442}
5443
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005444// AudioBufferProvider interface
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005445status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
5446 int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447{
5448 audio_track_cblk_t* cblk = this->cblk();
5449 uint32_t framesAvail;
5450 uint32_t framesReq = buffer->frameCount;
5451
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005452 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005453 if (mStepServerFailed) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07005454 if (!step()) {
5455 goto getNextBuffer_exit;
5456 }
Steve Block3856b092011-10-20 11:56:00 +01005457 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005458 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 }
5460
Glenn Kasten864585d2012-11-06 16:15:41 -08005461 // FIXME lock is not actually held, so overrun is possible
Glenn Kastenb6037442012-11-14 13:42:25 -08005462 framesAvail = cblk->framesAvailableIn_l(mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463
Glenn Kastenf6b16782011-12-15 09:51:17 -08005464 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 uint32_t s = cblk->server;
Glenn Kastenb6037442012-11-14 13:42:25 -08005466 uint32_t bufferEnd = cblk->serverBase + mFrameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467
5468 if (framesReq > framesAvail) {
5469 framesReq = framesAvail;
5470 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005471 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 framesReq = bufferEnd - s;
5473 }
5474
5475 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 buffer->frameCount = framesReq;
5477 return NO_ERROR;
5478 }
5479
5480getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005481 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 buffer->frameCount = 0;
5483 return NOT_ENOUGH_DATA;
5484}
5485
Glenn Kasten3acbd052012-02-28 10:39:56 -08005486status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005487 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488{
5489 sp<ThreadBase> thread = mThread.promote();
5490 if (thread != 0) {
5491 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005492 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 } else {
5494 return BAD_VALUE;
5495 }
5496}
5497
5498void AudioFlinger::RecordThread::RecordTrack::stop()
5499{
5500 sp<ThreadBase> thread = mThread.promote();
5501 if (thread != 0) {
5502 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005503 recordThread->mLock.lock();
5504 bool doStop = recordThread->stop_l(this);
5505 if (doStop) {
5506 TrackBase::reset();
5507 // Force overrun condition to avoid false overrun callback until first data is
5508 // read from buffer
Glenn Kasten9c5fdd82012-11-05 13:38:15 -08005509 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005510 }
5511 recordThread->mLock.unlock();
5512 if (doStop) {
5513 AudioSystem::stopInput(recordThread->id());
5514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 }
5516}
5517
Glenn Kasten510a3d62012-07-16 14:24:34 -07005518/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5519{
Glenn Kasten9f2016d2012-11-13 09:58:55 -08005520 result.append(" Clien Fmt Chn mask Session Step S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005521}
5522
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5524{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005525 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005526 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005528 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 mSessionId,
Glenn Kasten9f2016d2012-11-13 09:58:55 -08005530 mStepCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 mState,
5532 mCblk->sampleRate,
5533 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005534 mCblk->user,
Glenn Kastenb6037442012-11-14 13:42:25 -08005535 mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536}
5537
Glenn Kasten864585d2012-11-06 16:15:41 -08005538bool AudioFlinger::RecordThread::RecordTrack::isOut() const
5539{
5540 return false;
5541}
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542
5543// ----------------------------------------------------------------------------
5544
5545AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005546 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 DuplicatingThread *sourceThread,
5548 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005549 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005550 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08005551 size_t frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005552 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5553 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastenb929e412012-11-08 12:13:58 -08005554 mActive(false), mSourceThread(sourceThread), mBuffers(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555{
5556
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 if (mCblk != NULL) {
Glenn Kastenb929e412012-11-08 12:13:58 -08005558 mBuffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 mOutBuffer.frameCount = 0;
5560 playbackThread->mTracks.add(this);
Glenn Kasten827e5f12012-11-02 10:00:06 -07005561 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mBuffers %p, " \
Glenn Kasten3b16c762012-11-14 08:44:39 -08005562 "mCblk->frameCount %d, mCblk->sampleRate %u, mChannelMask 0x%08x mBufferEnd %p",
Glenn Kasten827e5f12012-11-02 10:00:06 -07005563 mCblk, mBuffer, mBuffers,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005564 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005566 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 }
5568}
5569
5570AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5571{
5572 clearBufferQueue();
5573}
5574
Glenn Kasten3acbd052012-02-28 10:39:56 -08005575status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005576 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005578 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 if (status != NO_ERROR) {
5580 return status;
5581 }
5582
5583 mActive = true;
5584 mRetryCount = 127;
5585 return status;
5586}
5587
5588void AudioFlinger::PlaybackThread::OutputTrack::stop()
5589{
5590 Track::stop();
5591 clearBufferQueue();
5592 mOutBuffer.frameCount = 0;
5593 mActive = false;
5594}
5595
5596bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5597{
5598 Buffer *pInBuffer;
5599 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005600 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 bool outputBufferFull = false;
5602 inBuffer.frameCount = frames;
5603 inBuffer.i16 = data;
5604
5605 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5606
5607 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005608 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 sp<ThreadBase> thread = mThread.promote();
5610 if (thread != 0) {
5611 MixerThread *mixerThread = (MixerThread *)thread.get();
Glenn Kastenb6037442012-11-14 13:42:25 -08005612 if (mFrameCount > frames){
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
Glenn Kastenb6037442012-11-14 13:42:25 -08005614 uint32_t startFrames = (mFrameCount - frames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 pInBuffer = new Buffer;
5616 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5617 pInBuffer->frameCount = startFrames;
5618 pInBuffer->i16 = pInBuffer->mBuffer;
5619 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5620 mBufferQueue.add(pInBuffer);
5621 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005622 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623 }
5624 }
5625 }
5626 }
5627
5628 while (waitTimeLeftMs) {
5629 // First write pending buffers, then new data
5630 if (mBufferQueue.size()) {
5631 pInBuffer = mBufferQueue.itemAt(0);
5632 } else {
5633 pInBuffer = &inBuffer;
5634 }
5635
5636 if (pInBuffer->frameCount == 0) {
5637 break;
5638 }
5639
5640 if (mOutBuffer.frameCount == 0) {
5641 mOutBuffer.frameCount = pInBuffer->frameCount;
5642 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005643 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005644 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this,
5645 mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646 outputBufferFull = true;
5647 break;
5648 }
5649 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5650 if (waitTimeLeftMs >= waitTimeMs) {
5651 waitTimeLeftMs -= waitTimeMs;
5652 } else {
5653 waitTimeLeftMs = 0;
5654 }
5655 }
5656
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005657 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
5658 pInBuffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kastenb6037442012-11-14 13:42:25 -08005660 mCblk->stepUserOut(outFrames, mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661 pInBuffer->frameCount -= outFrames;
5662 pInBuffer->i16 += outFrames * channelCount;
5663 mOutBuffer.frameCount -= outFrames;
5664 mOutBuffer.i16 += outFrames * channelCount;
5665
5666 if (pInBuffer->frameCount == 0) {
5667 if (mBufferQueue.size()) {
5668 mBufferQueue.removeAt(0);
5669 delete [] pInBuffer->mBuffer;
5670 delete pInBuffer;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005671 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
5672 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673 } else {
5674 break;
5675 }
5676 }
5677 }
5678
5679 // If we could not write all frames, allocate a buffer and queue it for next time.
5680 if (inBuffer.frameCount) {
5681 sp<ThreadBase> thread = mThread.promote();
5682 if (thread != 0 && !thread->standby()) {
5683 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5684 pInBuffer = new Buffer;
5685 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5686 pInBuffer->frameCount = inBuffer.frameCount;
5687 pInBuffer->i16 = pInBuffer->mBuffer;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005688 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
5689 sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 mBufferQueue.add(pInBuffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005691 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
5692 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005694 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
5695 mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 }
5697 }
5698 }
5699
5700 // Calling write() with a 0 length buffer, means that no more data will be written:
5701 // If no more buffers are pending, fill output track buffer to make sure it is started
5702 // by output mixer.
5703 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kastenb6037442012-11-14 13:42:25 -08005704 if (mCblk->user < mFrameCount) {
5705 frames = mFrameCount - mCblk->user;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005706 pInBuffer = new Buffer;
5707 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5708 pInBuffer->frameCount = frames;
5709 pInBuffer->i16 = pInBuffer->mBuffer;
5710 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5711 mBufferQueue.add(pInBuffer);
5712 } else if (mActive) {
5713 stop();
5714 }
5715 }
5716
5717 return outputBufferFull;
5718}
5719
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005720status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
5721 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722{
5723 int active;
5724 status_t result;
5725 audio_track_cblk_t* cblk = mCblk;
5726 uint32_t framesReq = buffer->frameCount;
5727
Glenn Kasten26dd66e2012-10-18 15:51:03 -07005728 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 buffer->frameCount = 0;
5730
Glenn Kastenb6037442012-11-14 13:42:25 -08005731 uint32_t framesAvail = cblk->framesAvailableOut(mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732
5733
5734 if (framesAvail == 0) {
5735 Mutex::Autolock _l(cblk->lock);
5736 goto start_loop_here;
5737 while (framesAvail == 0) {
5738 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005739 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005740 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005741 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 }
5743 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5744 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005745 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 }
5747 // read the server count again
5748 start_loop_here:
Glenn Kastenb6037442012-11-14 13:42:25 -08005749 framesAvail = cblk->framesAvailableOut_l(mFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 }
5751 }
5752
5753// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005754// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755// }
5756
5757 if (framesReq > framesAvail) {
5758 framesReq = framesAvail;
5759 }
5760
5761 uint32_t u = cblk->user;
Glenn Kastenb6037442012-11-14 13:42:25 -08005762 uint32_t bufferEnd = cblk->userBase + mFrameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763
Marco Nelissena1472d92012-03-30 14:36:54 -07005764 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005765 framesReq = bufferEnd - u;
5766 }
5767
5768 buffer->frameCount = framesReq;
Glenn Kasten83a03822012-11-12 07:58:20 -08005769 buffer->raw = cblk->buffer(mBuffers, mFrameSize, u);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770 return NO_ERROR;
5771}
5772
5773
5774void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5775{
5776 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777
5778 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005779 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780 delete [] pBuffer->mBuffer;
5781 delete pBuffer;
5782 }
5783 mBufferQueue.clear();
5784}
5785
5786// ----------------------------------------------------------------------------
5787
5788AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5789 : RefBase(),
5790 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005791 // 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 -07005792 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005793 mPid(pid),
5794 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795{
5796 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5797}
5798
5799// Client destructor must be called with AudioFlinger::mLock held
5800AudioFlinger::Client::~Client()
5801{
5802 mAudioFlinger->removeClient_l(mPid);
5803}
5804
Glenn Kasten435dbe62012-01-30 10:15:48 -08005805sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806{
5807 return mMemoryDealer;
5808}
5809
John Grossman4ff14ba2012-02-08 16:37:41 -08005810// Reserve one of the limited slots for a timed audio track associated
5811// with this client
5812bool AudioFlinger::Client::reserveTimedTrack()
5813{
5814 const int kMaxTimedTracksPerClient = 4;
5815
5816 Mutex::Autolock _l(mTimedTrackLock);
5817
5818 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5819 ALOGW("can not create timed track - pid %d has exceeded the limit",
5820 mPid);
5821 return false;
5822 }
5823
5824 mTimedTrackCount++;
5825 return true;
5826}
5827
5828// Release a slot for a timed audio track
5829void AudioFlinger::Client::releaseTimedTrack()
5830{
5831 Mutex::Autolock _l(mTimedTrackLock);
5832 mTimedTrackCount--;
5833}
5834
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835// ----------------------------------------------------------------------------
5836
5837AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5838 const sp<IAudioFlingerClient>& client,
5839 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005840 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841{
5842}
5843
5844AudioFlinger::NotificationClient::~NotificationClient()
5845{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846}
5847
5848void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5849{
5850 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005851 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852}
5853
5854// ----------------------------------------------------------------------------
5855
5856AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5857 : BnAudioTrack(),
5858 mTrack(track)
5859{
5860}
5861
5862AudioFlinger::TrackHandle::~TrackHandle() {
5863 // just stop the track on deletion, associated resources
5864 // will be freed from the main thread once all pending buffers have
5865 // been played. Unless it's not in the active track list, in which
5866 // case we free everything now...
5867 mTrack->destroy();
5868}
5869
Glenn Kasten90716c52012-01-26 13:40:12 -08005870sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5871 return mTrack->getCblk();
5872}
5873
Glenn Kasten3acbd052012-02-28 10:39:56 -08005874status_t AudioFlinger::TrackHandle::start() {
5875 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876}
5877
5878void AudioFlinger::TrackHandle::stop() {
5879 mTrack->stop();
5880}
5881
5882void AudioFlinger::TrackHandle::flush() {
5883 mTrack->flush();
5884}
5885
5886void AudioFlinger::TrackHandle::mute(bool e) {
5887 mTrack->mute(e);
5888}
5889
5890void AudioFlinger::TrackHandle::pause() {
5891 mTrack->pause();
5892}
5893
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5895{
5896 return mTrack->attachAuxEffect(EffectId);
5897}
5898
John Grossman4ff14ba2012-02-08 16:37:41 -08005899status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5900 sp<IMemory>* buffer) {
5901 if (!mTrack->isTimedTrack())
5902 return INVALID_OPERATION;
5903
5904 PlaybackThread::TimedTrack* tt =
5905 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5906 return tt->allocateTimedBuffer(size, buffer);
5907}
5908
5909status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5910 int64_t pts) {
5911 if (!mTrack->isTimedTrack())
5912 return INVALID_OPERATION;
5913
5914 PlaybackThread::TimedTrack* tt =
5915 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5916 return tt->queueTimedBuffer(buffer, pts);
5917}
5918
5919status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5920 const LinearTransform& xform, int target) {
5921
5922 if (!mTrack->isTimedTrack())
5923 return INVALID_OPERATION;
5924
5925 PlaybackThread::TimedTrack* tt =
5926 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5927 return tt->setMediaTimeTransform(
5928 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5929}
5930
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931status_t AudioFlinger::TrackHandle::onTransact(
5932 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5933{
5934 return BnAudioTrack::onTransact(code, data, reply, flags);
5935}
5936
5937// ----------------------------------------------------------------------------
5938
5939sp<IAudioRecord> AudioFlinger::openRecord(
5940 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005941 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005943 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005944 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08005945 size_t frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005946 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005947 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 int *sessionId,
5949 status_t *status)
5950{
5951 sp<RecordThread::RecordTrack> recordTrack;
5952 sp<RecordHandle> recordHandle;
5953 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 status_t lStatus;
5955 RecordThread *thread;
5956 size_t inFrameCount;
5957 int lSessionId;
5958
5959 // check calling permissions
5960 if (!recordingAllowed()) {
5961 lStatus = PERMISSION_DENIED;
5962 goto Exit;
5963 }
5964
5965 // add client to list
5966 { // scope for mLock
5967 Mutex::Autolock _l(mLock);
5968 thread = checkRecordThread_l(input);
5969 if (thread == NULL) {
5970 lStatus = BAD_VALUE;
5971 goto Exit;
5972 }
5973
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005974 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975
5976 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005977 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 lSessionId = *sessionId;
5979 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005980 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 if (sessionId != NULL) {
5982 *sessionId = lSessionId;
5983 }
5984 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005985 // create new record track.
5986 // The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005987 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5988 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005990 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005991 // remove local strong reference to Client before deleting the RecordTrack so that the
5992 // Client destructor is called by the TrackBase destructor with mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 client.clear();
5994 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 goto Exit;
5996 }
5997
5998 // return to handle to client
5999 recordHandle = new RecordHandle(recordTrack);
6000 lStatus = NO_ERROR;
6001
6002Exit:
6003 if (status) {
6004 *status = lStatus;
6005 }
6006 return recordHandle;
6007}
6008
6009// ----------------------------------------------------------------------------
6010
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006011AudioFlinger::RecordHandle::RecordHandle(
6012 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 : BnAudioRecord(),
6014 mRecordTrack(recordTrack)
6015{
6016}
6017
6018AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006019 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006020 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021}
6022
Glenn Kasten90716c52012-01-26 13:40:12 -08006023sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6024 return mRecordTrack->getCblk();
6025}
6026
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006027status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
6028 int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006029 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006030 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031}
6032
6033void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006034 stop_nonvirtual();
6035}
6036
6037void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006038 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 mRecordTrack->stop();
6040}
6041
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042status_t AudioFlinger::RecordHandle::onTransact(
6043 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6044{
6045 return BnAudioRecord::onTransact(code, data, reply, flags);
6046}
6047
6048// ----------------------------------------------------------------------------
6049
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006050AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6051 AudioStreamIn *input,
6052 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006053 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006054 audio_io_handle_t id,
Glenn Kastend06785b2012-09-30 12:29:28 -07006055 audio_devices_t device,
6056 const sp<NBAIO_Sink>& teeSink) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006057 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006058 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006059 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07006060 mReqChannelCount(popcount(channelMask)),
Glenn Kastend06785b2012-09-30 12:29:28 -07006061 mReqSampleRate(sampleRate),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006062 // mBytesRead is only meaningful while active, and so is cleared in start()
6063 // (but might be better to also clear here for dump?)
Glenn Kastend06785b2012-09-30 12:29:28 -07006064 mTeeSink(teeSink)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006065{
Glenn Kasten480b4682012-02-28 12:30:08 -08006066 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006067
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 readInputParameters();
Glenn Kastend06785b2012-09-30 12:29:28 -07006069
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070}
6071
6072
6073AudioFlinger::RecordThread::~RecordThread()
6074{
6075 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006076 delete mResampler;
6077 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078}
6079
6080void AudioFlinger::RecordThread::onFirstRef()
6081{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006082 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083}
6084
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006085status_t AudioFlinger::RecordThread::readyToRun()
6086{
6087 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006088 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006089 return status;
6090}
6091
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092bool AudioFlinger::RecordThread::threadLoop()
6093{
6094 AudioBufferProvider::Buffer buffer;
6095 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006096 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097
Eric Laurent44d98482010-09-30 16:12:31 -07006098 nsecs_t lastWarning = 0;
6099
Glenn Kastene4e2a372012-07-23 12:55:09 -07006100 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006101 acquireWakeLock();
6102
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006103 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006104 bool readOnce = false;
6105
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106 // start recording
6107 while (!exitPending()) {
6108
6109 processConfigEvents();
6110
6111 { // scope for mLock
6112 Mutex::Autolock _l(mLock);
6113 checkForNewParameters_l();
6114 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006115 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116
Glenn Kastend65d73c2012-06-22 17:21:07 -07006117 if (exitPending()) {
6118 break;
6119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120
Eric Laurentfeb0db62011-07-22 09:04:31 -07006121 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006122 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 // go to sleep
6124 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006125 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006126 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 continue;
6128 }
6129 if (mActiveTrack != 0) {
6130 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006131 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 mActiveTrack.clear();
6133 mStartStopCond.broadcast();
6134 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6135 if (mReqChannelCount != mActiveTrack->channelCount()) {
6136 mActiveTrack.clear();
6137 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006138 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 // record start succeeds only if first read from audio input
6140 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006141 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142 mActiveTrack->mState = TrackBase::ACTIVE;
6143 } else {
6144 mActiveTrack.clear();
6145 }
6146 mStartStopCond.broadcast();
6147 }
6148 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006149 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6150 removeTrack_l(mActiveTrack);
6151 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006152 }
6153 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006154 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 }
6156
6157 if (mActiveTrack != 0) {
6158 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6159 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006160 unlockEffectChains(effectChains);
6161 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006162 continue;
6163 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006164 for (size_t i = 0; i < effectChains.size(); i ++) {
6165 effectChains[i]->process_l();
6166 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006167
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006169 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006170 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006171 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006172 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 // no resampling
6174 while (framesOut) {
6175 size_t framesIn = mFrameCount - mRsmpInIndex;
6176 if (framesIn) {
6177 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006178 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kasten83a03822012-11-12 07:58:20 -08006179 mActiveTrack->mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180 if (framesIn > framesOut)
6181 framesIn = framesOut;
6182 mRsmpInIndex += framesIn;
6183 framesOut -= framesIn;
Glenn Kastena42ff002012-11-14 12:47:55 -08006184 if (mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006185 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 memcpy(dst, src, framesIn * mFrameSize);
6187 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006189 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6190 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006192 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6193 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 }
6195 }
6196 }
6197 if (framesOut && mFrameCount == mRsmpInIndex) {
Glenn Kastend06785b2012-09-30 12:29:28 -07006198 void *readInto;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 if (framesOut == mFrameCount &&
Glenn Kastena42ff002012-11-14 12:47:55 -08006200 (mChannelCount == mReqChannelCount ||
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006201 mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07006202 readInto = buffer.raw;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 framesOut = 0;
6204 } else {
Glenn Kastend06785b2012-09-30 12:29:28 -07006205 readInto = mRsmpInBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206 mRsmpInIndex = 0;
6207 }
Glenn Kastend06785b2012-09-30 12:29:28 -07006208 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes);
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006209 if (mBytesRead <= 0) {
6210 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6211 {
6212 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 // Force input into standby so that it tries to
6214 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006215 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 }
6218 mRsmpInIndex = mFrameCount;
6219 framesOut = 0;
6220 buffer.frameCount = 0;
Glenn Kastend06785b2012-09-30 12:29:28 -07006221 } else if (mTeeSink != 0) {
6222 (void) mTeeSink->write(readInto,
6223 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 }
6225 }
6226 }
6227 } else {
6228 // resampling
6229
6230 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6231 // alter output frame count as if we were expecting stereo samples
6232 if (mChannelCount == 1 && mReqChannelCount == 1) {
6233 framesOut >>= 1;
6234 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006235 mResampler->resample(mRsmpOutBuffer, framesOut,
6236 this /* AudioBufferProvider* */);
6237 // ditherAndClamp() works as long as all buffers returned by
6238 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006240 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006241 // the resampler always outputs stereo samples:
6242 // do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006243 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6244 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006246 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006247 }
6248
6249 }
Eric Laurenta011e352012-03-29 15:51:43 -07006250 if (mFramestoDrop == 0) {
6251 mActiveTrack->releaseBuffer(&buffer);
6252 } else {
6253 if (mFramestoDrop > 0) {
6254 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006255 if (mFramestoDrop <= 0) {
6256 clearSyncStartEvent();
6257 }
6258 } else {
6259 mFramestoDrop += buffer.frameCount;
6260 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6261 mSyncStartEvent->isCancelled()) {
6262 ALOGW("Synced record %s, session %d, trigger session %d",
6263 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6264 mActiveTrack->sessionId(),
6265 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6266 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006267 }
6268 }
6269 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006270 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 }
6272 // client isn't retrieving buffers fast enough
6273 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006274 if (!mActiveTrack->setOverflow()) {
6275 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006276 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006277 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006278 lastWarning = now;
6279 }
6280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 // Release the processor for a while before asking for a new buffer.
6282 // This will give the application more chance to read from the buffer and
6283 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006284 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 }
6286 }
Eric Laurentec437d82011-07-26 20:54:46 -07006287 // enable changes in effect chain
6288 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006289 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 }
6291
Glenn Kastene4e2a372012-07-23 12:55:09 -07006292 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293
Glenn Kasten33e6e352012-07-16 15:56:57 -07006294 {
6295 Mutex::Autolock _l(mLock);
6296 mActiveTrack.clear();
6297 mStartStopCond.broadcast();
6298 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299
Eric Laurentfeb0db62011-07-22 09:04:31 -07006300 releaseWakeLock();
6301
Steve Block3856b092011-10-20 11:56:00 +01006302 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 return false;
6304}
6305
Glenn Kastene4e2a372012-07-23 12:55:09 -07006306void AudioFlinger::RecordThread::standby()
6307{
6308 if (!mStandby) {
6309 inputStandBy();
6310 mStandby = true;
6311 }
6312}
6313
6314void AudioFlinger::RecordThread::inputStandBy()
6315{
6316 mInput->stream->common.standby(&mInput->stream->common);
6317}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006318
6319sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6320 const sp<AudioFlinger::Client>& client,
6321 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006322 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006323 audio_channel_mask_t channelMask,
Glenn Kastene33054e2012-11-14 12:54:39 -08006324 size_t frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006325 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006326 IAudioFlinger::track_flags_t flags,
6327 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006328 status_t *status)
6329{
6330 sp<RecordTrack> track;
6331 status_t lStatus;
6332
6333 lStatus = initCheck();
6334 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006335 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006336 goto Exit;
6337 }
6338
Glenn Kasten1879fff2012-07-11 15:36:59 -07006339 // FIXME use flags and tid similar to createTrack_l()
6340
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006341 { // scope for mLock
6342 Mutex::Autolock _l(mLock);
6343
6344 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006345 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006346
Glenn Kasten7378ca52012-01-20 13:44:40 -08006347 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006348 lStatus = NO_MEMORY;
6349 goto Exit;
6350 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006351 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006352
Eric Laurent59bd0da2011-08-01 09:52:20 -07006353 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006354 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006355 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006356 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6357 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006358 }
6359 lStatus = NO_ERROR;
6360
6361Exit:
6362 if (status) {
6363 *status = lStatus;
6364 }
6365 return track;
6366}
6367
Eric Laurenta011e352012-03-29 15:51:43 -07006368status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006369 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006370 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006371{
Glenn Kasten58912562012-04-03 10:45:00 -07006372 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006373 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006375
6376 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006377 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006378 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6379 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6380 triggerSession,
6381 recordTrack->sessionId(),
6382 syncStartEventCallback,
6383 this);
Eric Laurent29864602012-05-08 18:57:51 -07006384 // Sync event can be cancelled by the trigger session if the track is not in a
6385 // compatible state in which case we start record immediately
6386 if (mSyncStartEvent->isCancelled()) {
6387 clearSyncStartEvent();
6388 } else {
6389 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6390 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6391 }
Eric Laurenta011e352012-03-29 15:51:43 -07006392 }
6393
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006395 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 if (mActiveTrack != 0) {
6397 if (recordTrack != mActiveTrack.get()) {
6398 status = -EBUSY;
6399 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6400 mActiveTrack->mState = TrackBase::ACTIVE;
6401 }
6402 return status;
6403 }
6404
6405 recordTrack->mState = TrackBase::IDLE;
6406 mActiveTrack = recordTrack;
6407 mLock.unlock();
6408 status_t status = AudioSystem::startInput(mId);
6409 mLock.lock();
6410 if (status != NO_ERROR) {
6411 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006412 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413 return status;
6414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006415 mRsmpInIndex = mFrameCount;
6416 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006417 if (mResampler != NULL) {
6418 mResampler->reset();
6419 }
6420 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006422 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006423 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006425 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 mActiveTrack.clear();
6427 status = INVALID_OPERATION;
6428 goto startError;
6429 }
6430 mStartStopCond.wait(mLock);
6431 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006432 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 status = BAD_VALUE;
6434 goto startError;
6435 }
Steve Block3856b092011-10-20 11:56:00 +01006436 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 return status;
6438 }
6439startError:
6440 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006441 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 return status;
6443}
6444
Eric Laurenta011e352012-03-29 15:51:43 -07006445void AudioFlinger::RecordThread::clearSyncStartEvent()
6446{
6447 if (mSyncStartEvent != 0) {
6448 mSyncStartEvent->cancel();
6449 }
6450 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006451 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006452}
6453
6454void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6455{
6456 sp<SyncEvent> strongEvent = event.promote();
6457
6458 if (strongEvent != 0) {
6459 RecordThread *me = (RecordThread *)strongEvent->cookie();
6460 me->handleSyncStartEvent(strongEvent);
6461 }
6462}
6463
6464void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6465{
Eric Laurent29864602012-05-08 18:57:51 -07006466 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006467 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6468 // from audio HAL
6469 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006470 }
6471}
6472
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006473bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006474 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006475 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6476 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006478 recordTrack->mState = TrackBase::PAUSING;
6479 // do not wait for mStartStopCond if exiting
6480 if (exitPending()) {
6481 return true;
6482 }
6483 mStartStopCond.wait(mLock);
6484 // if we have been restarted, recordTrack == mActiveTrack.get() here
6485 if (exitPending() || recordTrack != mActiveTrack.get()) {
6486 ALOGV("Record stopped OK");
6487 return true;
6488 }
6489 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490}
6491
Glenn Kasten106e8a42012-08-02 13:37:12 -07006492bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006493{
6494 return false;
6495}
6496
6497status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6498{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006499#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 -07006500 if (!isValidSyncEvent(event)) {
6501 return BAD_VALUE;
6502 }
6503
Glenn Kasten510a3d62012-07-16 14:24:34 -07006504 int eventSession = event->triggerSession();
6505 status_t ret = NAME_NOT_FOUND;
6506
Eric Laurenta011e352012-03-29 15:51:43 -07006507 Mutex::Autolock _l(mLock);
6508
Glenn Kasten510a3d62012-07-16 14:24:34 -07006509 for (size_t i = 0; i < mTracks.size(); i++) {
6510 sp<RecordTrack> track = mTracks[i];
6511 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006512 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006513 ret = NO_ERROR;
6514 }
Eric Laurenta011e352012-03-29 15:51:43 -07006515 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006516 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006517#else
6518 return BAD_VALUE;
6519#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006520}
6521
6522void AudioFlinger::RecordThread::RecordTrack::destroy()
6523{
6524 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6525 sp<RecordTrack> keep(this);
6526 {
6527 sp<ThreadBase> thread = mThread.promote();
6528 if (thread != 0) {
6529 if (mState == ACTIVE || mState == RESUMING) {
6530 AudioSystem::stopInput(thread->id());
6531 }
6532 AudioSystem::releaseInput(thread->id());
6533 Mutex::Autolock _l(thread->mLock);
6534 RecordThread *recordThread = (RecordThread *) thread.get();
6535 recordThread->destroyTrack_l(this);
6536 }
6537 }
6538}
6539
6540// destroyTrack_l() must be called with ThreadBase::mLock held
6541void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6542{
6543 track->mState = TrackBase::TERMINATED;
6544 // active tracks are removed by threadLoop()
6545 if (mActiveTrack != track) {
6546 removeTrack_l(track);
6547 }
6548}
6549
6550void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6551{
6552 mTracks.remove(track);
6553 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006554}
6555
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006556void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006558 dumpInternals(fd, args);
6559 dumpTracks(fd, args);
6560 dumpEffectChains(fd, args);
6561}
6562
6563void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6564{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006565 const size_t SIZE = 256;
6566 char buffer[SIZE];
6567 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568
6569 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6570 result.append(buffer);
6571
6572 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6574 result.append(buffer);
6575 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6576 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006577 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 result.append(buffer);
Glenn Kastena42ff002012-11-14 12:47:55 -08006579 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580 result.append(buffer);
Glenn Kasten3b16c762012-11-14 08:44:39 -08006581 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006584 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006586
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587 write(fd, result.string(), result.size());
6588
6589 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006590}
6591
6592void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6593{
6594 const size_t SIZE = 256;
6595 char buffer[SIZE];
6596 String8 result;
6597
6598 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6599 result.append(buffer);
6600 RecordTrack::appendDumpHeader(result);
6601 for (size_t i = 0; i < mTracks.size(); ++i) {
6602 sp<RecordTrack> track = mTracks[i];
6603 if (track != 0) {
6604 track->dump(buffer, SIZE);
6605 result.append(buffer);
6606 }
6607 }
6608
6609 if (mActiveTrack != 0) {
6610 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6611 result.append(buffer);
6612 RecordTrack::appendDumpHeader(result);
6613 mActiveTrack->dump(buffer, SIZE);
6614 result.append(buffer);
6615
6616 }
6617 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618}
6619
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006620// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006621status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622{
6623 size_t framesReq = buffer->frameCount;
6624 size_t framesReady = mFrameCount - mRsmpInIndex;
6625 int channelCount;
6626
6627 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006628 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006629 if (mBytesRead <= 0) {
6630 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6631 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632 // Force input into standby so that it tries to
6633 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006634 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006635 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006636 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006637 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638 buffer->frameCount = 0;
6639 return NOT_ENOUGH_DATA;
6640 }
6641 mRsmpInIndex = 0;
6642 framesReady = mFrameCount;
6643 }
6644
6645 if (framesReq > framesReady) {
6646 framesReq = framesReady;
6647 }
6648
6649 if (mChannelCount == 1 && mReqChannelCount == 2) {
6650 channelCount = 1;
6651 } else {
6652 channelCount = 2;
6653 }
6654 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6655 buffer->frameCount = framesReq;
6656 return NO_ERROR;
6657}
6658
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006659// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6661{
6662 mRsmpInIndex += buffer->frameCount;
6663 buffer->frameCount = 0;
6664}
6665
6666bool AudioFlinger::RecordThread::checkForNewParameters_l()
6667{
6668 bool reconfig = false;
6669
6670 while (!mNewParameters.isEmpty()) {
6671 status_t status = NO_ERROR;
6672 String8 keyValuePair = mNewParameters[0];
6673 AudioParameter param = AudioParameter(keyValuePair);
6674 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006675 audio_format_t reqFormat = mFormat;
Glenn Kasten3b16c762012-11-14 08:44:39 -08006676 uint32_t reqSamplingRate = mReqSampleRate;
Glenn Kastena42ff002012-11-14 12:47:55 -08006677 uint32_t reqChannelCount = mReqChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678
6679 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6680 reqSamplingRate = value;
6681 reconfig = true;
6682 }
6683 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006684 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006685 reconfig = true;
6686 }
6687 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006688 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 reconfig = true;
6690 }
6691 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6692 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006693 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006694 // if frame count is changed after track creation
6695 if (mActiveTrack != 0) {
6696 status = INVALID_OPERATION;
6697 } else {
6698 reconfig = true;
6699 }
6700 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006701 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6702 // forward device change to effects that have requested to be
6703 // aware of attached audio device.
6704 for (size_t i = 0; i < mEffectChains.size(); i++) {
6705 mEffectChains[i]->setDevice_l(value);
6706 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07006707
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006708 // store input device and output device but do not forward output device to audio HAL.
6709 // Note that status is ignored by the caller for output device
6710 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07006711 if (audio_is_output_devices(value)) {
6712 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006713 status = BAD_VALUE;
6714 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006715 mInDevice = value;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006716 // disable AEC and NS if the device is a BT SCO headset supporting those
6717 // pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006718 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006719 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6720 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006721 for (size_t i = 0; i < mTracks.size(); i++) {
6722 sp<RecordTrack> track = mTracks[i];
6723 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6724 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6725 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006726 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006727 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006728 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07006729 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6730 mAudioSource != (audio_source_t)value) {
6731 // forward device change to effects that have requested to be
6732 // aware of attached audio device.
6733 for (size_t i = 0; i < mEffectChains.size(); i++) {
6734 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6735 }
6736 mAudioSource = (audio_source_t)value;
6737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006738 if (status == NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006739 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6740 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006742 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006743 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6744 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 }
6746 if (reconfig) {
6747 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006748 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006749 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006750 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common)
6751 <= (2 * reqSamplingRate)) &&
6752 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
6753 <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006754 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 status = NO_ERROR;
6756 }
6757 if (status == NO_ERROR) {
6758 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07006759 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760 }
6761 }
6762 }
6763
6764 mNewParameters.removeAt(0);
6765
6766 mParamStatus = status;
6767 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006768 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6769 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006770 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771 }
6772 return reconfig;
6773}
6774
6775String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6776{
Dima Zavinfce7a472011-04-19 22:30:36 -07006777 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006778 String8 out_s8 = String8();
6779
6780 Mutex::Autolock _l(mLock);
6781 if (initCheck() != NO_ERROR) {
6782 return out_s8;
6783 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006784
Dima Zavin799a70e2011-04-18 16:57:27 -07006785 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006786 out_s8 = String8(s);
6787 free(s);
6788 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789}
6790
6791void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6792 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006793 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006794
6795 switch (event) {
6796 case AudioSystem::INPUT_OPENED:
6797 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006798 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 desc.samplingRate = mSampleRate;
6800 desc.format = mFormat;
6801 desc.frameCount = mFrameCount;
6802 desc.latency = 0;
6803 param2 = &desc;
6804 break;
6805
6806 case AudioSystem::INPUT_CLOSED:
6807 default:
6808 break;
6809 }
6810 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6811}
6812
6813void AudioFlinger::RecordThread::readInputParameters()
6814{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006815 delete mRsmpInBuffer;
6816 // mRsmpInBuffer is always assigned a new[] below
6817 delete mRsmpOutBuffer;
6818 mRsmpOutBuffer = NULL;
6819 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006820 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821
Dima Zavin799a70e2011-04-18 16:57:27 -07006822 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006823 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6824 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006825 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006826 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006827 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006828 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006829 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006830 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6831
Glenn Kasten53d76db2012-03-08 12:32:47 -08006832 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 {
6834 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006835 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6836 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 if (mChannelCount == 1 && mReqChannelCount == 2) {
6838 channelCount = 1;
6839 } else {
6840 channelCount = 2;
6841 }
6842 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6843 mResampler->setSampleRate(mSampleRate);
6844 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6845 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6846
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006847 // optmization: if mono to mono, alter input frame count as if we were inputing
6848 // stereo samples
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849 if (mChannelCount == 1 && mReqChannelCount == 1) {
6850 mFrameCount >>= 1;
6851 }
6852
6853 }
6854 mRsmpInIndex = mFrameCount;
6855}
6856
6857unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6858{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006859 Mutex::Autolock _l(mLock);
6860 if (initCheck() != NO_ERROR) {
6861 return 0;
6862 }
6863
Dima Zavin799a70e2011-04-18 16:57:27 -07006864 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865}
6866
Glenn Kasten106e8a42012-08-02 13:37:12 -07006867uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006868{
6869 Mutex::Autolock _l(mLock);
6870 uint32_t result = 0;
6871 if (getEffectChain_l(sessionId) != 0) {
6872 result = EFFECT_SESSION;
6873 }
6874
Glenn Kasten510a3d62012-07-16 14:24:34 -07006875 for (size_t i = 0; i < mTracks.size(); ++i) {
6876 if (sessionId == mTracks[i]->sessionId()) {
6877 result |= TRACK_SESSION;
6878 break;
6879 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006880 }
6881
6882 return result;
6883}
6884
Glenn Kasten106e8a42012-08-02 13:37:12 -07006885KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006886{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006887 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006888 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006889 for (size_t j = 0; j < mTracks.size(); ++j) {
6890 sp<RecordThread::RecordTrack> track = mTracks[j];
6891 int sessionId = track->sessionId();
6892 if (ids.indexOfKey(sessionId) < 0) {
6893 ids.add(sessionId, true);
6894 }
6895 }
6896 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006897}
6898
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006899AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6900{
6901 Mutex::Autolock _l(mLock);
6902 AudioStreamIn *input = mInput;
6903 mInput = NULL;
6904 return input;
6905}
6906
6907// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006908audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006909{
6910 if (mInput == NULL) {
6911 return NULL;
6912 }
6913 return &mInput->stream->common;
6914}
6915
6916
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917// ----------------------------------------------------------------------------
6918
Eric Laurenta4c5a552012-03-29 10:12:40 -07006919audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6920{
6921 if (!settingsAllowed()) {
6922 return 0;
6923 }
6924 Mutex::Autolock _l(mLock);
6925 return loadHwModule_l(name);
6926}
6927
6928// loadHwModule_l() must be called with AudioFlinger::mLock held
6929audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6930{
6931 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6932 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6933 ALOGW("loadHwModule() module %s already loaded", name);
6934 return mAudioHwDevs.keyAt(i);
6935 }
6936 }
6937
Eric Laurenta4c5a552012-03-29 10:12:40 -07006938 audio_hw_device_t *dev;
6939
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006940 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006941 if (rc) {
6942 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6943 return 0;
6944 }
6945
6946 mHardwareStatus = AUDIO_HW_INIT;
6947 rc = dev->init_check(dev);
6948 mHardwareStatus = AUDIO_HW_IDLE;
6949 if (rc) {
6950 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6951 return 0;
6952 }
6953
John Grossmanee578c02012-07-23 17:05:46 -07006954 // Check and cache this HAL's level of support for master mute and master
6955 // volume. If this is the first HAL opened, and it supports the get
6956 // methods, use the initial values provided by the HAL as the current
6957 // master mute and volume settings.
6958
6959 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6960 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006961 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006962
6963 if (0 == mAudioHwDevs.size()) {
6964 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6965 if (NULL != dev->get_master_volume) {
6966 float mv;
6967 if (OK == dev->get_master_volume(dev, &mv)) {
6968 mMasterVolume = mv;
6969 }
6970 }
6971
6972 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6973 if (NULL != dev->get_master_mute) {
6974 bool mm;
6975 if (OK == dev->get_master_mute(dev, &mm)) {
6976 mMasterMute = mm;
6977 }
6978 }
6979 }
6980
Eric Laurenta4c5a552012-03-29 10:12:40 -07006981 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006982 if ((NULL != dev->set_master_volume) &&
6983 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6984 flags = static_cast<AudioHwDevice::Flags>(flags |
6985 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6986 }
6987
6988 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6989 if ((NULL != dev->set_master_mute) &&
6990 (OK == dev->set_master_mute(dev, mMasterMute))) {
6991 flags = static_cast<AudioHwDevice::Flags>(flags |
6992 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6993 }
6994
Eric Laurenta4c5a552012-03-29 10:12:40 -07006995 mHardwareStatus = AUDIO_HW_IDLE;
6996 }
6997
6998 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006999 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007000
7001 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007002 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007003
7004 return handle;
7005
7006}
7007
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007008// ----------------------------------------------------------------------------
7009
Glenn Kasten3b16c762012-11-14 08:44:39 -08007010uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007011{
7012 Mutex::Autolock _l(mLock);
7013 PlaybackThread *thread = primaryPlaybackThread_l();
7014 return thread != NULL ? thread->sampleRate() : 0;
7015}
7016
Glenn Kastene33054e2012-11-14 12:54:39 -08007017size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007018{
7019 Mutex::Autolock _l(mLock);
7020 PlaybackThread *thread = primaryPlaybackThread_l();
7021 return thread != NULL ? thread->frameCountHAL() : 0;
7022}
7023
7024// ----------------------------------------------------------------------------
7025
Eric Laurenta4c5a552012-03-29 10:12:40 -07007026audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7027 audio_devices_t *pDevices,
7028 uint32_t *pSamplingRate,
7029 audio_format_t *pFormat,
7030 audio_channel_mask_t *pChannelMask,
7031 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007032 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007033{
7034 status_t status;
7035 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007036 struct audio_config config = {
7037 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7038 channel_mask: pChannelMask ? *pChannelMask : 0,
7039 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7040 };
7041 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007042 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043
Eric Laurenta4c5a552012-03-29 10:12:40 -07007044 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7045 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007046 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007047 config.sample_rate,
7048 config.format,
7049 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007050 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051
7052 if (pDevices == NULL || *pDevices == 0) {
7053 return 0;
7054 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007055
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056 Mutex::Autolock _l(mLock);
7057
Eric Laurenta4c5a552012-03-29 10:12:40 -07007058 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007059 if (outHwDev == NULL)
7060 return 0;
7061
John Grossmanee578c02012-07-23 17:05:46 -07007062 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007063 audio_io_handle_t id = nextUniqueId();
7064
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007065 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007066
John Grossmanee578c02012-07-23 17:05:46 -07007067 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007068 id,
7069 *pDevices,
7070 (audio_output_flags_t)flags,
7071 &config,
7072 &outStream);
7073
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007074 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007075 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, "
7076 "Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007077 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007078 config.sample_rate,
7079 config.format,
7080 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081 status);
7082
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007083 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007084 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007085
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007086 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007087 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7088 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007090 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007091 } else {
7092 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007093 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007094 }
7095 mPlaybackThreads.add(id, thread);
7096
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007097 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7098 if (pFormat != NULL) *pFormat = config.format;
7099 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08007100 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101
7102 // notify client processes of the new output creation
7103 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007104
7105 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007106 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007107 ALOGI("Using module %d has the primary audio interface", module);
7108 mPrimaryHardwareDev = outHwDev;
7109
7110 AutoMutex lock(mHardwareLock);
7111 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007112 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007113 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115 return id;
7116 }
7117
7118 return 0;
7119}
7120
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007121audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7122 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123{
7124 Mutex::Autolock _l(mLock);
7125 MixerThread *thread1 = checkMixerThread_l(output1);
7126 MixerThread *thread2 = checkMixerThread_l(output2);
7127
7128 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007129 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
7130 output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131 return 0;
7132 }
7133
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007134 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7136 thread->addOutputTrack(thread2);
7137 mPlaybackThreads.add(id, thread);
7138 // notify client processes of the new output creation
7139 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7140 return id;
7141}
7142
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007143status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144{
Glenn Kastend96c5722012-04-25 13:44:49 -07007145 return closeOutput_nonvirtual(output);
7146}
7147
7148status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7149{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007150 // keep strong reference on the playback thread so that
7151 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007152 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 {
7154 Mutex::Autolock _l(mLock);
7155 thread = checkPlaybackThread_l(output);
7156 if (thread == NULL) {
7157 return BAD_VALUE;
7158 }
7159
Steve Block3856b092011-10-20 11:56:00 +01007160 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007162 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007164 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007165 DuplicatingThread *dupThread =
7166 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167 dupThread->removeOutputTrack((MixerThread *)thread.get());
7168 }
7169 }
7170 }
Glenn Kastena1117922012-01-26 10:53:32 -08007171 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 mPlaybackThreads.removeItem(output);
7173 }
7174 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007175 // The thread entity (active unit of execution) is no longer running here,
7176 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007178 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007179 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007180 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007181 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007182 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007183 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184 }
7185 return NO_ERROR;
7186}
7187
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007188status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189{
7190 Mutex::Autolock _l(mLock);
7191 PlaybackThread *thread = checkPlaybackThread_l(output);
7192
7193 if (thread == NULL) {
7194 return BAD_VALUE;
7195 }
7196
Steve Block3856b092011-10-20 11:56:00 +01007197 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198 thread->suspend();
7199
7200 return NO_ERROR;
7201}
7202
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007203status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204{
7205 Mutex::Autolock _l(mLock);
7206 PlaybackThread *thread = checkPlaybackThread_l(output);
7207
7208 if (thread == NULL) {
7209 return BAD_VALUE;
7210 }
7211
Steve Block3856b092011-10-20 11:56:00 +01007212 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213
7214 thread->restore();
7215
7216 return NO_ERROR;
7217}
7218
Eric Laurenta4c5a552012-03-29 10:12:40 -07007219audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7220 audio_devices_t *pDevices,
7221 uint32_t *pSamplingRate,
7222 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007223 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007224{
7225 status_t status;
7226 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007227 struct audio_config config = {
7228 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7229 channel_mask: pChannelMask ? *pChannelMask : 0,
7230 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7231 };
7232 uint32_t reqSamplingRate = config.sample_rate;
7233 audio_format_t reqFormat = config.format;
7234 audio_channel_mask_t reqChannels = config.channel_mask;
7235 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007236 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237
7238 if (pDevices == NULL || *pDevices == 0) {
7239 return 0;
7240 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007241
Mathias Agopian65ab4712010-07-14 17:59:35 -07007242 Mutex::Autolock _l(mLock);
7243
Eric Laurenta4c5a552012-03-29 10:12:40 -07007244 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007245 if (inHwDev == NULL)
7246 return 0;
7247
John Grossmanee578c02012-07-23 17:05:46 -07007248 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007249 audio_io_handle_t id = nextUniqueId();
7250
John Grossmanee578c02012-07-23 17:05:46 -07007251 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007252 &inStream);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007253 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
7254 "status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007255 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007256 config.sample_rate,
7257 config.format,
7258 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259 status);
7260
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007261 // If the input could not be opened with the requested parameters and we can handle the
7262 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
7263 // 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 -07007264 if (status == BAD_VALUE &&
7265 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7266 (config.sample_rate <= 2 * reqSamplingRate) &&
7267 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007268 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007269 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007270 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 }
7272
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007273 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07007274
7275 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
7276 // or (re-)create if current Pipe is idle and does not match the new format
7277 sp<NBAIO_Sink> teeSink;
7278#ifdef TEE_SINK_INPUT_FRAMES
7279 enum {
7280 TEE_SINK_NO, // don't copy input
7281 TEE_SINK_NEW, // copy input using a new pipe
7282 TEE_SINK_OLD, // copy input using an existing pipe
7283 } kind;
7284 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
7285 popcount(inStream->common.get_channels(&inStream->common)));
7286 if (format == Format_Invalid) {
7287 kind = TEE_SINK_NO;
7288 } else if (mRecordTeeSink == 0) {
7289 kind = TEE_SINK_NEW;
7290 } else if (mRecordTeeSink->getStrongCount() != 1) {
7291 kind = TEE_SINK_NO;
7292 } else if (format == mRecordTeeSink->format()) {
7293 kind = TEE_SINK_OLD;
7294 } else {
7295 kind = TEE_SINK_NEW;
7296 }
7297 switch (kind) {
7298 case TEE_SINK_NEW: {
7299 Pipe *pipe = new Pipe(TEE_SINK_INPUT_FRAMES, format);
7300 size_t numCounterOffers = 0;
7301 const NBAIO_Format offers[1] = {format};
7302 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7303 ALOG_ASSERT(index == 0);
7304 PipeReader *pipeReader = new PipeReader(*pipe);
7305 numCounterOffers = 0;
7306 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7307 ALOG_ASSERT(index == 0);
7308 mRecordTeeSink = pipe;
7309 mRecordTeeSource = pipeReader;
7310 teeSink = pipe;
7311 }
7312 break;
7313 case TEE_SINK_OLD:
7314 teeSink = mRecordTeeSink;
7315 break;
7316 case TEE_SINK_NO:
7317 default:
7318 break;
7319 }
7320#endif
Dima Zavin799a70e2011-04-18 16:57:27 -07007321 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7322
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007323 // Start record thread
7324 // RecorThread require both input and output device indication to forward to audio
7325 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007326 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Glenn Kastend06785b2012-09-30 12:29:28 -07007327
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007328 thread = new RecordThread(this,
7329 input,
7330 reqSamplingRate,
7331 reqChannels,
7332 id,
Glenn Kastend06785b2012-09-30 12:29:28 -07007333 device, teeSink);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007335 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007336 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007337 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007338 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339
Mathias Agopian65ab4712010-07-14 17:59:35 -07007340 // notify client processes of the new input creation
7341 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7342 return id;
7343 }
7344
7345 return 0;
7346}
7347
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007348status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349{
Glenn Kastend96c5722012-04-25 13:44:49 -07007350 return closeInput_nonvirtual(input);
7351}
7352
7353status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7354{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007355 // keep strong reference on the record thread so that
7356 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007357 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 {
7359 Mutex::Autolock _l(mLock);
7360 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007361 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 return BAD_VALUE;
7363 }
7364
Steve Block3856b092011-10-20 11:56:00 +01007365 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007366 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 mRecordThreads.removeItem(input);
7368 }
7369 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007370 // The thread entity (active unit of execution) is no longer running here,
7371 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007373 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007374 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007375 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007376 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007377 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378
7379 return NO_ERROR;
7380}
7381
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007382status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383{
7384 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007385 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386
7387 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7388 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007389 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391
7392 return NO_ERROR;
7393}
7394
7395
7396int AudioFlinger::newAudioSessionId()
7397{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007398 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399}
7400
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007401void AudioFlinger::acquireAudioSessionId(int audioSession)
7402{
7403 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007404 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007405 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007406 size_t num = mAudioSessionRefs.size();
7407 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007408 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007409 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7410 ref->mCnt++;
7411 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007412 return;
7413 }
7414 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007415 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7416 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007417}
7418
7419void AudioFlinger::releaseAudioSessionId(int audioSession)
7420{
7421 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007422 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007423 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007424 size_t num = mAudioSessionRefs.size();
7425 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007426 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007427 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7428 ref->mCnt--;
7429 ALOGV(" decremented refcount to %d", ref->mCnt);
7430 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007431 mAudioSessionRefs.removeAt(i);
7432 delete ref;
7433 purgeStaleEffects_l();
7434 }
7435 return;
7436 }
7437 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007438 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007439}
7440
7441void AudioFlinger::purgeStaleEffects_l() {
7442
Steve Block3856b092011-10-20 11:56:00 +01007443 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007444
7445 Vector< sp<EffectChain> > chains;
7446
7447 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7448 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7449 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7450 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007451 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7452 chains.push(ec);
7453 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007454 }
7455 }
7456 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7457 sp<RecordThread> t = mRecordThreads.valueAt(i);
7458 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7459 sp<EffectChain> ec = t->mEffectChains[j];
7460 chains.push(ec);
7461 }
7462 }
7463
7464 for (size_t i = 0; i < chains.size(); i++) {
7465 sp<EffectChain> ec = chains[i];
7466 int sessionid = ec->sessionId();
7467 sp<ThreadBase> t = ec->mThread.promote();
7468 if (t == 0) {
7469 continue;
7470 }
7471 size_t numsessionrefs = mAudioSessionRefs.size();
7472 bool found = false;
7473 for (size_t k = 0; k < numsessionrefs; k++) {
7474 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007475 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007476 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007477 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007478 found = true;
7479 break;
7480 }
7481 }
7482 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007483 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007484 // remove all effects from the chain
7485 while (ec->mEffects.size()) {
7486 sp<EffectModule> effect = ec->mEffects[0];
7487 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007488 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007489 if (effect->purgeHandles()) {
7490 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007491 }
7492 AudioSystem::unregisterEffect(effect->id());
7493 }
7494 }
7495 }
7496 return;
7497}
7498
Mathias Agopian65ab4712010-07-14 17:59:35 -07007499// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007500AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501{
Glenn Kastena1117922012-01-26 10:53:32 -08007502 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503}
7504
7505// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007506AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507{
7508 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007509 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007510}
7511
7512// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007513AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007514{
Glenn Kastena1117922012-01-26 10:53:32 -08007515 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007516}
7517
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007518uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007520 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007521}
7522
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007523AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007524{
7525 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7526 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007527 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007528 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007529 return thread;
7530 }
7531 }
7532 return NULL;
7533}
7534
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007535audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007536{
7537 PlaybackThread *thread = primaryPlaybackThread_l();
7538
7539 if (thread == NULL) {
7540 return 0;
7541 }
7542
Eric Laurentf1c04f92012-08-28 14:26:53 -07007543 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007544}
7545
Eric Laurenta011e352012-03-29 15:51:43 -07007546sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7547 int triggerSession,
7548 int listenerSession,
7549 sync_event_callback_t callBack,
7550 void *cookie)
7551{
7552 Mutex::Autolock _l(mLock);
7553
7554 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7555 status_t playStatus = NAME_NOT_FOUND;
7556 status_t recStatus = NAME_NOT_FOUND;
7557 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7558 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7559 if (playStatus == NO_ERROR) {
7560 return event;
7561 }
7562 }
7563 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7564 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7565 if (recStatus == NO_ERROR) {
7566 return event;
7567 }
7568 }
7569 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7570 mPendingSyncEvents.add(event);
7571 } else {
7572 ALOGV("createSyncEvent() invalid event %d", event->type());
7573 event.clear();
7574 }
7575 return event;
7576}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007577
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578// ----------------------------------------------------------------------------
7579// Effect management
7580// ----------------------------------------------------------------------------
7581
7582
Glenn Kastenf587ba52012-01-26 16:25:10 -08007583status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584{
7585 Mutex::Autolock _l(mLock);
7586 return EffectQueryNumberEffects(numEffects);
7587}
7588
Glenn Kastenf587ba52012-01-26 16:25:10 -08007589status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590{
7591 Mutex::Autolock _l(mLock);
7592 return EffectQueryEffect(index, descriptor);
7593}
7594
Glenn Kasten5e92a782012-01-30 07:40:52 -08007595status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007596 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597{
7598 Mutex::Autolock _l(mLock);
7599 return EffectGetDescriptor(pUuid, descriptor);
7600}
7601
7602
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7604 effect_descriptor_t *pDesc,
7605 const sp<IEffectClient>& effectClient,
7606 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007607 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 int sessionId,
7609 status_t *status,
7610 int *id,
7611 int *enabled)
7612{
7613 status_t lStatus = NO_ERROR;
7614 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007617 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007618 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619
7620 if (pDesc == NULL) {
7621 lStatus = BAD_VALUE;
7622 goto Exit;
7623 }
7624
Eric Laurent84e9a102010-09-23 16:10:16 -07007625 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007626 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007627 lStatus = PERMISSION_DENIED;
7628 goto Exit;
7629 }
7630
Dima Zavinfce7a472011-04-19 22:30:36 -07007631 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007632 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007633 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007634 lStatus = PERMISSION_DENIED;
7635 goto Exit;
7636 }
7637
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007638 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007639 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007640 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007641 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007642 lStatus = BAD_VALUE;
7643 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007644 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007645 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007646 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007647 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007648 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007649 }
7650 }
7651
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652 {
7653 Mutex::Autolock _l(mLock);
7654
Mathias Agopian65ab4712010-07-14 17:59:35 -07007655
7656 if (!EffectIsNullUuid(&pDesc->uuid)) {
7657 // if uuid is specified, request effect descriptor
7658 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7659 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007660 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007661 goto Exit;
7662 }
7663 } else {
7664 // if uuid is not specified, look for an available implementation
7665 // of the required type in effect factory
7666 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007667 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007668 lStatus = BAD_VALUE;
7669 goto Exit;
7670 }
7671 uint32_t numEffects = 0;
7672 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007673 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007674 bool found = false;
7675
7676 lStatus = EffectQueryNumberEffects(&numEffects);
7677 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007678 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 goto Exit;
7680 }
7681 for (uint32_t i = 0; i < numEffects; i++) {
7682 lStatus = EffectQueryEffect(i, &desc);
7683 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007684 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685 continue;
7686 }
7687 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7688 // If matching type found save effect descriptor. If the session is
7689 // 0 and the effect is not auxiliary, continue enumeration in case
7690 // an auxiliary version of this effect type is available
7691 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007692 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007693 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007694 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7695 break;
7696 }
7697 }
7698 }
7699 if (!found) {
7700 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007701 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007702 goto Exit;
7703 }
7704 // For same effect type, chose auxiliary version over insert version if
7705 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007706 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007708 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007709 }
7710 }
7711
7712 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007713 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007714 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7715 lStatus = INVALID_OPERATION;
7716 goto Exit;
7717 }
7718
Eric Laurent59255e42011-07-27 19:49:51 -07007719 // check recording permission for visualizer
7720 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7721 !recordingAllowed()) {
7722 lStatus = PERMISSION_DENIED;
7723 goto Exit;
7724 }
7725
Mathias Agopian65ab4712010-07-14 17:59:35 -07007726 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007727 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728
7729 // If output is not specified try to find a matching audio session ID in one of the
7730 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007731 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7732 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007733 // Note: io is never 0 when creating an effect on an input
7734 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007735 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7737 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007738 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007739 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007741 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007742 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007743 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7744 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7745 io = mRecordThreads.keyAt(i);
7746 break;
7747 }
7748 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007749 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007750 // If no output thread contains the requested session ID, default to
7751 // first output. The effect chain will be moved to the correct output
7752 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007753 if (io == 0 && mPlaybackThreads.size()) {
7754 io = mPlaybackThreads.keyAt(0);
7755 }
Steve Block3856b092011-10-20 11:56:00 +01007756 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007757 }
7758 ThreadBase *thread = checkRecordThread_l(io);
7759 if (thread == NULL) {
7760 thread = checkPlaybackThread_l(io);
7761 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007762 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007763 lStatus = BAD_VALUE;
7764 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007765 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007766 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007767
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007768 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007770 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007771 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7772 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773 if (handle != 0 && id != NULL) {
7774 *id = handle->id();
7775 }
7776 }
7777
7778Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007779 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 *status = lStatus;
7781 }
7782 return handle;
7783}
7784
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007785status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7786 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007787{
Steve Block3856b092011-10-20 11:56:00 +01007788 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007789 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007790 Mutex::Autolock _l(mLock);
7791 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007792 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007793 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 }
Eric Laurentde070132010-07-13 04:45:46 -07007795 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7796 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007797 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007798 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 }
Eric Laurentde070132010-07-13 04:45:46 -07007800 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7801 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007802 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007803 return BAD_VALUE;
7804 }
7805
7806 Mutex::Autolock _dl(dstThread->mLock);
7807 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007808 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007809
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 return NO_ERROR;
7811}
7812
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007813// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007814status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007815 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007816 AudioFlinger::PlaybackThread *dstThread,
7817 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007818{
Steve Block3856b092011-10-20 11:56:00 +01007819 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007820 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007821
Eric Laurent59255e42011-07-27 19:49:51 -07007822 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007823 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007824 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007825 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007826 return INVALID_OPERATION;
7827 }
7828
Eric Laurent39e94f82010-07-28 01:32:47 -07007829 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007830 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007831 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007832 // removed.
7833 srcThread->removeEffectChain_l(chain);
7834
7835 // transfer all effects one by one so that new effect chain is created on new thread with
7836 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007837 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007838 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007839 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007840 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7841 while (effect != 0) {
7842 srcThread->removeEffect_l(effect);
7843 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007844 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7845 if (effect->state() == EffectModule::ACTIVE ||
7846 effect->state() == EffectModule::STOPPING) {
7847 effect->start();
7848 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007849 // if the move request is not received from audio policy manager, the effect must be
7850 // re-registered with the new strategy and output
7851 if (dstChain == 0) {
7852 dstChain = effect->chain().promote();
7853 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007854 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007855 srcThread->addEffect_l(effect);
7856 return NO_INIT;
7857 }
7858 strategy = dstChain->strategy();
7859 }
7860 if (reRegister) {
7861 AudioSystem::unregisterEffect(effect->id());
7862 AudioSystem::registerEffect(&effect->desc(),
7863 dstOutput,
7864 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007865 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007866 effect->id());
7867 }
Eric Laurentde070132010-07-13 04:45:46 -07007868 effect = chain->getEffectFromId_l(0);
7869 }
7870
7871 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872}
7873
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007874
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007876sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007877 const sp<AudioFlinger::Client>& client,
7878 const sp<IEffectClient>& effectClient,
7879 int32_t priority,
7880 int sessionId,
7881 effect_descriptor_t *desc,
7882 int *enabled,
7883 status_t *status
7884 )
7885{
7886 sp<EffectModule> effect;
7887 sp<EffectHandle> handle;
7888 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007890 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891 bool effectCreated = false;
7892 bool effectRegistered = false;
7893
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007894 lStatus = initCheck();
7895 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007896 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897 goto Exit;
7898 }
7899
7900 // Do not allow effects with session ID 0 on direct output or duplicating threads
7901 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007902 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007903 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007904 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905 lStatus = BAD_VALUE;
7906 goto Exit;
7907 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007908 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007909 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007910 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007911 desc->name, desc->flags, mType);
7912 lStatus = BAD_VALUE;
7913 goto Exit;
7914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915
Steve Block3856b092011-10-20 11:56:00 +01007916 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007917
7918 { // scope for mLock
7919 Mutex::Autolock _l(mLock);
7920
7921 // check for existing effect chain with the requested audio session
7922 chain = getEffectChain_l(sessionId);
7923 if (chain == 0) {
7924 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007925 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007926 chain = new EffectChain(this, sessionId);
7927 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007928 chain->setStrategy(getStrategyForSession_l(sessionId));
7929 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007930 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007931 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 }
7933
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007934 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935
7936 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007937 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007939 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007940 if (lStatus != NO_ERROR) {
7941 goto Exit;
7942 }
7943 effectRegistered = true;
7944 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007945 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007946 lStatus = effect->status();
7947 if (lStatus != NO_ERROR) {
7948 goto Exit;
7949 }
Eric Laurentcab11242010-07-15 12:50:15 -07007950 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951 if (lStatus != NO_ERROR) {
7952 goto Exit;
7953 }
7954 effectCreated = true;
7955
Eric Laurentf1c04f92012-08-28 14:26:53 -07007956 effect->setDevice(mOutDevice);
7957 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007958 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007959 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960 }
7961 // create effect handle and connect it to effect module
7962 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007963 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007964 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007965 *enabled = (int)effect->isEnabled();
7966 }
7967 }
7968
7969Exit:
7970 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007971 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007972 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007973 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007974 }
7975 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007976 AudioSystem::unregisterEffect(effect->id());
7977 }
7978 if (chainCreated) {
7979 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980 }
7981 handle.clear();
7982 }
7983
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007984 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007985 *status = lStatus;
7986 }
7987 return handle;
7988}
7989
Eric Laurent717e1282012-06-29 16:36:52 -07007990sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7991{
7992 Mutex::Autolock _l(mLock);
7993 return getEffect_l(sessionId, effectId);
7994}
7995
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007996sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7997{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007998 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007999 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008000}
8001
Eric Laurentde070132010-07-13 04:45:46 -07008002// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8003// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008004status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008005{
8006 // check for existing effect chain with the requested audio session
8007 int sessionId = effect->sessionId();
8008 sp<EffectChain> chain = getEffectChain_l(sessionId);
8009 bool chainCreated = false;
8010
8011 if (chain == 0) {
8012 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008013 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008014 chain = new EffectChain(this, sessionId);
8015 addEffectChain_l(chain);
8016 chain->setStrategy(getStrategyForSession_l(sessionId));
8017 chainCreated = true;
8018 }
Steve Block3856b092011-10-20 11:56:00 +01008019 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008020
8021 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008022 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008023 this, effect->desc().name, chain.get());
8024 return BAD_VALUE;
8025 }
8026
8027 status_t status = chain->addEffect_l(effect);
8028 if (status != NO_ERROR) {
8029 if (chainCreated) {
8030 removeEffectChain_l(chain);
8031 }
8032 return status;
8033 }
8034
Eric Laurentf1c04f92012-08-28 14:26:53 -07008035 effect->setDevice(mOutDevice);
8036 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008037 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008038 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008039 return NO_ERROR;
8040}
8041
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008042void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008043
Steve Block3856b092011-10-20 11:56:00 +01008044 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008046 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8047 detachAuxEffect_l(effect->id());
8048 }
8049
8050 sp<EffectChain> chain = effect->chain().promote();
8051 if (chain != 0) {
8052 // remove effect chain if removing last effect
8053 if (chain->removeEffect_l(effect) == 0) {
8054 removeEffectChain_l(chain);
8055 }
8056 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008057 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008058 }
8059}
8060
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008061void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008062 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008063{
8064 effectChains = mEffectChains;
8065 for (size_t i = 0; i < mEffectChains.size(); i++) {
8066 mEffectChains[i]->lock();
8067 }
8068}
8069
8070void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008071 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008072{
8073 for (size_t i = 0; i < effectChains.size(); i++) {
8074 effectChains[i]->unlock();
8075 }
8076}
8077
8078sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8079{
8080 Mutex::Autolock _l(mLock);
8081 return getEffectChain_l(sessionId);
8082}
8083
Glenn Kasten106e8a42012-08-02 13:37:12 -07008084sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008085{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008086 size_t size = mEffectChains.size();
8087 for (size_t i = 0; i < size; i++) {
8088 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008089 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008090 }
8091 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008092 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008093}
8094
Glenn Kastenf78aee72012-01-04 11:00:47 -08008095void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008096{
8097 Mutex::Autolock _l(mLock);
8098 size_t size = mEffectChains.size();
8099 for (size_t i = 0; i < size; i++) {
8100 mEffectChains[i]->setMode_l(mode);
8101 }
8102}
8103
8104void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008105 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008106 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008107
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008109 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 // delete the effect module if removing last handle on it
8111 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008112 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008113 removeEffect_l(effect);
8114 AudioSystem::unregisterEffect(effect->id());
8115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008116 }
8117}
8118
8119status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8120{
8121 int session = chain->sessionId();
8122 int16_t *buffer = mMixBuffer;
8123 bool ownsBuffer = false;
8124
Steve Block3856b092011-10-20 11:56:00 +01008125 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008126 if (session > 0) {
8127 // Only one effect chain can be present in direct output thread and it uses
8128 // the mix buffer as input
8129 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008130 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131 buffer = new int16_t[numSamples];
8132 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008133 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008134 ownsBuffer = true;
8135 }
8136
8137 // Attach all tracks with same session ID to this chain.
8138 for (size_t i = 0; i < mTracks.size(); ++i) {
8139 sp<Track> track = mTracks[i];
8140 if (session == track->sessionId()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07008141 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
8142 buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008143 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008144 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008145 }
8146 }
8147
8148 // indicate all active tracks in the chain
8149 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8150 sp<Track> track = mActiveTracks[i].promote();
Glenn Kastend65d73c2012-06-22 17:21:07 -07008151 if (track == 0) {
8152 continue;
8153 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008155 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008156 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157 }
8158 }
8159 }
8160
8161 chain->setInBuffer(buffer, ownsBuffer);
8162 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008163 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008164 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008165 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8166 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008168 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8169 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008170 // Effect chain for other sessions are inserted at beginning of effect
8171 // chains list to be processed before output mix effects. Relative order between other
8172 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 size_t size = mEffectChains.size();
8174 size_t i = 0;
8175 for (i = 0; i < size; i++) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07008176 if (mEffectChains[i]->sessionId() < session) {
8177 break;
8178 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008179 }
8180 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008181 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008182
8183 return NO_ERROR;
8184}
8185
8186size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8187{
8188 int session = chain->sessionId();
8189
Steve Block3856b092011-10-20 11:56:00 +01008190 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008191
8192 for (size_t i = 0; i < mEffectChains.size(); i++) {
8193 if (chain == mEffectChains[i]) {
8194 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008195 // detach all active tracks from the chain
8196 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8197 sp<Track> track = mActiveTracks[i].promote();
Glenn Kastend65d73c2012-06-22 17:21:07 -07008198 if (track == 0) {
8199 continue;
8200 }
Eric Laurentb469b942011-05-09 12:09:06 -07008201 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008202 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008203 chain.get(), session);
8204 chain->decActiveTrackCnt();
8205 }
8206 }
8207
Mathias Agopian65ab4712010-07-14 17:59:35 -07008208 // detach all tracks with same session ID from this chain
8209 for (size_t i = 0; i < mTracks.size(); ++i) {
8210 sp<Track> track = mTracks[i];
8211 if (session == track->sessionId()) {
8212 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008213 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214 }
8215 }
Eric Laurentde070132010-07-13 04:45:46 -07008216 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 }
8218 }
8219 return mEffectChains.size();
8220}
8221
Eric Laurentde070132010-07-13 04:45:46 -07008222status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8223 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008224{
8225 Mutex::Autolock _l(mLock);
8226 return attachAuxEffect_l(track, EffectId);
8227}
8228
Eric Laurentde070132010-07-13 04:45:46 -07008229status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8230 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008231{
8232 status_t status = NO_ERROR;
8233
8234 if (EffectId == 0) {
8235 track->setAuxBuffer(0, NULL);
8236 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008237 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8238 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239 if (effect != 0) {
8240 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8241 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8242 } else {
8243 status = INVALID_OPERATION;
8244 }
8245 } else {
8246 status = BAD_VALUE;
8247 }
8248 }
8249 return status;
8250}
8251
8252void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8253{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008254 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008255 sp<Track> track = mTracks[i];
8256 if (track->auxEffectId() == effectId) {
8257 attachAuxEffect_l(track, 0);
8258 }
8259 }
8260}
8261
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008262status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8263{
8264 // only one chain per input thread
8265 if (mEffectChains.size() != 0) {
8266 return INVALID_OPERATION;
8267 }
Steve Block3856b092011-10-20 11:56:00 +01008268 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008269
8270 chain->setInBuffer(NULL);
8271 chain->setOutBuffer(NULL);
8272
Eric Laurent59255e42011-07-27 19:49:51 -07008273 checkSuspendOnAddEffectChain_l(chain);
8274
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008275 mEffectChains.add(chain);
8276
8277 return NO_ERROR;
8278}
8279
8280size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8281{
Steve Block3856b092011-10-20 11:56:00 +01008282 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008283 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008284 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8285 chain.get(), mEffectChains.size(), this);
8286 if (mEffectChains.size() == 1) {
8287 mEffectChains.removeAt(0);
8288 }
8289 return 0;
8290}
8291
Mathias Agopian65ab4712010-07-14 17:59:35 -07008292// ----------------------------------------------------------------------------
8293// EffectModule implementation
8294// ----------------------------------------------------------------------------
8295
8296#undef LOG_TAG
8297#define LOG_TAG "AudioFlinger::EffectModule"
8298
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008299AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008300 const wp<AudioFlinger::EffectChain>& chain,
8301 effect_descriptor_t *desc,
8302 int id,
8303 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008304 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8305 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008306 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008307 // mConfig is set by configure() and not used before then
8308 mEffectInterface(NULL),
8309 mStatus(NO_INIT), mState(IDLE),
8310 // mMaxDisableWaitCnt is set by configure() and not used before then
8311 // mDisableWaitCnt is set by process() and updateState() and not used before then
8312 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313{
Steve Block3856b092011-10-20 11:56:00 +01008314 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008315 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008316
8317 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008318 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319
8320 if (mStatus != NO_ERROR) {
8321 return;
8322 }
8323 lStatus = init();
8324 if (lStatus < 0) {
8325 mStatus = lStatus;
8326 goto Error;
8327 }
8328
Steve Block3856b092011-10-20 11:56:00 +01008329 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 return;
8331Error:
8332 EffectRelease(mEffectInterface);
8333 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008334 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335}
8336
8337AudioFlinger::EffectModule::~EffectModule()
8338{
Steve Block3856b092011-10-20 11:56:00 +01008339 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008340 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008341 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8342 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8343 sp<ThreadBase> thread = mThread.promote();
8344 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008345 audio_stream_t *stream = thread->stream();
8346 if (stream != NULL) {
8347 stream->remove_audio_effect(stream, mEffectInterface);
8348 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008349 }
8350 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008351 // release effect engine
8352 EffectRelease(mEffectInterface);
8353 }
8354}
8355
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008356status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357{
8358 status_t status;
8359
8360 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008361 int priority = handle->priority();
8362 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008363 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008364 size_t i;
8365 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008366 EffectHandle *h = mHandles[i];
Glenn Kastend65d73c2012-06-22 17:21:07 -07008367 if (h == NULL || h->destroyed_l()) {
8368 continue;
8369 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008370 // first non destroyed handle is considered in control
8371 if (controlHandle == NULL)
8372 controlHandle = h;
Glenn Kastend65d73c2012-06-22 17:21:07 -07008373 if (h->priority() <= priority) {
8374 break;
8375 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376 }
8377 // if inserted in first place, move effect control from previous owner to this handle
8378 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008379 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008380 if (controlHandle != NULL) {
8381 enabled = controlHandle->enabled();
8382 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008383 }
Eric Laurent59255e42011-07-27 19:49:51 -07008384 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008385 status = NO_ERROR;
8386 } else {
8387 status = ALREADY_EXISTS;
8388 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008389 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390 mHandles.insertAt(handle, i);
8391 return status;
8392}
8393
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008394size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008395{
8396 Mutex::Autolock _l(mLock);
8397 size_t size = mHandles.size();
8398 size_t i;
8399 for (i = 0; i < size; i++) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07008400 if (mHandles[i] == handle) {
8401 break;
8402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008403 }
8404 if (i == size) {
8405 return size;
8406 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008407 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008408
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008410 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008411 if (i == 0) {
8412 EffectHandle *h = controlHandle_l();
8413 if (h != NULL) {
8414 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008415 }
8416 }
8417
Eric Laurentec437d82011-07-26 20:54:46 -07008418 // Prevent calls to process() and other functions on effect interface from now on.
8419 // The effect engine will be released by the destructor when the last strong reference on
8420 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008421 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008422 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008423 }
8424
Eric Laurente65c8912012-07-20 15:57:23 -07008425 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008426}
8427
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008428// must be called with EffectModule::mLock held
8429AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008430{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008431 // the first valid handle in the list has control over the module
8432 for (size_t i = 0; i < mHandles.size(); i++) {
8433 EffectHandle *h = mHandles[i];
8434 if (h != NULL && !h->destroyed_l()) {
8435 return h;
8436 }
8437 }
8438
8439 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008440}
8441
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008442size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008443{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008444 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008445 // keep a strong reference on this EffectModule to avoid calling the
8446 // destructor before we exit
8447 sp<EffectModule> keep(this);
8448 {
8449 sp<ThreadBase> thread = mThread.promote();
8450 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008451 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452 }
8453 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008454 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455}
8456
8457void AudioFlinger::EffectModule::updateState() {
8458 Mutex::Autolock _l(mLock);
8459
8460 switch (mState) {
8461 case RESTART:
8462 reset_l();
8463 // FALL THROUGH
8464
8465 case STARTING:
8466 // clear auxiliary effect input buffer for next accumulation
8467 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8468 memset(mConfig.inputCfg.buffer.raw,
8469 0,
8470 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8471 }
8472 start_l();
8473 mState = ACTIVE;
8474 break;
8475 case STOPPING:
8476 stop_l();
8477 mDisableWaitCnt = mMaxDisableWaitCnt;
8478 mState = STOPPED;
8479 break;
8480 case STOPPED:
8481 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8482 // turn off sequence.
8483 if (--mDisableWaitCnt == 0) {
8484 reset_l();
8485 mState = IDLE;
8486 }
8487 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008488 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008489 break;
8490 }
8491}
8492
8493void AudioFlinger::EffectModule::process()
8494{
8495 Mutex::Autolock _l(mLock);
8496
Eric Laurentec437d82011-07-26 20:54:46 -07008497 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008498 mConfig.inputCfg.buffer.raw == NULL ||
8499 mConfig.outputCfg.buffer.raw == NULL) {
8500 return;
8501 }
8502
Eric Laurent8f45bd72010-08-31 13:50:07 -07008503 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008504 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8505 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008506 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008507 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008508 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008509 }
8510
8511 // do the actual processing in the effect engine
8512 int ret = (*mEffectInterface)->process(mEffectInterface,
8513 &mConfig.inputCfg.buffer,
8514 &mConfig.outputCfg.buffer);
8515
8516 // force transition to IDLE state when engine is ready
8517 if (mState == STOPPED && ret == -ENODATA) {
8518 mDisableWaitCnt = 1;
8519 }
8520
8521 // clear auxiliary effect input buffer for next accumulation
8522 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008523 memset(mConfig.inputCfg.buffer.raw, 0,
8524 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525 }
8526 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008527 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8528 // If an insert effect is idle and input buffer is different from output buffer,
8529 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008530 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008531 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008532 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8533 int16_t *in = mConfig.inputCfg.buffer.s16;
8534 int16_t *out = mConfig.outputCfg.buffer.s16;
8535 for (size_t i = 0; i < frameCnt; i++) {
8536 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538 }
8539 }
8540}
8541
8542void AudioFlinger::EffectModule::reset_l()
8543{
8544 if (mEffectInterface == NULL) {
8545 return;
8546 }
8547 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8548}
8549
8550status_t AudioFlinger::EffectModule::configure()
8551{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008552 if (mEffectInterface == NULL) {
8553 return NO_INIT;
8554 }
8555
8556 sp<ThreadBase> thread = mThread.promote();
8557 if (thread == 0) {
8558 return DEAD_OBJECT;
8559 }
8560
8561 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008562 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008563
8564 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008565 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008566 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008567 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008568 }
Glenn Kasten254af182012-07-03 14:59:05 -07008569 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008570 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8571 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008572 mConfig.inputCfg.samplingRate = thread->sampleRate();
8573 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8574 mConfig.inputCfg.bufferProvider.cookie = NULL;
8575 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8576 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8577 mConfig.outputCfg.bufferProvider.cookie = NULL;
8578 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8579 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8580 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8581 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008582 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008583 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008584 // - in other sessions:
8585 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8586 // other effect: overwrites output buffer: input buffer == output buffer
8587 // Auxiliary effect:
8588 // accumulates in output buffer: input buffer != output buffer
8589 // Therefore: accumulate <=> input buffer != output buffer
8590 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8591 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8592 } else {
8593 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8594 }
8595 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8596 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8597 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8598 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8599
Steve Block3856b092011-10-20 11:56:00 +01008600 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008601 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8602
Mathias Agopian65ab4712010-07-14 17:59:35 -07008603 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008604 uint32_t size = sizeof(int);
8605 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008606 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008607 sizeof(effect_config_t),
8608 &mConfig,
8609 &size,
8610 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008611 if (status == 0) {
8612 status = cmdStatus;
8613 }
8614
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008615 if (status == 0 &&
8616 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8617 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8618 effect_param_t *p = (effect_param_t *)buf32;
8619
8620 p->psize = sizeof(uint32_t);
8621 p->vsize = sizeof(uint32_t);
8622 size = sizeof(int);
8623 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8624
8625 uint32_t latency = 0;
8626 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8627 if (pbt != NULL) {
8628 latency = pbt->latency_l();
8629 }
8630
8631 *((int32_t *)p->data + 1)= latency;
8632 (*mEffectInterface)->command(mEffectInterface,
8633 EFFECT_CMD_SET_PARAM,
8634 sizeof(effect_param_t) + 8,
8635 &buf32,
8636 &size,
8637 &cmdStatus);
8638 }
8639
Mathias Agopian65ab4712010-07-14 17:59:35 -07008640 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8641 (1000 * mConfig.outputCfg.buffer.frameCount);
8642
8643 return status;
8644}
8645
8646status_t AudioFlinger::EffectModule::init()
8647{
8648 Mutex::Autolock _l(mLock);
8649 if (mEffectInterface == NULL) {
8650 return NO_INIT;
8651 }
8652 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008653 uint32_t size = sizeof(status_t);
8654 status_t status = (*mEffectInterface)->command(mEffectInterface,
8655 EFFECT_CMD_INIT,
8656 0,
8657 NULL,
8658 &size,
8659 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008660 if (status == 0) {
8661 status = cmdStatus;
8662 }
8663 return status;
8664}
8665
Eric Laurentec35a142011-10-05 17:42:25 -07008666status_t AudioFlinger::EffectModule::start()
8667{
8668 Mutex::Autolock _l(mLock);
8669 return start_l();
8670}
8671
Mathias Agopian65ab4712010-07-14 17:59:35 -07008672status_t AudioFlinger::EffectModule::start_l()
8673{
8674 if (mEffectInterface == NULL) {
8675 return NO_INIT;
8676 }
8677 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008678 uint32_t size = sizeof(status_t);
8679 status_t status = (*mEffectInterface)->command(mEffectInterface,
8680 EFFECT_CMD_ENABLE,
8681 0,
8682 NULL,
8683 &size,
8684 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008685 if (status == 0) {
8686 status = cmdStatus;
8687 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008688 if (status == 0 &&
8689 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8690 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8691 sp<ThreadBase> thread = mThread.promote();
8692 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008693 audio_stream_t *stream = thread->stream();
8694 if (stream != NULL) {
8695 stream->add_audio_effect(stream, mEffectInterface);
8696 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008697 }
8698 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699 return status;
8700}
8701
Eric Laurentec437d82011-07-26 20:54:46 -07008702status_t AudioFlinger::EffectModule::stop()
8703{
8704 Mutex::Autolock _l(mLock);
8705 return stop_l();
8706}
8707
Mathias Agopian65ab4712010-07-14 17:59:35 -07008708status_t AudioFlinger::EffectModule::stop_l()
8709{
8710 if (mEffectInterface == NULL) {
8711 return NO_INIT;
8712 }
8713 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008714 uint32_t size = sizeof(status_t);
8715 status_t status = (*mEffectInterface)->command(mEffectInterface,
8716 EFFECT_CMD_DISABLE,
8717 0,
8718 NULL,
8719 &size,
8720 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008721 if (status == 0) {
8722 status = cmdStatus;
8723 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008724 if (status == 0 &&
8725 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8726 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8727 sp<ThreadBase> thread = mThread.promote();
8728 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008729 audio_stream_t *stream = thread->stream();
8730 if (stream != NULL) {
8731 stream->remove_audio_effect(stream, mEffectInterface);
8732 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008733 }
8734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735 return status;
8736}
8737
Eric Laurent25f43952010-07-28 05:40:18 -07008738status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8739 uint32_t cmdSize,
8740 void *pCmdData,
8741 uint32_t *replySize,
8742 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743{
8744 Mutex::Autolock _l(mLock);
Glenn Kasten26dd66e2012-10-18 15:51:03 -07008745 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746
Eric Laurentec437d82011-07-26 20:54:46 -07008747 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008748 return NO_INIT;
8749 }
Eric Laurent25f43952010-07-28 05:40:18 -07008750 status_t status = (*mEffectInterface)->command(mEffectInterface,
8751 cmdCode,
8752 cmdSize,
8753 pCmdData,
8754 replySize,
8755 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008757 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008758 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008759 EffectHandle *h = mHandles[i];
8760 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008761 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8762 }
8763 }
8764 }
8765 return status;
8766}
8767
8768status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8769{
8770 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008771 return setEnabled_l(enabled);
8772}
8773
8774// must be called with EffectModule::mLock held
8775status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8776{
8777
Steve Block3856b092011-10-20 11:56:00 +01008778 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008779
8780 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008781 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8782 if (enabled && status != NO_ERROR) {
8783 return status;
8784 }
8785
Mathias Agopian65ab4712010-07-14 17:59:35 -07008786 switch (mState) {
8787 // going from disabled to enabled
8788 case IDLE:
8789 mState = STARTING;
8790 break;
8791 case STOPPED:
8792 mState = RESTART;
8793 break;
8794 case STOPPING:
8795 mState = ACTIVE;
8796 break;
8797
8798 // going from enabled to disabled
8799 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008800 mState = STOPPED;
8801 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008802 case STARTING:
8803 mState = IDLE;
8804 break;
8805 case ACTIVE:
8806 mState = STOPPING;
8807 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008808 case DESTROYED:
8809 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810 }
8811 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008812 EffectHandle *h = mHandles[i];
8813 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008814 h->setEnabled(enabled);
8815 }
8816 }
8817 }
8818 return NO_ERROR;
8819}
8820
Glenn Kastenc59c0042012-02-02 14:06:11 -08008821bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008822{
8823 switch (mState) {
8824 case RESTART:
8825 case STARTING:
8826 case ACTIVE:
8827 return true;
8828 case IDLE:
8829 case STOPPING:
8830 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008831 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008832 default:
8833 return false;
8834 }
8835}
8836
Glenn Kastenc59c0042012-02-02 14:06:11 -08008837bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008838{
8839 switch (mState) {
8840 case RESTART:
8841 case ACTIVE:
8842 case STOPPING:
8843 case STOPPED:
8844 return true;
8845 case IDLE:
8846 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008847 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008848 default:
8849 return false;
8850 }
8851}
8852
Mathias Agopian65ab4712010-07-14 17:59:35 -07008853status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8854{
8855 Mutex::Autolock _l(mLock);
8856 status_t status = NO_ERROR;
8857
8858 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8859 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008860 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008861 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8862 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008863 status_t cmdStatus;
8864 uint32_t volume[2];
8865 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008866 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867 volume[0] = *left;
8868 volume[1] = *right;
8869 if (controller) {
8870 pVolume = volume;
8871 }
Eric Laurent25f43952010-07-28 05:40:18 -07008872 status = (*mEffectInterface)->command(mEffectInterface,
8873 EFFECT_CMD_SET_VOLUME,
8874 size,
8875 volume,
8876 &size,
8877 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008878 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8879 *left = volume[0];
8880 *right = volume[1];
8881 }
8882 }
8883 return status;
8884}
8885
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008886status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887{
Eric Laurentf1c04f92012-08-28 14:26:53 -07008888 if (device == AUDIO_DEVICE_NONE) {
8889 return NO_ERROR;
8890 }
8891
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892 Mutex::Autolock _l(mLock);
8893 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008894 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07008895 status_t cmdStatus;
8896 uint32_t size = sizeof(status_t);
8897 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8898 EFFECT_CMD_SET_INPUT_DEVICE;
8899 status = (*mEffectInterface)->command(mEffectInterface,
8900 cmd,
8901 sizeof(uint32_t),
8902 &device,
8903 &size,
8904 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905 }
8906 return status;
8907}
8908
Glenn Kastenf78aee72012-01-04 11:00:47 -08008909status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008910{
8911 Mutex::Autolock _l(mLock);
8912 status_t status = NO_ERROR;
8913 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008915 uint32_t size = sizeof(status_t);
8916 status = (*mEffectInterface)->command(mEffectInterface,
8917 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008918 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008919 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008920 &size,
8921 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922 if (status == NO_ERROR) {
8923 status = cmdStatus;
8924 }
8925 }
8926 return status;
8927}
8928
Eric Laurent57b2dd12012-08-31 17:44:06 -07008929status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8930{
8931 Mutex::Autolock _l(mLock);
8932 status_t status = NO_ERROR;
8933 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8934 uint32_t size = 0;
8935 status = (*mEffectInterface)->command(mEffectInterface,
8936 EFFECT_CMD_SET_AUDIO_SOURCE,
8937 sizeof(audio_source_t),
8938 &source,
8939 &size,
8940 NULL);
8941 }
8942 return status;
8943}
8944
Eric Laurent59255e42011-07-27 19:49:51 -07008945void AudioFlinger::EffectModule::setSuspended(bool suspended)
8946{
8947 Mutex::Autolock _l(mLock);
8948 mSuspended = suspended;
8949}
Glenn Kastena3a85482012-01-04 11:01:11 -08008950
8951bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008952{
8953 Mutex::Autolock _l(mLock);
8954 return mSuspended;
8955}
8956
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008957bool AudioFlinger::EffectModule::purgeHandles()
8958{
8959 bool enabled = false;
8960 Mutex::Autolock _l(mLock);
8961 for (size_t i = 0; i < mHandles.size(); i++) {
8962 EffectHandle *handle = mHandles[i];
8963 if (handle != NULL && !handle->destroyed_l()) {
8964 handle->effect().clear();
8965 if (handle->hasControl()) {
8966 enabled = handle->enabled();
8967 }
8968 }
8969 }
8970 return enabled;
8971}
8972
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008973void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974{
8975 const size_t SIZE = 256;
8976 char buffer[SIZE];
8977 String8 result;
8978
8979 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8980 result.append(buffer);
8981
8982 bool locked = tryLock(mLock);
8983 // failed to lock - AudioFlinger is probably deadlocked
8984 if (!locked) {
8985 result.append("\t\tCould not lock Fx mutex:\n");
8986 }
8987
8988 result.append("\t\tSession Status State Engine:\n");
8989 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8990 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8991 result.append(buffer);
8992
8993 result.append("\t\tDescriptor:\n");
8994 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8995 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07008996 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],
8997 mDescriptor.uuid.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07008998 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8999 result.append(buffer);
9000 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009001 mDescriptor.type.timeLow, mDescriptor.type.timeMid,
9002 mDescriptor.type.timeHiAndVersion,
9003 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],
9004 mDescriptor.type.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07009005 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9006 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009007 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008 mDescriptor.apiVersion,
9009 mDescriptor.flags);
9010 result.append(buffer);
9011 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9012 mDescriptor.name);
9013 result.append(buffer);
9014 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9015 mDescriptor.implementor);
9016 result.append(buffer);
9017
9018 result.append("\t\t- Input configuration:\n");
9019 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9020 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9021 (uint32_t)mConfig.inputCfg.buffer.raw,
9022 mConfig.inputCfg.buffer.frameCount,
9023 mConfig.inputCfg.samplingRate,
9024 mConfig.inputCfg.channels,
9025 mConfig.inputCfg.format);
9026 result.append(buffer);
9027
9028 result.append("\t\t- Output configuration:\n");
9029 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9030 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9031 (uint32_t)mConfig.outputCfg.buffer.raw,
9032 mConfig.outputCfg.buffer.frameCount,
9033 mConfig.outputCfg.samplingRate,
9034 mConfig.outputCfg.channels,
9035 mConfig.outputCfg.format);
9036 result.append(buffer);
9037
9038 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9039 result.append(buffer);
9040 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9041 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009042 EffectHandle *handle = mHandles[i];
9043 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009044 handle->dump(buffer, SIZE);
9045 result.append(buffer);
9046 }
9047 }
9048
9049 result.append("\n");
9050
9051 write(fd, result.string(), result.length());
9052
9053 if (locked) {
9054 mLock.unlock();
9055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056}
9057
9058// ----------------------------------------------------------------------------
9059// EffectHandle implementation
9060// ----------------------------------------------------------------------------
9061
9062#undef LOG_TAG
9063#define LOG_TAG "AudioFlinger::EffectHandle"
9064
9065AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9066 const sp<AudioFlinger::Client>& client,
9067 const sp<IEffectClient>& effectClient,
9068 int32_t priority)
9069 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009070 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009071 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009072{
Steve Block3856b092011-10-20 11:56:00 +01009073 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009074
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009075 if (client == 0) {
9076 return;
9077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009078 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9079 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9080 if (mCblkMemory != 0) {
9081 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9082
Glenn Kastena0d68332012-01-27 16:47:15 -08009083 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009084 new(mCblk) effect_param_cblk_t();
9085 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009087 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009088 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE +
9089 sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009090 return;
9091 }
9092}
9093
9094AudioFlinger::EffectHandle::~EffectHandle()
9095{
Steve Block3856b092011-10-20 11:56:00 +01009096 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009097
9098 if (mEffect == 0) {
9099 mDestroyed = true;
9100 return;
9101 }
9102 mEffect->lock();
9103 mDestroyed = true;
9104 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009105 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009106}
9107
9108status_t AudioFlinger::EffectHandle::enable()
9109{
Steve Block3856b092011-10-20 11:56:00 +01009110 ALOGV("enable %p", this);
Glenn Kastend65d73c2012-06-22 17:21:07 -07009111 if (!mHasControl) {
9112 return INVALID_OPERATION;
9113 }
9114 if (mEffect == 0) {
9115 return DEAD_OBJECT;
9116 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009117
Eric Laurentdb7c0792011-08-10 10:37:50 -07009118 if (mEnabled) {
9119 return NO_ERROR;
9120 }
9121
Eric Laurent59255e42011-07-27 19:49:51 -07009122 mEnabled = true;
9123
9124 sp<ThreadBase> thread = mEffect->thread().promote();
9125 if (thread != 0) {
9126 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9127 }
9128
9129 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9130 if (mEffect->suspended()) {
9131 return NO_ERROR;
9132 }
9133
Eric Laurentdb7c0792011-08-10 10:37:50 -07009134 status_t status = mEffect->setEnabled(true);
9135 if (status != NO_ERROR) {
9136 if (thread != 0) {
9137 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9138 }
9139 mEnabled = false;
9140 }
9141 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009142}
9143
9144status_t AudioFlinger::EffectHandle::disable()
9145{
Steve Block3856b092011-10-20 11:56:00 +01009146 ALOGV("disable %p", this);
Glenn Kastend65d73c2012-06-22 17:21:07 -07009147 if (!mHasControl) {
9148 return INVALID_OPERATION;
9149 }
9150 if (mEffect == 0) {
9151 return DEAD_OBJECT;
9152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009153
Eric Laurentdb7c0792011-08-10 10:37:50 -07009154 if (!mEnabled) {
9155 return NO_ERROR;
9156 }
Eric Laurent59255e42011-07-27 19:49:51 -07009157 mEnabled = false;
9158
9159 if (mEffect->suspended()) {
9160 return NO_ERROR;
9161 }
9162
9163 status_t status = mEffect->setEnabled(false);
9164
9165 sp<ThreadBase> thread = mEffect->thread().promote();
9166 if (thread != 0) {
9167 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9168 }
9169
9170 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009171}
9172
9173void AudioFlinger::EffectHandle::disconnect()
9174{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009175 disconnect(true);
9176}
9177
Glenn Kasten58123c32012-02-03 10:32:24 -08009178void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009179{
Glenn Kasten58123c32012-02-03 10:32:24 -08009180 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009181 if (mEffect == 0) {
9182 return;
9183 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009184 // restore suspended effects if the disconnected handle was enabled and the last one.
9185 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009186 sp<ThreadBase> thread = mEffect->thread().promote();
9187 if (thread != 0) {
9188 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9189 }
Eric Laurent59255e42011-07-27 19:49:51 -07009190 }
9191
Mathias Agopian65ab4712010-07-14 17:59:35 -07009192 // release sp on module => module destructor can be called now
9193 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009194 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009195 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009196 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009197 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9198 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009199 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009200 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009201 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9202 mClient.clear();
9203 }
9204}
9205
Eric Laurent25f43952010-07-28 05:40:18 -07009206status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9207 uint32_t cmdSize,
9208 void *pCmdData,
9209 uint32_t *replySize,
9210 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009211{
Glenn Kasten26dd66e2012-10-18 15:51:03 -07009212 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
9213 cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009214
9215 // only get parameter command is permitted for applications not controlling the effect
9216 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9217 return INVALID_OPERATION;
9218 }
Glenn Kastend65d73c2012-06-22 17:21:07 -07009219 if (mEffect == 0) {
9220 return DEAD_OBJECT;
9221 }
9222 if (mClient == 0) {
9223 return INVALID_OPERATION;
9224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009225
9226 // handle commands that are not forwarded transparently to effect engine
9227 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009228 // No need to trylock() here as this function is executed in the binder thread serving a
9229 // particular client process: no risk to block the whole media server process or mixer
9230 // threads if we are stuck here
Mathias Agopian65ab4712010-07-14 17:59:35 -07009231 Mutex::Autolock _l(mCblk->lock);
9232 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9233 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9234 mCblk->serverIndex = 0;
9235 mCblk->clientIndex = 0;
9236 return BAD_VALUE;
9237 }
9238 status_t status = NO_ERROR;
9239 while (mCblk->serverIndex < mCblk->clientIndex) {
9240 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009241 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009242 int *p = (int *)(mBuffer + mCblk->serverIndex);
9243 int size = *p++;
9244 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009245 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009246 break;
9247 }
9248 effect_param_t *param = (effect_param_t *)p;
9249 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009250 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009251 mCblk->serverIndex += size;
9252 continue;
9253 }
Eric Laurent25f43952010-07-28 05:40:18 -07009254 uint32_t psize = sizeof(effect_param_t) +
9255 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9256 param->vsize;
9257 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9258 psize,
9259 p,
9260 &rsize,
9261 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009262 // stop at first error encountered
9263 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009264 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009265 *(int *)pReplyData = reply;
9266 break;
9267 } else if (reply != NO_ERROR) {
9268 *(int *)pReplyData = reply;
9269 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009270 }
9271 mCblk->serverIndex += size;
9272 }
9273 mCblk->serverIndex = 0;
9274 mCblk->clientIndex = 0;
9275 return status;
9276 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009277 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009278 return enable();
9279 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009280 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009281 return disable();
9282 }
9283
9284 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9285}
9286
Eric Laurent59255e42011-07-27 19:49:51 -07009287void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009288{
Steve Block3856b092011-10-20 11:56:00 +01009289 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009290
9291 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009292 mEnabled = enabled;
9293
Mathias Agopian65ab4712010-07-14 17:59:35 -07009294 if (signal && mEffectClient != 0) {
9295 mEffectClient->controlStatusChanged(hasControl);
9296 }
9297}
9298
Eric Laurent25f43952010-07-28 05:40:18 -07009299void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9300 uint32_t cmdSize,
9301 void *pCmdData,
9302 uint32_t replySize,
9303 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009304{
9305 if (mEffectClient != 0) {
9306 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9307 }
9308}
9309
9310
9311
9312void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9313{
9314 if (mEffectClient != 0) {
9315 mEffectClient->enableStatusChanged(enabled);
9316 }
9317}
9318
9319status_t AudioFlinger::EffectHandle::onTransact(
9320 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9321{
9322 return BnEffect::onTransact(code, data, reply, flags);
9323}
9324
9325
9326void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9327{
Glenn Kastena0d68332012-01-27 16:47:15 -08009328 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009329
9330 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009331 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009332 mPriority,
9333 mHasControl,
9334 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009335 mCblk ? mCblk->clientIndex : 0,
9336 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009337 );
9338
9339 if (locked) {
9340 mCblk->lock.unlock();
9341 }
9342}
9343
9344#undef LOG_TAG
9345#define LOG_TAG "AudioFlinger::EffectChain"
9346
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009347AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009348 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009349 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009350 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9351 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009352{
Dima Zavinfce7a472011-04-19 22:30:36 -07009353 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009354 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009355 return;
9356 }
9357 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9358 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009359}
9360
9361AudioFlinger::EffectChain::~EffectChain()
9362{
9363 if (mOwnInBuffer) {
9364 delete mInBuffer;
9365 }
9366
9367}
9368
Eric Laurent59255e42011-07-27 19:49:51 -07009369// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009370sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
9371 effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009372{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009373 size_t size = mEffects.size();
9374
9375 for (size_t i = 0; i < size; i++) {
9376 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009377 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009378 }
9379 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009380 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009381}
9382
Eric Laurent59255e42011-07-27 19:49:51 -07009383// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009384sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009385{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009386 size_t size = mEffects.size();
9387
9388 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009389 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9390 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009391 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009392 }
9393 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009394 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009395}
9396
Eric Laurent59255e42011-07-27 19:49:51 -07009397// getEffectFromType_l() must be called with ThreadBase::mLock held
9398sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9399 const effect_uuid_t *type)
9400{
Eric Laurent59255e42011-07-27 19:49:51 -07009401 size_t size = mEffects.size();
9402
9403 for (size_t i = 0; i < size; i++) {
9404 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009405 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009406 }
9407 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009408 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009409}
9410
Eric Laurent91b14c42012-05-30 12:30:29 -07009411void AudioFlinger::EffectChain::clearInputBuffer()
9412{
9413 Mutex::Autolock _l(mLock);
9414 sp<ThreadBase> thread = mThread.promote();
9415 if (thread == 0) {
9416 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9417 return;
9418 }
9419 clearInputBuffer_l(thread);
9420}
9421
9422// Must be called with EffectChain::mLock locked
9423void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9424{
9425 size_t numSamples = thread->frameCount() * thread->channelCount();
9426 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9427
9428}
9429
Mathias Agopian65ab4712010-07-14 17:59:35 -07009430// Must be called with EffectChain::mLock locked
9431void AudioFlinger::EffectChain::process_l()
9432{
Eric Laurentdac69112010-09-28 14:09:57 -07009433 sp<ThreadBase> thread = mThread.promote();
9434 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009435 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009436 return;
9437 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009438 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9439 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009440 // always process effects unless no more tracks are on the session and the effect tail
9441 // has been rendered
9442 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009443 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009444 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009445
Eric Laurent544fe9b2011-11-11 15:42:52 -08009446 if (!tracksOnSession && mTailBufferCount == 0) {
9447 doProcess = false;
9448 }
9449
9450 if (activeTrackCnt() == 0) {
9451 // if no track is active and the effect tail has not been rendered,
9452 // the input buffer must be cleared here as the mixer process will not do it
9453 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009454 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009455 if (mTailBufferCount > 0) {
9456 mTailBufferCount--;
9457 }
9458 }
9459 }
Eric Laurentdac69112010-09-28 14:09:57 -07009460 }
9461
Mathias Agopian65ab4712010-07-14 17:59:35 -07009462 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009463 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009464 for (size_t i = 0; i < size; i++) {
9465 mEffects[i]->process();
9466 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009467 }
9468 for (size_t i = 0; i < size; i++) {
9469 mEffects[i]->updateState();
9470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009471}
9472
Eric Laurentcab11242010-07-15 12:50:15 -07009473// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009474status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009475{
9476 effect_descriptor_t desc = effect->desc();
9477 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9478
9479 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009480 effect->setChain(this);
9481 sp<ThreadBase> thread = mThread.promote();
9482 if (thread == 0) {
9483 return NO_INIT;
9484 }
9485 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009486
9487 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9488 // Auxiliary effects are inserted at the beginning of mEffects vector as
9489 // they are processed first and accumulated in chain input buffer
9490 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009491
Mathias Agopian65ab4712010-07-14 17:59:35 -07009492 // the input buffer for auxiliary effect contains mono samples in
9493 // 32 bit format. This is to avoid saturation in AudoMixer
9494 // accumulation stage. Saturation is done in EffectModule::process() before
9495 // calling the process in effect engine
9496 size_t numSamples = thread->frameCount();
9497 int32_t *buffer = new int32_t[numSamples];
9498 memset(buffer, 0, numSamples * sizeof(int32_t));
9499 effect->setInBuffer((int16_t *)buffer);
9500 // auxiliary effects output samples to chain input buffer for further processing
9501 // by insert effects
9502 effect->setOutBuffer(mInBuffer);
9503 } else {
9504 // Insert effects are inserted at the end of mEffects vector as they are processed
9505 // after track and auxiliary effects.
9506 // Insert effect order as a function of indicated preference:
9507 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9508 // another effect is present
9509 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9510 // last effect claiming first position
9511 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9512 // first effect claiming last position
9513 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9514 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9515 // already present
9516
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009517 size_t size = mEffects.size();
9518 size_t idx_insert = size;
9519 ssize_t idx_insert_first = -1;
9520 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009521
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009522 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009523 effect_descriptor_t d = mEffects[i]->desc();
9524 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9525 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9526 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9527 // check invalid effect chaining combinations
9528 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9529 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009530 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
9531 desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009532 return INVALID_OPERATION;
9533 }
9534 // remember position of first insert effect and by default
9535 // select this as insert position for new effect
9536 if (idx_insert == size) {
9537 idx_insert = i;
9538 }
9539 // remember position of last insert effect claiming
9540 // first position
9541 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9542 idx_insert_first = i;
9543 }
9544 // remember position of first insert effect claiming
9545 // last position
9546 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9547 idx_insert_last == -1) {
9548 idx_insert_last = i;
9549 }
9550 }
9551 }
9552
9553 // modify idx_insert from first position if needed
9554 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9555 if (idx_insert_last != -1) {
9556 idx_insert = idx_insert_last;
9557 } else {
9558 idx_insert = size;
9559 }
9560 } else {
9561 if (idx_insert_first != -1) {
9562 idx_insert = idx_insert_first + 1;
9563 }
9564 }
9565
9566 // always read samples from chain input buffer
9567 effect->setInBuffer(mInBuffer);
9568
9569 // if last effect in the chain, output samples to chain
9570 // output buffer, otherwise to chain input buffer
9571 if (idx_insert == size) {
9572 if (idx_insert != 0) {
9573 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9574 mEffects[idx_insert-1]->configure();
9575 }
9576 effect->setOutBuffer(mOutBuffer);
9577 } else {
9578 effect->setOutBuffer(mInBuffer);
9579 }
9580 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009581
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009582 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this,
9583 idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009584 }
9585 effect->configure();
9586 return NO_ERROR;
9587}
9588
Eric Laurentcab11242010-07-15 12:50:15 -07009589// removeEffect_l() must be called with PlaybackThread::mLock held
9590size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009591{
9592 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009593 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009594 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9595
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009596 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009597 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009598 // calling stop here will remove pre-processing effect from the audio HAL.
9599 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9600 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009601 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9602 mEffects[i]->state() == EffectModule::STOPPING) {
9603 mEffects[i]->stop();
9604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009605 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9606 delete[] effect->inBuffer();
9607 } else {
9608 if (i == size - 1 && i != 0) {
9609 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9610 mEffects[i - 1]->configure();
9611 }
9612 }
9613 mEffects.removeAt(i);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009614 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(),
9615 this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009616 break;
9617 }
9618 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009619
9620 return mEffects.size();
9621}
9622
Eric Laurentcab11242010-07-15 12:50:15 -07009623// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009624void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009625{
9626 size_t size = mEffects.size();
9627 for (size_t i = 0; i < size; i++) {
9628 mEffects[i]->setDevice(device);
9629 }
9630}
9631
Eric Laurentcab11242010-07-15 12:50:15 -07009632// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009633void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009634{
9635 size_t size = mEffects.size();
9636 for (size_t i = 0; i < size; i++) {
9637 mEffects[i]->setMode(mode);
9638 }
9639}
9640
Eric Laurent57b2dd12012-08-31 17:44:06 -07009641// setAudioSource_l() must be called with PlaybackThread::mLock held
9642void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9643{
9644 size_t size = mEffects.size();
9645 for (size_t i = 0; i < size; i++) {
9646 mEffects[i]->setAudioSource(source);
9647 }
9648}
9649
Eric Laurentcab11242010-07-15 12:50:15 -07009650// setVolume_l() must be called with PlaybackThread::mLock held
9651bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009652{
9653 uint32_t newLeft = *left;
9654 uint32_t newRight = *right;
9655 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009656 int ctrlIdx = -1;
9657 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009658
Eric Laurentcab11242010-07-15 12:50:15 -07009659 // first update volume controller
9660 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009661 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009662 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9663 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009664 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009665 break;
9666 }
9667 }
9668
9669 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009670 if (hasControl) {
9671 *left = mNewLeftVolume;
9672 *right = mNewRightVolume;
9673 }
9674 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009675 }
9676
9677 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009678 mLeftVolume = newLeft;
9679 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009680
9681 // second get volume update from volume controller
9682 if (ctrlIdx >= 0) {
9683 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009684 mNewLeftVolume = newLeft;
9685 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009686 }
9687 // then indicate volume to all other effects in chain.
9688 // Pass altered volume to effects before volume controller
9689 // and requested volume to effects after controller
9690 uint32_t lVol = newLeft;
9691 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009692
Mathias Agopian65ab4712010-07-14 17:59:35 -07009693 for (size_t i = 0; i < size; i++) {
Glenn Kastend65d73c2012-06-22 17:21:07 -07009694 if ((int)i == ctrlIdx) {
9695 continue;
9696 }
Eric Laurentcab11242010-07-15 12:50:15 -07009697 // this also works for ctrlIdx == -1 when there is no volume controller
9698 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009699 lVol = *left;
9700 rVol = *right;
9701 }
9702 mEffects[i]->setVolume(&lVol, &rVol, false);
9703 }
9704 *left = newLeft;
9705 *right = newRight;
9706
9707 return hasControl;
9708}
9709
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009710void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009711{
9712 const size_t SIZE = 256;
9713 char buffer[SIZE];
9714 String8 result;
9715
9716 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9717 result.append(buffer);
9718
9719 bool locked = tryLock(mLock);
9720 // failed to lock - AudioFlinger is probably deadlocked
9721 if (!locked) {
9722 result.append("\tCould not lock mutex:\n");
9723 }
9724
Eric Laurentcab11242010-07-15 12:50:15 -07009725 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9726 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009727 mEffects.size(),
9728 (uint32_t)mInBuffer,
9729 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009730 mActiveTrackCnt);
9731 result.append(buffer);
9732 write(fd, result.string(), result.size());
9733
9734 for (size_t i = 0; i < mEffects.size(); ++i) {
9735 sp<EffectModule> effect = mEffects[i];
9736 if (effect != 0) {
9737 effect->dump(fd, args);
9738 }
9739 }
9740
9741 if (locked) {
9742 mLock.unlock();
9743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009744}
9745
Eric Laurent59255e42011-07-27 19:49:51 -07009746// must be called with ThreadBase::mLock held
9747void AudioFlinger::EffectChain::setEffectSuspended_l(
9748 const effect_uuid_t *type, bool suspend)
9749{
9750 sp<SuspendedEffectDesc> desc;
9751 // use effect type UUID timelow as key as there is no real risk of identical
9752 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009753 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009754 if (suspend) {
9755 if (index >= 0) {
9756 desc = mSuspendedEffects.valueAt(index);
9757 } else {
9758 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009759 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009760 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009761 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009762 }
9763 if (desc->mRefCount++ == 0) {
9764 sp<EffectModule> effect = getEffectIfEnabled(type);
9765 if (effect != 0) {
9766 desc->mEffect = effect;
9767 effect->setSuspended(true);
9768 effect->setEnabled(false);
9769 }
9770 }
9771 } else {
9772 if (index < 0) {
9773 return;
9774 }
9775 desc = mSuspendedEffects.valueAt(index);
9776 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009777 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009778 desc->mRefCount = 1;
9779 }
9780 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009781 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009782 if (desc->mEffect != 0) {
9783 sp<EffectModule> effect = desc->mEffect.promote();
9784 if (effect != 0) {
9785 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009786 effect->lock();
9787 EffectHandle *handle = effect->controlHandle_l();
9788 if (handle != NULL && !handle->destroyed_l()) {
9789 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009790 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009791 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009792 }
9793 desc->mEffect.clear();
9794 }
9795 mSuspendedEffects.removeItemsAt(index);
9796 }
9797 }
9798}
9799
9800// must be called with ThreadBase::mLock held
9801void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9802{
9803 sp<SuspendedEffectDesc> desc;
9804
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009805 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009806 if (suspend) {
9807 if (index >= 0) {
9808 desc = mSuspendedEffects.valueAt(index);
9809 } else {
9810 desc = new SuspendedEffectDesc();
9811 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009812 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009813 }
9814 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009815 Vector< sp<EffectModule> > effects;
9816 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009817 for (size_t i = 0; i < effects.size(); i++) {
9818 setEffectSuspended_l(&effects[i]->desc().type, true);
9819 }
9820 }
9821 } else {
9822 if (index < 0) {
9823 return;
9824 }
9825 desc = mSuspendedEffects.valueAt(index);
9826 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009827 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009828 desc->mRefCount = 1;
9829 }
9830 if (--desc->mRefCount == 0) {
9831 Vector<const effect_uuid_t *> types;
9832 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9833 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9834 continue;
9835 }
9836 types.add(&mSuspendedEffects.valueAt(i)->mType);
9837 }
9838 for (size_t i = 0; i < types.size(); i++) {
9839 setEffectSuspended_l(types[i], false);
9840 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009841 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
9842 mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009843 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9844 }
9845 }
9846}
9847
Eric Laurent6bffdb82011-09-23 08:40:41 -07009848
9849// The volume effect is used for automated tests only
9850#ifndef OPENSL_ES_H_
9851static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9852 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9853const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9854#endif //OPENSL_ES_H_
9855
Eric Laurentdb7c0792011-08-10 10:37:50 -07009856bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9857{
9858 // auxiliary effects and visualizer are never suspended on output mix
9859 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9860 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009861 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9862 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009863 return false;
9864 }
9865 return true;
9866}
9867
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009868void AudioFlinger::EffectChain::getSuspendEligibleEffects(
9869 Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009870{
Glenn Kastend0539712012-01-30 12:56:03 -08009871 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009872 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009873 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9874 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009875 }
Eric Laurent59255e42011-07-27 19:49:51 -07009876 }
Eric Laurent59255e42011-07-27 19:49:51 -07009877}
9878
9879sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9880 const effect_uuid_t *type)
9881{
Glenn Kasten090f0192012-01-30 13:00:02 -08009882 sp<EffectModule> effect = getEffectFromType_l(type);
9883 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009884}
9885
9886void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9887 bool enabled)
9888{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009889 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009890 if (enabled) {
9891 if (index < 0) {
9892 // if the effect is not suspend check if all effects are suspended
9893 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9894 if (index < 0) {
9895 return;
9896 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009897 if (!isEffectEligibleForSuspend(effect->desc())) {
9898 return;
9899 }
Eric Laurent59255e42011-07-27 19:49:51 -07009900 setEffectSuspended_l(&effect->desc().type, enabled);
9901 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009902 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009903 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009904 return;
9905 }
Eric Laurent59255e42011-07-27 19:49:51 -07009906 }
Steve Block3856b092011-10-20 11:56:00 +01009907 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009908 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009909 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9910 // if effect is requested to suspended but was not yet enabled, supend it now.
9911 if (desc->mEffect == 0) {
9912 desc->mEffect = effect;
9913 effect->setEnabled(false);
9914 effect->setSuspended(true);
9915 }
9916 } else {
9917 if (index < 0) {
9918 return;
9919 }
Steve Block3856b092011-10-20 11:56:00 +01009920 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009921 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009922 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9923 desc->mEffect.clear();
9924 effect->setSuspended(false);
9925 }
9926}
9927
Mathias Agopian65ab4712010-07-14 17:59:35 -07009928#undef LOG_TAG
9929#define LOG_TAG "AudioFlinger"
9930
9931// ----------------------------------------------------------------------------
9932
9933status_t AudioFlinger::onTransact(
9934 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9935{
9936 return BnAudioFlinger::onTransact(code, data, reply, flags);
9937}
9938
Mathias Agopian65ab4712010-07-14 17:59:35 -07009939}; // namespace android