blob: 57d708910ada6762ea807e35c2d7f03609a0bdb0 [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
79#include "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
Glenn Kastenfbae5da2012-05-21 09:17:20 -070082#include "Pipe.h"
83#include "PipeReader.h"
Glenn Kasten58912562012-04-03 10:45:00 -070084#include "SourceAudioBufferProvider.h"
85
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#ifdef HAVE_REQUEST_PRIORITY
87#include "SchedulingPolicyService.h"
88#endif
89
Glenn Kasten58912562012-04-03 10:45:00 -070090#ifdef SOAKER
91#include "Soaker.h"
92#endif
93
Mathias Agopian65ab4712010-07-14 17:59:35 -070094// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
John Grossman1c345192012-03-27 14:00:17 -070096// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
Eric Laurentde070132010-07-13 04:45:46 -0700108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800111static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
112static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800115static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116
117// retry counts for buffer fill timeout
118// 50 * ~20msecs = 1 second
119static const int8_t kMaxTrackRetries = 50;
120static const int8_t kMaxTrackStartupRetries = 50;
121// allow less retry attempts on direct output thread.
122// direct outputs can be a scarce resource in audio hardware and should
123// be released as quickly as possible.
124static const int8_t kMaxTrackRetriesDirect = 2;
125
126static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800127static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// don't warn about blocked writes or record buffer overflows more often than this
130static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700132// RecordThread loop sleep time upon application overrun or audio HAL read error
133static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Glenn Kasten7dede872011-12-13 11:04:14 -0800135// maximum time to wait for setParameters to complete
136static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700137
Eric Laurent7cafbb32011-11-22 18:50:29 -0800138// minimum sleep time for the mixer thread loop when tracks are active but in underrun
139static const uint32_t kMinThreadSleepTimeUs = 5000;
140// maximum divider applied to the active sleep time in the mixer thread loop
141static const uint32_t kMaxThreadSleepTimeShift = 2;
142
Glenn Kasten58912562012-04-03 10:45:00 -0700143// minimum normal mix buffer size, expressed in milliseconds rather than frames
144static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700145// maximum normal mix buffer size
146static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700147
John Grossman4ff14ba2012-02-08 16:37:41 -0800148nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800149
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700150// Whether to use fast mixer
151static const enum {
152 FastMixer_Never, // never initialize or use: for debugging only
153 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
154 // normal mixer multiplier is 1
155 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700156 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700157 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700158 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700159 // FIXME for FastMixer_Dynamic:
160 // Supporting this option will require fixing HALs that can't handle large writes.
161 // For example, one HAL implementation returns an error from a large write,
162 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
163 // We could either fix the HAL implementations, or provide a wrapper that breaks
164 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
165} kUseFastMixer = FastMixer_Static;
166
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167// ----------------------------------------------------------------------------
168
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700169#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800170// To collect the amplifier usage
171static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800172 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
173 if (service == NULL) {
174 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800175 return;
176 }
177
178 service->addBatteryData(params);
179}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700180#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800181
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700182static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700183{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700184 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 int rc;
186
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700187 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
188 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
189 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
190 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700191 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192 }
193 rc = audio_hw_device_open(mod, dev);
194 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
195 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
196 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700197 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700198 }
199 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
200 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
201 rc = BAD_VALUE;
202 goto out;
203 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 return 0;
205
206out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 *dev = NULL;
208 return rc;
209}
210
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211// ----------------------------------------------------------------------------
212
213AudioFlinger::AudioFlinger()
214 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800215 mPrimaryHardwareDev(NULL),
216 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
217 mMasterVolume(1.0f),
218 mMasterVolumeSupportLvl(MVS_NONE),
219 mMasterMute(false),
220 mNextUniqueId(1),
221 mMode(AUDIO_MODE_INVALID),
222 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700224}
225
226void AudioFlinger::onFirstRef()
227{
Dima Zavin799a70e2011-04-18 16:57:27 -0700228 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700229
Eric Laurent93575202011-01-18 18:39:02 -0800230 Mutex::Autolock _l(mLock);
231
Dima Zavin799a70e2011-04-18 16:57:27 -0700232 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800233 char val_str[PROPERTY_VALUE_MAX] = { 0 };
234 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
235 uint32_t int_val;
236 if (1 == sscanf(val_str, "%u", &int_val)) {
237 mStandbyTimeInNsecs = milliseconds(int_val);
238 ALOGI("Using %u mSec as standby time.", int_val);
239 } else {
240 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
241 ALOGI("Using default %u mSec as standby time.",
242 (uint32_t)(mStandbyTimeInNsecs / 1000000));
243 }
244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245
Eric Laurenta4c5a552012-03-29 10:12:40 -0700246 mMode = AUDIO_MODE_NORMAL;
247 mMasterVolumeSW = 1.0;
248 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800249 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250}
251
252AudioFlinger::~AudioFlinger()
253{
Dima Zavin799a70e2011-04-18 16:57:27 -0700254
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255 while (!mRecordThreads.isEmpty()) {
256 // closeInput() will remove first entry from mRecordThreads
257 closeInput(mRecordThreads.keyAt(0));
258 }
259 while (!mPlaybackThreads.isEmpty()) {
260 // closeOutput() will remove first entry from mPlaybackThreads
261 closeOutput(mPlaybackThreads.keyAt(0));
262 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700263
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800264 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
265 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700266 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
267 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700268 }
269}
270
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271static const char * const audio_interfaces[] = {
272 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
273 AUDIO_HARDWARE_MODULE_ID_A2DP,
274 AUDIO_HARDWARE_MODULE_ID_USB,
275};
276#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
277
278audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700279{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700280 // if module is 0, the request comes from an old policy manager and we should load
281 // well known modules
282 if (module == 0) {
283 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
284 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
285 loadHwModule_l(audio_interfaces[i]);
286 }
287 } else {
288 // check a match for the requested module handle
289 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
290 if (audioHwdevice != NULL) {
291 return audioHwdevice->hwDevice();
292 }
293 }
294 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700296 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700297 if ((dev->get_supported_devices(dev) & devices) == devices)
298 return dev;
299 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700300
Dima Zavin799a70e2011-04-18 16:57:27 -0700301 return NULL;
302}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303
304status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
305{
306 const size_t SIZE = 256;
307 char buffer[SIZE];
308 String8 result;
309
310 result.append("Clients:\n");
311 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800312 sp<Client> client = mClients.valueAt(i).promote();
313 if (client != 0) {
314 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
315 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700316 }
317 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700318
319 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800320 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
322 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800323 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700324 result.append(buffer);
325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326 write(fd, result.string(), result.size());
327 return NO_ERROR;
328}
329
330
331status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
332{
333 const size_t SIZE = 256;
334 char buffer[SIZE];
335 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800336 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337
John Grossman4ff14ba2012-02-08 16:37:41 -0800338 snprintf(buffer, SIZE, "Hardware status: %d\n"
339 "Standby Time mSec: %u\n",
340 hardwareStatus,
341 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342 result.append(buffer);
343 write(fd, result.string(), result.size());
344 return NO_ERROR;
345}
346
347status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
348{
349 const size_t SIZE = 256;
350 char buffer[SIZE];
351 String8 result;
352 snprintf(buffer, SIZE, "Permission Denial: "
353 "can't dump AudioFlinger from pid=%d, uid=%d\n",
354 IPCThreadState::self()->getCallingPid(),
355 IPCThreadState::self()->getCallingUid());
356 result.append(buffer);
357 write(fd, result.string(), result.size());
358 return NO_ERROR;
359}
360
361static bool tryLock(Mutex& mutex)
362{
363 bool locked = false;
364 for (int i = 0; i < kDumpLockRetries; ++i) {
365 if (mutex.tryLock() == NO_ERROR) {
366 locked = true;
367 break;
368 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800369 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 }
371 return locked;
372}
373
374status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
375{
Glenn Kasten44deb052012-02-05 18:09:08 -0800376 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377 dumpPermissionDenial(fd, args);
378 } else {
379 // get state of hardware lock
380 bool hardwareLocked = tryLock(mHardwareLock);
381 if (!hardwareLocked) {
382 String8 result(kHardwareLockedString);
383 write(fd, result.string(), result.size());
384 } else {
385 mHardwareLock.unlock();
386 }
387
388 bool locked = tryLock(mLock);
389
390 // failed to lock - AudioFlinger is probably deadlocked
391 if (!locked) {
392 String8 result(kDeadlockedString);
393 write(fd, result.string(), result.size());
394 }
395
396 dumpClients(fd, args);
397 dumpInternals(fd, args);
398
399 // dump playback threads
400 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
401 mPlaybackThreads.valueAt(i)->dump(fd, args);
402 }
403
404 // dump record threads
405 for (size_t i = 0; i < mRecordThreads.size(); i++) {
406 mRecordThreads.valueAt(i)->dump(fd, args);
407 }
408
Dima Zavin799a70e2011-04-18 16:57:27 -0700409 // dump all hardware devs
410 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700411 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700412 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700413 }
414 if (locked) mLock.unlock();
415 }
416 return NO_ERROR;
417}
418
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800419sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
420{
421 // If pid is already in the mClients wp<> map, then use that entry
422 // (for which promote() is always != 0), otherwise create a new entry and Client.
423 sp<Client> client = mClients.valueFor(pid).promote();
424 if (client == 0) {
425 client = new Client(this, pid);
426 mClients.add(pid, client);
427 }
428
429 return client;
430}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431
432// IAudioFlinger interface
433
434
435sp<IAudioTrack> AudioFlinger::createTrack(
436 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800437 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800439 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700440 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800442 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800444 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800445 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 int *sessionId,
447 status_t *status)
448{
449 sp<PlaybackThread::Track> track;
450 sp<TrackHandle> trackHandle;
451 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 status_t lStatus;
453 int lSessionId;
454
Glenn Kasten263709e2012-01-06 08:40:01 -0800455 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
456 // but if someone uses binder directly they could bypass that and cause us to crash
457 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000458 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459 lStatus = BAD_VALUE;
460 goto Exit;
461 }
462
463 {
464 Mutex::Autolock _l(mLock);
465 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700466 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000468 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 lStatus = BAD_VALUE;
470 goto Exit;
471 }
472
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800473 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474
Steve Block3856b092011-10-20 11:56:00 +0100475 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700476 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700477 // check if an effect chain with the same session ID is present on another
478 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
481 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700483 if (sessions & PlaybackThread::EFFECT_SESSION) {
484 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700485 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700486 }
Eric Laurentde070132010-07-13 04:45:46 -0700487 }
488 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 lSessionId = *sessionId;
490 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700491 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700492 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 if (sessionId != NULL) {
494 *sessionId = lSessionId;
495 }
496 }
Steve Block3856b092011-10-20 11:56:00 +0100497 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498
499 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800500 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700501
502 // move effect chain to this output thread if an effect on same session was waiting
503 // for a track to be created
504 if (lStatus == NO_ERROR && effectThread != NULL) {
505 Mutex::Autolock _dl(thread->mLock);
506 Mutex::Autolock _sl(effectThread->mLock);
507 moveEffectChain_l(lSessionId, effectThread, thread, true);
508 }
Eric Laurenta011e352012-03-29 15:51:43 -0700509
510 // Look for sync events awaiting for a session to be used.
511 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
512 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
513 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700514 if (lStatus == NO_ERROR) {
515 track->setSyncEvent(mPendingSyncEvents[i]);
516 } else {
517 mPendingSyncEvents[i]->cancel();
518 }
Eric Laurenta011e352012-03-29 15:51:43 -0700519 mPendingSyncEvents.removeAt(i);
520 i--;
521 }
522 }
523 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524 }
525 if (lStatus == NO_ERROR) {
526 trackHandle = new TrackHandle(track);
527 } else {
528 // remove local strong reference to Client before deleting the Track so that the Client
529 // destructor is called by the TrackBase destructor with mLock held
530 client.clear();
531 track.clear();
532 }
533
534Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700535 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536 *status = lStatus;
537 }
538 return trackHandle;
539}
540
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800541uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542{
543 Mutex::Autolock _l(mLock);
544 PlaybackThread *thread = checkPlaybackThread_l(output);
545 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000546 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547 return 0;
548 }
549 return thread->sampleRate();
550}
551
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800552int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553{
554 Mutex::Autolock _l(mLock);
555 PlaybackThread *thread = checkPlaybackThread_l(output);
556 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000557 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 return 0;
559 }
560 return thread->channelCount();
561}
562
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800563audio_format_t AudioFlinger::format(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("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800569 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570 }
571 return thread->format();
572}
573
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800574size_t AudioFlinger::frameCount(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("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 return 0;
581 }
Glenn Kasten58912562012-04-03 10:45:00 -0700582 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
583 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 return thread->frameCount();
585}
586
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800587uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588{
589 Mutex::Autolock _l(mLock);
590 PlaybackThread *thread = checkPlaybackThread_l(output);
591 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000592 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593 return 0;
594 }
595 return thread->latency();
596}
597
598status_t AudioFlinger::setMasterVolume(float value)
599{
Eric Laurenta1884f92011-08-23 08:25:03 -0700600 status_t ret = initCheck();
601 if (ret != NO_ERROR) {
602 return ret;
603 }
604
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 // check calling permissions
606 if (!settingsAllowed()) {
607 return PERMISSION_DENIED;
608 }
609
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 float swmv = value;
611
Eric Laurenta4c5a552012-03-29 10:12:40 -0700612 Mutex::Autolock _l(mLock);
613
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800615 if (MVS_NONE != mMasterVolumeSupportLvl) {
616 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
617 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700618 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800619
620 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
621 if (NULL != dev->set_master_volume) {
622 dev->set_master_volume(dev, value);
623 }
624 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800625 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800626
627 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
John Grossman4ff14ba2012-02-08 16:37:41 -0800630 mMasterVolume = value;
631 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800632 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700633 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634
635 return NO_ERROR;
636}
637
Glenn Kastenf78aee72012-01-04 11:00:47 -0800638status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639{
Eric Laurenta1884f92011-08-23 08:25:03 -0700640 status_t ret = initCheck();
641 if (ret != NO_ERROR) {
642 return ret;
643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644
645 // check calling permissions
646 if (!settingsAllowed()) {
647 return PERMISSION_DENIED;
648 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800649 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000650 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651 return BAD_VALUE;
652 }
653
654 { // scope for the lock
655 AutoMutex lock(mHardwareLock);
656 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700657 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 mHardwareStatus = AUDIO_HW_IDLE;
659 }
660
661 if (NO_ERROR == ret) {
662 Mutex::Autolock _l(mLock);
663 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800664 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700665 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 }
667
668 return ret;
669}
670
671status_t AudioFlinger::setMicMute(bool state)
672{
Eric Laurenta1884f92011-08-23 08:25:03 -0700673 status_t ret = initCheck();
674 if (ret != NO_ERROR) {
675 return ret;
676 }
677
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 // check calling permissions
679 if (!settingsAllowed()) {
680 return PERMISSION_DENIED;
681 }
682
683 AutoMutex lock(mHardwareLock);
684 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700685 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 mHardwareStatus = AUDIO_HW_IDLE;
687 return ret;
688}
689
690bool AudioFlinger::getMicMute() const
691{
Eric Laurenta1884f92011-08-23 08:25:03 -0700692 status_t ret = initCheck();
693 if (ret != NO_ERROR) {
694 return false;
695 }
696
Dima Zavinfce7a472011-04-19 22:30:36 -0700697 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800698 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700700 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 mHardwareStatus = AUDIO_HW_IDLE;
702 return state;
703}
704
705status_t AudioFlinger::setMasterMute(bool muted)
706{
707 // check calling permissions
708 if (!settingsAllowed()) {
709 return PERMISSION_DENIED;
710 }
711
Eric Laurent93575202011-01-18 18:39:02 -0800712 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800713 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800715 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700716 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717
718 return NO_ERROR;
719}
720
721float AudioFlinger::masterVolume() const
722{
Glenn Kasten98067102011-12-13 11:47:54 -0800723 Mutex::Autolock _l(mLock);
724 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725}
726
John Grossman4ff14ba2012-02-08 16:37:41 -0800727float AudioFlinger::masterVolumeSW() const
728{
729 Mutex::Autolock _l(mLock);
730 return masterVolumeSW_l();
731}
732
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733bool AudioFlinger::masterMute() const
734{
Glenn Kasten98067102011-12-13 11:47:54 -0800735 Mutex::Autolock _l(mLock);
736 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737}
738
John Grossman4ff14ba2012-02-08 16:37:41 -0800739float AudioFlinger::masterVolume_l() const
740{
741 if (MVS_FULL == mMasterVolumeSupportLvl) {
742 float ret_val;
743 AutoMutex lock(mHardwareLock);
744
745 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800746 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
747 (NULL != mPrimaryHardwareDev->get_master_volume),
748 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800749
750 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
751 mHardwareStatus = AUDIO_HW_IDLE;
752 return ret_val;
753 }
754
755 return mMasterVolume;
756}
757
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800758status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
759 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760{
761 // check calling permissions
762 if (!settingsAllowed()) {
763 return PERMISSION_DENIED;
764 }
765
Glenn Kasten263709e2012-01-06 08:40:01 -0800766 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000767 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768 return BAD_VALUE;
769 }
770
771 AutoMutex lock(mLock);
772 PlaybackThread *thread = NULL;
773 if (output) {
774 thread = checkPlaybackThread_l(output);
775 if (thread == NULL) {
776 return BAD_VALUE;
777 }
778 }
779
780 mStreamTypes[stream].volume = value;
781
782 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800783 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700784 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 }
786 } else {
787 thread->setStreamVolume(stream, value);
788 }
789
790 return NO_ERROR;
791}
792
Glenn Kastenfff6d712012-01-12 16:38:12 -0800793status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794{
795 // check calling permissions
796 if (!settingsAllowed()) {
797 return PERMISSION_DENIED;
798 }
799
Glenn Kasten263709e2012-01-06 08:40:01 -0800800 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700801 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000802 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803 return BAD_VALUE;
804 }
805
Eric Laurent93575202011-01-18 18:39:02 -0800806 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 mStreamTypes[stream].mute = muted;
808 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700809 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810
811 return NO_ERROR;
812}
813
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800814float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815{
Glenn Kasten263709e2012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return 0.0f;
818 }
819
820 AutoMutex lock(mLock);
821 float volume;
822 if (output) {
823 PlaybackThread *thread = checkPlaybackThread_l(output);
824 if (thread == NULL) {
825 return 0.0f;
826 }
827 volume = thread->streamVolume(stream);
828 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800829 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 }
831
832 return volume;
833}
834
Glenn Kastenfff6d712012-01-12 16:38:12 -0800835bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836{
Glenn Kasten263709e2012-01-06 08:40:01 -0800837 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 return true;
839 }
840
Glenn Kasten6637baa2012-01-09 09:40:36 -0800841 AutoMutex lock(mLock);
842 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843}
844
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800845status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800847 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
849 // check calling permissions
850 if (!settingsAllowed()) {
851 return PERMISSION_DENIED;
852 }
853
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 // ioHandle == 0 means the parameters are global to the audio hardware interface
855 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700856 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700857 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800858 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700859 AutoMutex lock(mHardwareLock);
860 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
861 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
862 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
863 status_t result = dev->set_parameters(dev, keyValuePairs.string());
864 final_result = result ?: final_result;
865 }
866 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800867 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700868 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
869 AudioParameter param = AudioParameter(keyValuePairs);
870 String8 value;
871 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700872 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
873 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700874 for (size_t i = 0; i < mRecordThreads.size(); i++) {
875 sp<RecordThread> thread = mRecordThreads.valueAt(i);
876 RecordThread::RecordTrack *track = thread->track();
877 if (track != NULL) {
878 audio_devices_t device = (audio_devices_t)(
879 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700880 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700881 thread->setEffectSuspended(FX_IID_AEC,
882 suspend,
883 track->sessionId());
884 thread->setEffectSuspended(FX_IID_NS,
885 suspend,
886 track->sessionId());
887 }
888 }
Eric Laurentbee53372011-08-29 12:42:48 -0700889 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700890 }
891 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700892 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
894
895 // hold a strong ref on thread in case closeOutput() or closeInput() is called
896 // and the thread is exited once the lock is released
897 sp<ThreadBase> thread;
898 {
899 Mutex::Autolock _l(mLock);
900 thread = checkPlaybackThread_l(ioHandle);
901 if (thread == NULL) {
902 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800903 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700904 // indicate output device change to all input threads for pre processing
905 AudioParameter param = AudioParameter(keyValuePairs);
906 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700907 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
908 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700909 for (size_t i = 0; i < mRecordThreads.size(); i++) {
910 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
911 }
912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800915 if (thread != 0) {
916 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918 return BAD_VALUE;
919}
920
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800921String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800923// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
925
Eric Laurenta4c5a552012-03-29 10:12:40 -0700926 Mutex::Autolock _l(mLock);
927
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700929 String8 out_s8;
930
Dima Zavin799a70e2011-04-18 16:57:27 -0700931 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800932 char *s;
933 {
934 AutoMutex lock(mHardwareLock);
935 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700936 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800937 s = dev->get_parameters(dev, keys.string());
938 mHardwareStatus = AUDIO_HW_IDLE;
939 }
John Grossmanef7740b2012-02-09 11:28:36 -0800940 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700941 free(s);
942 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700943 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 }
945
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
947 if (playbackThread != NULL) {
948 return playbackThread->getParameters(keys);
949 }
950 RecordThread *recordThread = checkRecordThread_l(ioHandle);
951 if (recordThread != NULL) {
952 return recordThread->getParameters(keys);
953 }
954 return String8("");
955}
956
Glenn Kastenf587ba52012-01-26 16:25:10 -0800957size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958{
Eric Laurenta1884f92011-08-23 08:25:03 -0700959 status_t ret = initCheck();
960 if (ret != NO_ERROR) {
961 return 0;
962 }
963
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800964 AutoMutex lock(mHardwareLock);
965 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700966 struct audio_config config = {
967 sample_rate: sampleRate,
968 channel_mask: audio_channel_in_mask_from_count(channelCount),
969 format: format,
970 };
971 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800972 mHardwareStatus = AUDIO_HW_IDLE;
973 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974}
975
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800976unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977{
978 if (ioHandle == 0) {
979 return 0;
980 }
981
982 Mutex::Autolock _l(mLock);
983
984 RecordThread *recordThread = checkRecordThread_l(ioHandle);
985 if (recordThread != NULL) {
986 return recordThread->getInputFramesLost();
987 }
988 return 0;
989}
990
991status_t AudioFlinger::setVoiceVolume(float value)
992{
Eric Laurenta1884f92011-08-23 08:25:03 -0700993 status_t ret = initCheck();
994 if (ret != NO_ERROR) {
995 return ret;
996 }
997
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998 // check calling permissions
999 if (!settingsAllowed()) {
1000 return PERMISSION_DENIED;
1001 }
1002
1003 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001004 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001005 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 mHardwareStatus = AUDIO_HW_IDLE;
1007
1008 return ret;
1009}
1010
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001011status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1012 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013{
1014 status_t status;
1015
1016 Mutex::Autolock _l(mLock);
1017
1018 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1019 if (playbackThread != NULL) {
1020 return playbackThread->getRenderPosition(halFrames, dspFrames);
1021 }
1022
1023 return BAD_VALUE;
1024}
1025
1026void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1027{
1028
1029 Mutex::Autolock _l(mLock);
1030
Glenn Kastenbb001922012-02-03 11:10:26 -08001031 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 if (mNotificationClients.indexOfKey(pid) < 0) {
1033 sp<NotificationClient> notificationClient = new NotificationClient(this,
1034 client,
1035 pid);
Steve Block3856b092011-10-20 11:56:00 +01001036 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037
1038 mNotificationClients.add(pid, notificationClient);
1039
1040 sp<IBinder> binder = client->asBinder();
1041 binder->linkToDeath(notificationClient);
1042
1043 // the config change is always sent from playback or record threads to avoid deadlock
1044 // with AudioSystem::gLock
1045 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1046 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1047 }
1048
1049 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1050 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1051 }
1052 }
1053}
1054
1055void AudioFlinger::removeNotificationClient(pid_t pid)
1056{
1057 Mutex::Autolock _l(mLock);
1058
Glenn Kastena3b09252012-01-20 09:19:01 -08001059 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001060
Steve Block3856b092011-10-20 11:56:00 +01001061 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001062 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001064 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001065 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001066 ALOGV(" pid %d @ %d", ref->mPid, i);
1067 if (ref->mPid == pid) {
1068 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001069 mAudioSessionRefs.removeAt(i);
1070 delete ref;
1071 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001072 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001073 } else {
1074 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001075 }
1076 }
1077 if (removed) {
1078 purgeStaleEffects_l();
1079 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080}
1081
1082// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001083void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084{
1085 size_t size = mNotificationClients.size();
1086 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001087 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1088 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 }
1090}
1091
1092// removeClient_l() must be called with AudioFlinger::mLock held
1093void AudioFlinger::removeClient_l(pid_t pid)
1094{
Steve Block3856b092011-10-20 11:56:00 +01001095 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 mClients.removeItem(pid);
1097}
1098
1099
1100// ----------------------------------------------------------------------------
1101
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001102AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1103 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001105 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001106 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001107 // mChannelMask
1108 mChannelCount(0),
1109 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1110 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001111 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001112 mDevice(device),
1113 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114{
1115}
1116
1117AudioFlinger::ThreadBase::~ThreadBase()
1118{
1119 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001120 // do not lock the mutex in destructor
1121 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001122 if (mPowerManager != 0) {
1123 sp<IBinder> binder = mPowerManager->asBinder();
1124 binder->unlinkToDeath(mDeathRecipient);
1125 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126}
1127
1128void AudioFlinger::ThreadBase::exit()
1129{
Steve Block3856b092011-10-20 11:56:00 +01001130 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001132 // This lock prevents the following race in thread (uniprocessor for illustration):
1133 // if (!exitPending()) {
1134 // // context switch from here to exit()
1135 // // exit() calls requestExit(), what exitPending() observes
1136 // // exit() calls signal(), which is dropped since no waiters
1137 // // context switch back from exit() to here
1138 // mWaitWorkCV.wait(...);
1139 // // now thread is hung
1140 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001141 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 requestExit();
1143 mWaitWorkCV.signal();
1144 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001145 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1146 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 requestExitAndWait();
1148}
1149
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1151{
1152 status_t status;
1153
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 Mutex::Autolock _l(mLock);
1156
1157 mNewParameters.add(keyValuePairs);
1158 mWaitWorkCV.signal();
1159 // wait condition with timeout in case the thread loop has exited
1160 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001161 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 status = mParamStatus;
1163 mWaitWorkCV.signal();
1164 } else {
1165 status = TIMED_OUT;
1166 }
1167 return status;
1168}
1169
1170void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1171{
1172 Mutex::Autolock _l(mLock);
1173 sendConfigEvent_l(event, param);
1174}
1175
1176// sendConfigEvent_l() must be called with ThreadBase::mLock held
1177void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1178{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001179 ConfigEvent configEvent;
1180 configEvent.mEvent = event;
1181 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001183 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 mWaitWorkCV.signal();
1185}
1186
1187void AudioFlinger::ThreadBase::processConfigEvents()
1188{
1189 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001190 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001191 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001192 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 mConfigEvents.removeAt(0);
1194 // release mLock before locking AudioFlinger mLock: lock order is always
1195 // AudioFlinger then ThreadBase to avoid cross deadlock
1196 mLock.unlock();
1197 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001198 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 mLock.lock();
1201 }
1202 mLock.unlock();
1203}
1204
1205status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1206{
1207 const size_t SIZE = 256;
1208 char buffer[SIZE];
1209 String8 result;
1210
1211 bool locked = tryLock(mLock);
1212 if (!locked) {
1213 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1214 write(fd, buffer, strlen(buffer));
1215 }
1216
Eric Laurent612bbb52012-03-14 15:03:26 -07001217 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1218 result.append(buffer);
1219 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1220 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1222 result.append(buffer);
1223 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1224 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001225 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1226 result.append(buffer);
1227 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228 result.append(buffer);
1229 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1230 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001231 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1232 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001233 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1234 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001235 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 result.append(buffer);
1237
1238 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1239 result.append(buffer);
1240 result.append(" Index Command");
1241 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1242 snprintf(buffer, SIZE, "\n %02d ", i);
1243 result.append(buffer);
1244 result.append(mNewParameters[i]);
1245 }
1246
1247 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1248 result.append(buffer);
1249 snprintf(buffer, SIZE, " Index event param\n");
1250 result.append(buffer);
1251 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001252 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 result.append(buffer);
1254 }
1255 result.append("\n");
1256
1257 write(fd, result.string(), result.size());
1258
1259 if (locked) {
1260 mLock.unlock();
1261 }
1262 return NO_ERROR;
1263}
1264
Eric Laurent1d2bff02011-07-24 17:49:51 -07001265status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1266{
1267 const size_t SIZE = 256;
1268 char buffer[SIZE];
1269 String8 result;
1270
1271 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1272 write(fd, buffer, strlen(buffer));
1273
1274 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1275 sp<EffectChain> chain = mEffectChains[i];
1276 if (chain != 0) {
1277 chain->dump(fd, args);
1278 }
1279 }
1280 return NO_ERROR;
1281}
1282
Eric Laurentfeb0db62011-07-22 09:04:31 -07001283void AudioFlinger::ThreadBase::acquireWakeLock()
1284{
1285 Mutex::Autolock _l(mLock);
1286 acquireWakeLock_l();
1287}
1288
1289void AudioFlinger::ThreadBase::acquireWakeLock_l()
1290{
1291 if (mPowerManager == 0) {
1292 // use checkService() to avoid blocking if power service is not up yet
1293 sp<IBinder> binder =
1294 defaultServiceManager()->checkService(String16("power"));
1295 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001296 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001297 } else {
1298 mPowerManager = interface_cast<IPowerManager>(binder);
1299 binder->linkToDeath(mDeathRecipient);
1300 }
1301 }
1302 if (mPowerManager != 0) {
1303 sp<IBinder> binder = new BBinder();
1304 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1305 binder,
1306 String16(mName));
1307 if (status == NO_ERROR) {
1308 mWakeLockToken = binder;
1309 }
Steve Block3856b092011-10-20 11:56:00 +01001310 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001311 }
1312}
1313
1314void AudioFlinger::ThreadBase::releaseWakeLock()
1315{
1316 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001317 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001318}
1319
1320void AudioFlinger::ThreadBase::releaseWakeLock_l()
1321{
1322 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001323 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001324 if (mPowerManager != 0) {
1325 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1326 }
1327 mWakeLockToken.clear();
1328 }
1329}
1330
1331void AudioFlinger::ThreadBase::clearPowerManager()
1332{
1333 Mutex::Autolock _l(mLock);
1334 releaseWakeLock_l();
1335 mPowerManager.clear();
1336}
1337
1338void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1339{
1340 sp<ThreadBase> thread = mThread.promote();
1341 if (thread != 0) {
1342 thread->clearPowerManager();
1343 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001344 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001345}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001346
Eric Laurent59255e42011-07-27 19:49:51 -07001347void AudioFlinger::ThreadBase::setEffectSuspended(
1348 const effect_uuid_t *type, bool suspend, int sessionId)
1349{
1350 Mutex::Autolock _l(mLock);
1351 setEffectSuspended_l(type, suspend, sessionId);
1352}
1353
1354void AudioFlinger::ThreadBase::setEffectSuspended_l(
1355 const effect_uuid_t *type, bool suspend, int sessionId)
1356{
Glenn Kasten090f0192012-01-30 13:00:02 -08001357 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001358 if (chain != 0) {
1359 if (type != NULL) {
1360 chain->setEffectSuspended_l(type, suspend);
1361 } else {
1362 chain->setEffectSuspendedAll_l(suspend);
1363 }
1364 }
1365
1366 updateSuspendedSessions_l(type, suspend, sessionId);
1367}
1368
1369void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1370{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001371 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001372 if (index < 0) {
1373 return;
1374 }
1375
1376 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1377 mSuspendedSessions.editValueAt(index);
1378
1379 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001380 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001381 for (int j = 0; j < desc->mRefCount; j++) {
1382 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1383 chain->setEffectSuspendedAll_l(true);
1384 } else {
Steve Block3856b092011-10-20 11:56:00 +01001385 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001386 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001387 chain->setEffectSuspended_l(&desc->mType, true);
1388 }
1389 }
1390 }
1391}
1392
Eric Laurent59255e42011-07-27 19:49:51 -07001393void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1394 bool suspend,
1395 int sessionId)
1396{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001397 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001398
1399 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1400
1401 if (suspend) {
1402 if (index >= 0) {
1403 sessionEffects = mSuspendedSessions.editValueAt(index);
1404 } else {
1405 mSuspendedSessions.add(sessionId, sessionEffects);
1406 }
1407 } else {
1408 if (index < 0) {
1409 return;
1410 }
1411 sessionEffects = mSuspendedSessions.editValueAt(index);
1412 }
1413
1414
1415 int key = EffectChain::kKeyForSuspendAll;
1416 if (type != NULL) {
1417 key = type->timeLow;
1418 }
1419 index = sessionEffects.indexOfKey(key);
1420
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001421 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001422 if (suspend) {
1423 if (index >= 0) {
1424 desc = sessionEffects.valueAt(index);
1425 } else {
1426 desc = new SuspendedSessionDesc();
1427 if (type != NULL) {
1428 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1429 }
1430 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001431 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001432 }
1433 desc->mRefCount++;
1434 } else {
1435 if (index < 0) {
1436 return;
1437 }
1438 desc = sessionEffects.valueAt(index);
1439 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001440 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001441 sessionEffects.removeItemsAt(index);
1442 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001443 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001444 sessionId);
1445 mSuspendedSessions.removeItem(sessionId);
1446 }
1447 }
1448 }
1449 if (!sessionEffects.isEmpty()) {
1450 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1451 }
1452}
1453
1454void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1455 bool enabled,
1456 int sessionId)
1457{
1458 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001459 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1460}
Eric Laurent59255e42011-07-27 19:49:51 -07001461
Eric Laurenta85a74a2011-10-19 11:44:54 -07001462void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1463 bool enabled,
1464 int sessionId)
1465{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001466 if (mType != RECORD) {
1467 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1468 // another session. This gives the priority to well behaved effect control panels
1469 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001470 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1471 // global effects
1472 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001473 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1474 }
1475 }
Eric Laurent59255e42011-07-27 19:49:51 -07001476
1477 sp<EffectChain> chain = getEffectChain_l(sessionId);
1478 if (chain != 0) {
1479 chain->checkSuspendOnEffectEnabled(effect, enabled);
1480 }
1481}
1482
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483// ----------------------------------------------------------------------------
1484
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001485AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1486 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001487 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001488 uint32_t device,
1489 type_t type)
1490 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001491 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1492 // Assumes constructor is called by AudioFlinger with it's mLock held,
1493 // but it would be safer to explicitly pass initial masterMute as parameter
1494 mMasterMute(audioFlinger->masterMute_l()),
1495 // mStreamTypes[] initialized in constructor body
1496 mOutput(output),
1497 // Assumes constructor is called by AudioFlinger with it's mLock held,
1498 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001499 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001500 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001501 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001502 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001503 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten288ed212012-04-25 17:52:27 -07001504 // index 0 is reserved for normal mixer's submix
1505 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506{
Glenn Kasten480b4682012-02-28 12:30:08 -08001507 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001508
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 readOutputParameters();
1510
Glenn Kasten263709e2012-01-06 08:40:01 -08001511 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001512 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1513 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1514 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001515 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1516 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001518 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1519 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520}
1521
1522AudioFlinger::PlaybackThread::~PlaybackThread()
1523{
1524 delete [] mMixBuffer;
1525}
1526
1527status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1528{
1529 dumpInternals(fd, args);
1530 dumpTracks(fd, args);
1531 dumpEffectChains(fd, args);
1532 return NO_ERROR;
1533}
1534
1535status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1536{
1537 const size_t SIZE = 256;
1538 char buffer[SIZE];
1539 String8 result;
1540
Glenn Kasten58912562012-04-03 10:45:00 -07001541 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1542 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1543 const stream_type_t *st = &mStreamTypes[i];
1544 if (i > 0) {
1545 result.appendFormat(", ");
1546 }
1547 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1548 if (st->mute) {
1549 result.append("M");
1550 }
1551 }
1552 result.append("\n");
1553 write(fd, result.string(), result.length());
1554 result.clear();
1555
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1557 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001558 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559 for (size_t i = 0; i < mTracks.size(); ++i) {
1560 sp<Track> track = mTracks[i];
1561 if (track != 0) {
1562 track->dump(buffer, SIZE);
1563 result.append(buffer);
1564 }
1565 }
1566
1567 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1568 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001569 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001571 sp<Track> track = mActiveTracks[i].promote();
1572 if (track != 0) {
1573 track->dump(buffer, SIZE);
1574 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575 }
1576 }
1577 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001578
1579 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1580 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1581 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1582 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1583
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 return NO_ERROR;
1585}
1586
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1588{
1589 const size_t SIZE = 256;
1590 char buffer[SIZE];
1591 String8 result;
1592
1593 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1596 result.append(buffer);
1597 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1598 result.append(buffer);
1599 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1600 result.append(buffer);
1601 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1602 result.append(buffer);
1603 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1604 result.append(buffer);
1605 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1606 result.append(buffer);
1607 write(fd, result.string(), result.size());
1608
1609 dumpBase(fd, args);
1610
1611 return NO_ERROR;
1612}
1613
1614// Thread virtuals
1615status_t AudioFlinger::PlaybackThread::readyToRun()
1616{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001617 status_t status = initCheck();
1618 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001619 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001620 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001621 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001623 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624}
1625
1626void AudioFlinger::PlaybackThread::onFirstRef()
1627{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001628 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629}
1630
1631// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001632sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001634 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001636 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001637 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 int frameCount,
1639 const sp<IMemory>& sharedBuffer,
1640 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001641 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001642 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 status_t *status)
1644{
1645 sp<Track> track;
1646 status_t lStatus;
1647
Glenn Kasten73d22752012-03-19 13:38:30 -07001648 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1649
1650 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001651 if (flags & IAudioFlinger::TRACK_FAST) {
1652 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001653 // not timed
1654 (!isTimed) &&
1655 // either of these use cases:
1656 (
1657 // use case 1: shared buffer with any frame count
1658 (
1659 (sharedBuffer != 0)
1660 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001661 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001662 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001663 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001664 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001665 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001666 )
1667 ) &&
1668 // PCM data
1669 audio_is_linear_pcm(format) &&
1670 // mono or stereo
1671 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1672 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001673#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001674 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001675 (sampleRate == mSampleRate) &&
1676#endif
1677 // normal mixer has an associated fast mixer
1678 hasFastMixer() &&
1679 // there are sufficient fast track slots available
1680 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001681 // FIXME test that MixerThread for this fast track has a capable output HAL
1682 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001683 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001684 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1685 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001686 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001687 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001688 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001689 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001690 } else {
1691 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001692 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1693 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1694 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1695 audio_is_linear_pcm(format),
1696 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001697 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001698 // For compatibility with AudioTrack calculation, buffer depth is forced
1699 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1700 // This is probably too conservative, but legacy application code may depend on it.
1701 // If you change this calculation, also review the start threshold which is related.
1702 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1703 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1704 if (minBufCount < 2) {
1705 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001706 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001707 int minFrameCount = mNormalFrameCount * minBufCount;
1708 if (frameCount < minFrameCount) {
1709 frameCount = minFrameCount;
1710 }
1711 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001712 }
1713
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001715 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1716 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001717 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001718 "for output %p with format %d",
1719 sampleRate, format, channelMask, mOutput, mFormat);
1720 lStatus = BAD_VALUE;
1721 goto Exit;
1722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 }
1724 } else {
1725 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1726 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001727 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 lStatus = BAD_VALUE;
1729 goto Exit;
1730 }
1731 }
1732
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001733 lStatus = initCheck();
1734 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001735 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736 goto Exit;
1737 }
1738
1739 { // scope for mLock
1740 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001741
1742 // all tracks in same audio session must share the same routing strategy otherwise
1743 // conflicts will happen when tracks are moved from one output to another by audio policy
1744 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001745 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001746 for (size_t i = 0; i < mTracks.size(); ++i) {
1747 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001748 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001749 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001750 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001751 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001752 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001753 lStatus = BAD_VALUE;
1754 goto Exit;
1755 }
1756 }
1757 }
1758
John Grossman4ff14ba2012-02-08 16:37:41 -08001759 if (!isTimed) {
1760 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001761 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001762 } else {
1763 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1764 channelMask, frameCount, sharedBuffer, sessionId);
1765 }
1766 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 lStatus = NO_MEMORY;
1768 goto Exit;
1769 }
1770 mTracks.add(track);
1771
1772 sp<EffectChain> chain = getEffectChain_l(sessionId);
1773 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001774 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001776 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001777 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778 }
1779 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001780
1781#ifdef HAVE_REQUEST_PRIORITY
1782 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1783 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1784 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1785 // so ask activity manager to do this on our behalf
1786 int err = requestPriority(callingPid, tid, 1);
1787 if (err != 0) {
1788 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1789 1, callingPid, tid, err);
1790 }
1791 }
1792#endif
1793
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794 lStatus = NO_ERROR;
1795
1796Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001797 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 *status = lStatus;
1799 }
1800 return track;
1801}
1802
Eric Laurente737cda2012-05-22 18:55:44 -07001803uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1804{
1805 if (mFastMixer != NULL) {
1806 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1807 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1808 }
1809 return latency;
1810}
1811
1812uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1813{
1814 return latency;
1815}
1816
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817uint32_t AudioFlinger::PlaybackThread::latency() const
1818{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001819 Mutex::Autolock _l(mLock);
1820 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001821 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001822 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 return 0;
1824 }
1825}
1826
Glenn Kasten6637baa2012-01-09 09:40:36 -08001827void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001829 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831}
1832
Glenn Kasten6637baa2012-01-09 09:40:36 -08001833void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001835 Mutex::Autolock _l(mLock);
1836 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837}
1838
Glenn Kasten6637baa2012-01-09 09:40:36 -08001839void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001841 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843}
1844
Glenn Kasten6637baa2012-01-09 09:40:36 -08001845void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001847 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849}
1850
Glenn Kastenfff6d712012-01-12 16:38:12 -08001851float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001853 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 return mStreamTypes[stream].volume;
1855}
1856
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857// addTrack_l() must be called with ThreadBase::mLock held
1858status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1859{
1860 status_t status = ALREADY_EXISTS;
1861
1862 // set retry count for buffer fill
1863 track->mRetryCount = kMaxTrackStartupRetries;
1864 if (mActiveTracks.indexOf(track) < 0) {
1865 // the track is newly added, make sure it fills up all its
1866 // buffers before playing. This is to ensure the client will
1867 // effectively get the latency it requested.
1868 track->mFillingUpStatus = Track::FS_FILLING;
1869 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001870 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 mActiveTracks.add(track);
1872 if (track->mainBuffer() != mMixBuffer) {
1873 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1874 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001875 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001876 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 }
1878 }
1879
1880 status = NO_ERROR;
1881 }
1882
Steve Block3856b092011-10-20 11:56:00 +01001883 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 mWaitWorkCV.broadcast();
1885
1886 return status;
1887}
1888
1889// destroyTrack_l() must be called with ThreadBase::mLock held
1890void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1891{
1892 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001893 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001895 removeTrack_l(track);
1896 }
1897}
1898
1899void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1900{
Eric Laurent29864602012-05-08 18:57:51 -07001901 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001902 mTracks.remove(track);
1903 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001904 // redundant as track is about to be destroyed, for dumpsys only
1905 track->mName = -1;
1906 if (track->isFastTrack()) {
1907 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001908 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001909 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1910 mFastTrackAvailMask |= 1 << index;
1911 // redundant as track is about to be destroyed, for dumpsys only
1912 track->mFastIndex = -1;
1913 }
Eric Laurentb469b942011-05-09 12:09:06 -07001914 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1915 if (chain != 0) {
1916 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 }
1918}
1919
1920String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1921{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001922 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001923 char *s;
1924
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001925 Mutex::Autolock _l(mLock);
1926 if (initCheck() != NO_ERROR) {
1927 return out_s8;
1928 }
1929
Dima Zavin799a70e2011-04-18 16:57:27 -07001930 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001931 out_s8 = String8(s);
1932 free(s);
1933 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934}
1935
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001936// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1938 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001939 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940
Steve Block3856b092011-10-20 11:56:00 +01001941 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942
1943 switch (event) {
1944 case AudioSystem::OUTPUT_OPENED:
1945 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001946 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 desc.samplingRate = mSampleRate;
1948 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001949 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950 desc.latency = latency();
1951 param2 = &desc;
1952 break;
1953
1954 case AudioSystem::STREAM_CONFIG_CHANGED:
1955 param2 = &param;
1956 case AudioSystem::OUTPUT_CLOSED:
1957 default:
1958 break;
1959 }
1960 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1961}
1962
1963void AudioFlinger::PlaybackThread::readOutputParameters()
1964{
Dima Zavin799a70e2011-04-18 16:57:27 -07001965 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001966 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1967 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001968 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001969 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001970 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001971 if (mFrameCount & 15) {
1972 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1973 mFrameCount);
1974 }
1975
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001976 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001977 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001978 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001979 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001980 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1981 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1982 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1983 maxNormalFrameCount = maxNormalFrameCount & ~15;
1984 if (maxNormalFrameCount < minNormalFrameCount) {
1985 maxNormalFrameCount = minNormalFrameCount;
1986 }
1987 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1988 if (multiplier <= 1.0) {
1989 multiplier = 1.0;
1990 } else if (multiplier <= 2.0) {
1991 if (2 * mFrameCount <= maxNormalFrameCount) {
1992 multiplier = 2.0;
1993 } else {
1994 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1995 }
1996 } else {
1997 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
1998 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
1999 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2000 // FIXME this rounding up should not be done if no HAL SRC
2001 uint32_t truncMult = (uint32_t) multiplier;
2002 if ((truncMult & 1)) {
2003 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2004 ++truncMult;
2005 }
2006 }
2007 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002008 }
Glenn Kasten58912562012-04-03 10:45:00 -07002009 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002010 mNormalFrameCount = multiplier * mFrameCount;
2011 // round up to nearest 16 frames to satisfy AudioMixer
2012 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002013 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014
2015 // FIXME - Current mixer implementation only supports stereo output: Always
2016 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08002017 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07002018 mMixBuffer = new int16_t[mNormalFrameCount * 2];
2019 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020
Eric Laurentde070132010-07-13 04:45:46 -07002021 // force reconfiguration of effect chains and engines to take new buffer size and audio
2022 // parameters into account
2023 // Note that mLock is not held when readOutputParameters() is called from the constructor
2024 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2025 // matter.
2026 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2027 Vector< sp<EffectChain> > effectChains = mEffectChains;
2028 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002029 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002030 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031}
2032
Eric Laurente737cda2012-05-22 18:55:44 -07002033
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2035{
Glenn Kastena0d68332012-01-27 16:47:15 -08002036 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 return BAD_VALUE;
2038 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002039 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002040 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041 return INVALID_OPERATION;
2042 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002043 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044
Dima Zavin799a70e2011-04-18 16:57:27 -07002045 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046}
2047
Eric Laurent39e94f82010-07-28 01:32:47 -07002048uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049{
2050 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002051 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002053 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 }
2055
2056 for (size_t i = 0; i < mTracks.size(); ++i) {
2057 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002058 if (sessionId == track->sessionId() &&
2059 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002060 result |= TRACK_SESSION;
2061 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 }
2063 }
2064
Eric Laurent39e94f82010-07-28 01:32:47 -07002065 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066}
2067
Eric Laurentde070132010-07-13 04:45:46 -07002068uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2069{
Dima Zavinfce7a472011-04-19 22:30:36 -07002070 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002071 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002072 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2073 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002074 }
2075 for (size_t i = 0; i < mTracks.size(); i++) {
2076 sp<Track> track = mTracks[i];
2077 if (sessionId == track->sessionId() &&
2078 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002079 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002080 }
2081 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002082 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002083}
2084
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085
Glenn Kastenaed850d2012-01-26 09:46:34 -08002086AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002087{
2088 Mutex::Autolock _l(mLock);
2089 return mOutput;
2090}
2091
2092AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2093{
2094 Mutex::Autolock _l(mLock);
2095 AudioStreamOut *output = mOutput;
2096 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002097 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2098 // must push a NULL and wait for ack
2099 mOutputSink.clear();
2100 mPipeSink.clear();
2101 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002102 return output;
2103}
2104
2105// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002106audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002107{
2108 if (mOutput == NULL) {
2109 return NULL;
2110 }
2111 return &mOutput->stream->common;
2112}
2113
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002114uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002115{
2116 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2117 // decoding and transfer time. So sleeping for half of the latency would likely cause
2118 // underruns
2119 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002120 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002121 } else {
2122 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2123 }
2124}
2125
Eric Laurenta011e352012-03-29 15:51:43 -07002126status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2127{
2128 if (!isValidSyncEvent(event)) {
2129 return BAD_VALUE;
2130 }
2131
2132 Mutex::Autolock _l(mLock);
2133
2134 for (size_t i = 0; i < mTracks.size(); ++i) {
2135 sp<Track> track = mTracks[i];
2136 if (event->triggerSession() == track->sessionId()) {
2137 track->setSyncEvent(event);
2138 return NO_ERROR;
2139 }
2140 }
2141
2142 return NAME_NOT_FOUND;
2143}
2144
2145bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2146{
2147 switch (event->type()) {
2148 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2149 return true;
2150 default:
2151 break;
2152 }
2153 return false;
2154}
2155
Eric Laurent44a957f2012-05-15 15:26:05 -07002156void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2157{
2158 size_t count = tracksToRemove.size();
2159 if (CC_UNLIKELY(count)) {
2160 for (size_t i = 0 ; i < count ; i++) {
2161 const sp<Track>& track = tracksToRemove.itemAt(i);
2162 if ((track->sharedBuffer() != 0) &&
2163 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2164 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2165 }
2166 }
2167 }
2168
2169}
2170
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171// ----------------------------------------------------------------------------
2172
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002173AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002174 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002175 : PlaybackThread(audioFlinger, output, id, device, type),
2176 // mAudioMixer below
2177#ifdef SOAKER
2178 mSoaker(NULL),
2179#endif
2180 // mFastMixer below
2181 mFastMixerFutex(0)
2182 // mOutputSink below
2183 // mPipeSink below
2184 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185{
Glenn Kasten58912562012-04-03 10:45:00 -07002186 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2187 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2188 "mFrameCount=%d, mNormalFrameCount=%d",
2189 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2190 mNormalFrameCount);
2191 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2192
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 // FIXME - Current mixer implementation only supports stereo output
2194 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002195 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 }
Glenn Kasten58912562012-04-03 10:45:00 -07002197
2198 // create an NBAIO sink for the HAL output stream, and negotiate
2199 mOutputSink = new AudioStreamOutSink(output->stream);
2200 size_t numCounterOffers = 0;
2201 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2202 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2203 ALOG_ASSERT(index == 0);
2204
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002205 // initialize fast mixer depending on configuration
2206 bool initFastMixer;
2207 switch (kUseFastMixer) {
2208 case FastMixer_Never:
2209 initFastMixer = false;
2210 break;
2211 case FastMixer_Always:
2212 initFastMixer = true;
2213 break;
2214 case FastMixer_Static:
2215 case FastMixer_Dynamic:
2216 initFastMixer = mFrameCount < mNormalFrameCount;
2217 break;
2218 }
2219 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002220
2221 // create a MonoPipe to connect our submix to FastMixer
2222 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002223 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2224 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2225 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2226 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002227 const NBAIO_Format offers[1] = {format};
2228 size_t numCounterOffers = 0;
2229 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2230 ALOG_ASSERT(index == 0);
2231 mPipeSink = monoPipe;
2232
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002233#ifdef TEE_SINK_FRAMES
2234 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2235 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2236 numCounterOffers = 0;
2237 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2238 ALOG_ASSERT(index == 0);
2239 mTeeSink = teeSink;
2240 PipeReader *teeSource = new PipeReader(*teeSink);
2241 numCounterOffers = 0;
2242 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2243 ALOG_ASSERT(index == 0);
2244 mTeeSource = teeSource;
2245#endif
2246
Glenn Kasten58912562012-04-03 10:45:00 -07002247#ifdef SOAKER
2248 // create a soaker as workaround for governor issues
2249 mSoaker = new Soaker();
2250 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2251 mSoaker->run("Soaker", PRIORITY_LOWEST);
2252#endif
2253
2254 // create fast mixer and configure it initially with just one fast track for our submix
2255 mFastMixer = new FastMixer();
2256 FastMixerStateQueue *sq = mFastMixer->sq();
2257 FastMixerState *state = sq->begin();
2258 FastTrack *fastTrack = &state->mFastTracks[0];
2259 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2260 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2261 fastTrack->mVolumeProvider = NULL;
2262 fastTrack->mGeneration++;
2263 state->mFastTracksGen++;
2264 state->mTrackMask = 1;
2265 // fast mixer will use the HAL output sink
2266 state->mOutputSink = mOutputSink.get();
2267 state->mOutputSinkGen++;
2268 state->mFrameCount = mFrameCount;
2269 state->mCommand = FastMixerState::COLD_IDLE;
2270 // already done in constructor initialization list
2271 //mFastMixerFutex = 0;
2272 state->mColdFutexAddr = &mFastMixerFutex;
2273 state->mColdGen++;
2274 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002275 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002276 sq->end();
2277 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2278
2279 // start the fast mixer
2280 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2281#ifdef HAVE_REQUEST_PRIORITY
2282 pid_t tid = mFastMixer->getTid();
2283 int err = requestPriority(getpid_cached, tid, 2);
2284 if (err != 0) {
2285 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2286 2, getpid_cached, tid, err);
2287 }
2288#endif
2289
2290 } else {
2291 mFastMixer = NULL;
2292 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002293
2294 switch (kUseFastMixer) {
2295 case FastMixer_Never:
2296 case FastMixer_Dynamic:
2297 mNormalSink = mOutputSink;
2298 break;
2299 case FastMixer_Always:
2300 mNormalSink = mPipeSink;
2301 break;
2302 case FastMixer_Static:
2303 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2304 break;
2305 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306}
2307
2308AudioFlinger::MixerThread::~MixerThread()
2309{
Glenn Kasten58912562012-04-03 10:45:00 -07002310 if (mFastMixer != NULL) {
2311 FastMixerStateQueue *sq = mFastMixer->sq();
2312 FastMixerState *state = sq->begin();
2313 if (state->mCommand == FastMixerState::COLD_IDLE) {
2314 int32_t old = android_atomic_inc(&mFastMixerFutex);
2315 if (old == -1) {
2316 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2317 }
2318 }
2319 state->mCommand = FastMixerState::EXIT;
2320 sq->end();
2321 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2322 mFastMixer->join();
2323 // Though the fast mixer thread has exited, it's state queue is still valid.
2324 // We'll use that extract the final state which contains one remaining fast track
2325 // corresponding to our sub-mix.
2326 state = sq->begin();
2327 ALOG_ASSERT(state->mTrackMask == 1);
2328 FastTrack *fastTrack = &state->mFastTracks[0];
2329 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2330 delete fastTrack->mBufferProvider;
2331 sq->end(false /*didModify*/);
2332 delete mFastMixer;
2333#ifdef SOAKER
2334 if (mSoaker != NULL) {
2335 mSoaker->requestExitAndWait();
2336 }
2337 delete mSoaker;
2338#endif
2339 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 delete mAudioMixer;
2341}
2342
Glenn Kasten83efdd02012-02-24 07:21:32 -08002343class CpuStats {
2344public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002345 CpuStats();
2346 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002347#ifdef DEBUG_CPU_USAGE
2348private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002349 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2350 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2351
2352 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2353
2354 int mCpuNum; // thread's current CPU number
2355 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002356#endif
2357};
2358
Glenn Kasten190a46f2012-03-06 11:27:10 -08002359CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002360#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002361 : mCpuNum(-1), mCpukHz(-1)
2362#endif
2363{
2364}
2365
2366void CpuStats::sample(const String8 &title) {
2367#ifdef DEBUG_CPU_USAGE
2368 // get current thread's delta CPU time in wall clock ns
2369 double wcNs;
2370 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2371
2372 // record sample for wall clock statistics
2373 if (valid) {
2374 mWcStats.sample(wcNs);
2375 }
2376
2377 // get the current CPU number
2378 int cpuNum = sched_getcpu();
2379
2380 // get the current CPU frequency in kHz
2381 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2382
2383 // check if either CPU number or frequency changed
2384 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2385 mCpuNum = cpuNum;
2386 mCpukHz = cpukHz;
2387 // ignore sample for purposes of cycles
2388 valid = false;
2389 }
2390
2391 // if no change in CPU number or frequency, then record sample for cycle statistics
2392 if (valid && mCpukHz > 0) {
2393 double cycles = wcNs * cpukHz * 0.000001;
2394 mHzStats.sample(cycles);
2395 }
2396
2397 unsigned n = mWcStats.n();
2398 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002399 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002400 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2402 double perLoop = elapsed / (double) n;
2403 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002404 double perLoop1k = perLoop * 0.001;
2405 double mean = mWcStats.mean();
2406 double stddev = mWcStats.stddev();
2407 double minimum = mWcStats.minimum();
2408 double maximum = mWcStats.maximum();
2409 double meanCycles = mHzStats.mean();
2410 double stddevCycles = mHzStats.stddev();
2411 double minCycles = mHzStats.minimum();
2412 double maxCycles = mHzStats.maximum();
2413 mCpuUsage.resetElapsed();
2414 mWcStats.reset();
2415 mHzStats.reset();
2416 ALOGD("CPU usage for %s over past %.1f secs\n"
2417 " (%u mixer loops at %.1f mean ms per loop):\n"
2418 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2419 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2420 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2421 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002422 elapsed * .000000001, n, perLoop * .000001,
2423 mean * .001,
2424 stddev * .001,
2425 minimum * .001,
2426 maximum * .001,
2427 mean / perLoop100,
2428 stddev / perLoop100,
2429 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002430 maximum / perLoop100,
2431 meanCycles / perLoop1k,
2432 stddevCycles / perLoop1k,
2433 minCycles / perLoop1k,
2434 maxCycles / perLoop1k);
2435
Glenn Kasten83efdd02012-02-24 07:21:32 -08002436 }
2437 }
2438#endif
2439};
2440
Glenn Kasten37d825e2012-02-24 07:21:48 -08002441void AudioFlinger::PlaybackThread::checkSilentMode_l()
2442{
2443 if (!mMasterMute) {
2444 char value[PROPERTY_VALUE_MAX];
2445 if (property_get("ro.audio.silent", value, "0") > 0) {
2446 char *endptr;
2447 unsigned long ul = strtoul(value, &endptr, 0);
2448 if (*endptr == '\0' && ul != 0) {
2449 ALOGD("Silence is golden");
2450 // The setprop command will not allow a property to be changed after
2451 // the first time it is set, so we don't have to worry about un-muting.
2452 setMasterMute_l(true);
2453 }
2454 }
2455 }
2456}
2457
Glenn Kasten000f0e32012-03-01 17:10:56 -08002458bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459{
2460 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002461
Glenn Kasten000f0e32012-03-01 17:10:56 -08002462 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002463
2464 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002466if (mType == MIXER) {
2467 longStandbyExit = false;
2468}
Glenn Kasten688a6402012-02-29 07:57:06 -08002469
Glenn Kasten000f0e32012-03-01 17:10:56 -08002470 // DUPLICATING
2471 // FIXME could this be made local to while loop?
2472 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002473
Glenn Kasten66fcab92012-02-24 14:59:21 -08002474 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475 sleepTime = idleSleepTime;
2476
2477if (mType == MIXER) {
2478 sleepTimeShift = 0;
2479}
2480
Glenn Kasten83efdd02012-02-24 07:21:32 -08002481 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002482 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483
Eric Laurentfeb0db62011-07-22 09:04:31 -07002484 acquireWakeLock();
2485
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 while (!exitPending())
2487 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002488 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002489
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002490 Vector< sp<EffectChain> > effectChains;
2491
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 processConfigEvents();
2493
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 { // scope for mLock
2495
2496 Mutex::Autolock _l(mLock);
2497
2498 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002499 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 }
2501
Glenn Kastenfa26a852012-03-06 11:28:04 -08002502 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002505 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002506 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508
2509 threadLoop_standby();
2510
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 mStandby = true;
2512 mBytesWritten = 0;
2513 }
2514
Glenn Kasten3e074702012-02-28 18:40:35 -08002515 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 // we're about to wait, flush the binder command buffer
2517 IPCThreadState::self()->flushCommands();
2518
Glenn Kastenfa26a852012-03-06 11:28:04 -08002519 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 if (exitPending()) break;
2522
Eric Laurentfeb0db62011-07-22 09:04:31 -07002523 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002525 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002527 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002528 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529
Eric Laurentda747442012-04-25 18:53:13 -07002530 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002531 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002532
Glenn Kasten37d825e2012-02-24 07:21:48 -08002533 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534
Glenn Kasten000f0e32012-03-01 17:10:56 -08002535 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002537 if (mType == MIXER) {
2538 sleepTimeShift = 0;
2539 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002540
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 continue;
2542 }
2543 }
2544
Glenn Kasten81028042012-04-30 18:15:12 -07002545 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002546 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547
2548 // prevent any changes in effect chain list and in each effect chain
2549 // during mixing and effect process as the audio buffers could be deleted
2550 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002551 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553
Glenn Kastenfec279f2012-03-08 07:47:15 -08002554 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002555 threadLoop_mix();
2556 } else {
2557 threadLoop_sleepTime();
2558 }
2559
2560 if (mSuspended > 0) {
2561 sleepTime = suspendSleepTimeUs();
2562 }
2563
2564 // only process effects if we're going to write
2565 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002566 for (size_t i = 0; i < effectChains.size(); i ++) {
2567 effectChains[i]->process_l();
2568 }
2569 }
2570
2571 // enable changes in effect chain
2572 unlockEffectChains(effectChains);
2573
2574 // sleepTime == 0 means we must write to audio hardware
2575 if (sleepTime == 0) {
2576
2577 threadLoop_write();
2578
2579if (mType == MIXER) {
2580 // write blocked detection
2581 nsecs_t now = systemTime();
2582 nsecs_t delta = now - mLastWriteTime;
2583 if (!mStandby && delta > maxPeriod) {
2584 mNumDelayedWrites++;
2585 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002586#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002587 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002588#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002589 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2590 ns2ms(delta), mNumDelayedWrites, this);
2591 lastWarning = now;
2592 }
2593 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2594 // a different threshold. Or completely removed for what it is worth anyway...
2595 if (mStandby) {
2596 longStandbyExit = true;
2597 }
2598 }
2599}
2600
2601 mStandby = false;
2602 } else {
2603 usleep(sleepTime);
2604 }
2605
Glenn Kasten58912562012-04-03 10:45:00 -07002606 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002607 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002608 // same lock. This will also mutate and push a new fast mixer state.
2609 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002610 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002611
Glenn Kastenfa26a852012-03-06 11:28:04 -08002612 // FIXME I don't understand the need for this here;
2613 // it was in the original code but maybe the
2614 // assignment in saveOutputTracks() makes this unnecessary?
2615 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002616
2617 // Effect chains will be actually deleted here if they were removed from
2618 // mEffectChains list during mixing or effects processing
2619 effectChains.clear();
2620
2621 // FIXME Note that the above .clear() is no longer necessary since effectChains
2622 // is now local to this block, but will keep it for now (at least until merge done).
2623 }
2624
2625if (mType == MIXER || mType == DIRECT) {
2626 // put output stream into standby mode
2627 if (!mStandby) {
2628 mOutput->stream->common.standby(&mOutput->stream->common);
2629 }
2630}
2631if (mType == DUPLICATING) {
2632 // for DuplicatingThread, standby mode is handled by the outputTracks
2633}
2634
2635 releaseWakeLock();
2636
2637 ALOGV("Thread %p type %d exiting", this, mType);
2638 return false;
2639}
2640
Glenn Kasten58912562012-04-03 10:45:00 -07002641void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2642{
Glenn Kasten58912562012-04-03 10:45:00 -07002643 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2644}
2645
2646void AudioFlinger::MixerThread::threadLoop_write()
2647{
2648 // FIXME we should only do one push per cycle; confirm this is true
2649 // Start the fast mixer if it's not already running
2650 if (mFastMixer != NULL) {
2651 FastMixerStateQueue *sq = mFastMixer->sq();
2652 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002653 if (state->mCommand != FastMixerState::MIX_WRITE &&
2654 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002655 if (state->mCommand == FastMixerState::COLD_IDLE) {
2656 int32_t old = android_atomic_inc(&mFastMixerFutex);
2657 if (old == -1) {
2658 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2659 }
2660 }
2661 state->mCommand = FastMixerState::MIX_WRITE;
2662 sq->end();
2663 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002664 if (kUseFastMixer == FastMixer_Dynamic) {
2665 mNormalSink = mPipeSink;
2666 }
Glenn Kasten58912562012-04-03 10:45:00 -07002667 } else {
2668 sq->end(false /*didModify*/);
2669 }
2670 }
2671 PlaybackThread::threadLoop_write();
2672}
2673
Glenn Kasten000f0e32012-03-01 17:10:56 -08002674// shared by MIXER and DIRECT, overridden by DUPLICATING
2675void AudioFlinger::PlaybackThread::threadLoop_write()
2676{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002677 // FIXME rewrite to reduce number of system calls
2678 mLastWriteTime = systemTime();
2679 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002680
Glenn Kasten58912562012-04-03 10:45:00 -07002681#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002682 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002683#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002684 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002685#endif
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002686 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002687#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002688 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002689#endif
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002690 if (framesWritten > 0) {
2691 size_t bytesWritten = framesWritten << mBitShift;
2692 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002693 }
2694
Glenn Kasten952eeb22012-03-06 11:30:57 -08002695 mNumWrites++;
2696 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002697}
2698
Glenn Kasten58912562012-04-03 10:45:00 -07002699void AudioFlinger::MixerThread::threadLoop_standby()
2700{
2701 // Idle the fast mixer if it's currently running
2702 if (mFastMixer != NULL) {
2703 FastMixerStateQueue *sq = mFastMixer->sq();
2704 FastMixerState *state = sq->begin();
2705 if (!(state->mCommand & FastMixerState::IDLE)) {
2706 state->mCommand = FastMixerState::COLD_IDLE;
2707 state->mColdFutexAddr = &mFastMixerFutex;
2708 state->mColdGen++;
2709 mFastMixerFutex = 0;
2710 sq->end();
2711 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2712 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002713 if (kUseFastMixer == FastMixer_Dynamic) {
2714 mNormalSink = mOutputSink;
2715 }
Glenn Kasten58912562012-04-03 10:45:00 -07002716 } else {
2717 sq->end(false /*didModify*/);
2718 }
2719 }
2720 PlaybackThread::threadLoop_standby();
2721}
2722
Glenn Kasten000f0e32012-03-01 17:10:56 -08002723// shared by MIXER and DIRECT, overridden by DUPLICATING
2724void AudioFlinger::PlaybackThread::threadLoop_standby()
2725{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002726 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2727 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002728}
2729
2730void AudioFlinger::MixerThread::threadLoop_mix()
2731{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002732 // obtain the presentation timestamp of the next output buffer
2733 int64_t pts;
2734 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002735
Glenn Kasten952eeb22012-03-06 11:30:57 -08002736 if (NULL != mOutput->stream->get_next_write_timestamp) {
2737 status = mOutput->stream->get_next_write_timestamp(
2738 mOutput->stream, &pts);
2739 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002740
Glenn Kasten952eeb22012-03-06 11:30:57 -08002741 if (status != NO_ERROR) {
2742 pts = AudioBufferProvider::kInvalidPTS;
2743 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002744
Glenn Kasten952eeb22012-03-06 11:30:57 -08002745 // mix buffers...
2746 mAudioMixer->process(pts);
2747 // increase sleep time progressively when application underrun condition clears.
2748 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2749 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2750 // such that we would underrun the audio HAL.
2751 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2752 sleepTimeShift--;
2753 }
2754 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002755 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002756 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002757}
2758
2759void AudioFlinger::MixerThread::threadLoop_sleepTime()
2760{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002761 // If no tracks are ready, sleep once for the duration of an output
2762 // buffer size, then write 0s to the output
2763 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002764 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002765 sleepTime = activeSleepTime >> sleepTimeShift;
2766 if (sleepTime < kMinThreadSleepTimeUs) {
2767 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002769 // reduce sleep time in case of consecutive application underruns to avoid
2770 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2771 // duration we would end up writing less data than needed by the audio HAL if
2772 // the condition persists.
2773 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2774 sleepTimeShift++;
2775 }
2776 } else {
2777 sleepTime = idleSleepTime;
2778 }
2779 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002780 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002781 memset (mMixBuffer, 0, mixBufferSize);
2782 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002783 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002784 }
2785 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786}
2787
2788// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002789AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002790 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791{
2792
Glenn Kasten29c23c32012-01-26 13:37:52 -08002793 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002795 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 size_t mixedTracks = 0;
2797 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002798 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002799 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002800 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801
2802 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002803 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804
Eric Laurent571d49c2010-08-11 05:20:11 -07002805 if (masterMute) {
2806 masterVolume = 0;
2807 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002809 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002811 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002812 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 masterVolume = (float)((v + (1 << 23)) >> 24);
2814 chain.clear();
2815 }
2816
Glenn Kasten288ed212012-04-25 17:52:27 -07002817 // prepare a new state to push
2818 FastMixerStateQueue *sq = NULL;
2819 FastMixerState *state = NULL;
2820 bool didModify = false;
2821 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2822 if (mFastMixer != NULL) {
2823 sq = mFastMixer->sq();
2824 state = sq->begin();
2825 }
2826
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002828 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 if (t == 0) continue;
2830
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002831 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002833
Glenn Kasten288ed212012-04-25 17:52:27 -07002834 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002835 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002836
2837 // It's theoretically possible (though unlikely) for a fast track to be created
2838 // and then removed within the same normal mix cycle. This is not a problem, as
2839 // the track never becomes active so it's fast mixer slot is never touched.
2840 // The converse, of removing an (active) track and then creating a new track
2841 // at the identical fast mixer slot within the same normal mix cycle,
2842 // is impossible because the slot isn't marked available until the end of each cycle.
2843 int j = track->mFastIndex;
2844 FastTrack *fastTrack = &state->mFastTracks[j];
2845
2846 // Determine whether the track is currently in underrun condition,
2847 // and whether it had a recent underrun.
Glenn Kasten09474df2012-05-10 14:48:07 -07002848 FastTrackUnderruns underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2849 uint32_t recentFull = (underruns.mBitFields.mFull -
2850 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2851 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2852 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2853 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2854 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2855 uint32_t recentUnderruns = recentPartial + recentEmpty;
2856 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002857 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002858 // or stopped which can occur when flush() is called while active
2859 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002860 track->mUnderrunCount += recentUnderruns;
2861 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002862
Glenn Kastend08f48c2012-05-01 18:14:02 -07002863 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002864 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002865 bool isActive = true;
2866 switch (track->mState) {
2867 case TrackBase::STOPPING_1:
2868 // track stays active in STOPPING_1 state until first underrun
2869 if (recentUnderruns > 0) {
2870 track->mState = TrackBase::STOPPING_2;
2871 }
2872 break;
2873 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002874 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002875 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002876 break;
2877 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002878 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002879 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002880 break;
2881 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002882 if (recentFull > 0 || recentPartial > 0) {
2883 // track has provided at least some frames recently: reset retry count
2884 track->mRetryCount = kMaxTrackRetries;
2885 }
2886 if (recentUnderruns == 0) {
2887 // no recent underruns: stay active
2888 break;
2889 }
2890 // there has recently been an underrun of some kind
2891 if (track->sharedBuffer() == 0) {
2892 // were any of the recent underruns "empty" (no frames available)?
2893 if (recentEmpty == 0) {
2894 // no, then ignore the partial underruns as they are allowed indefinitely
2895 break;
2896 }
2897 // there has recently been an "empty" underrun: decrement the retry counter
2898 if (--(track->mRetryCount) > 0) {
2899 break;
2900 }
2901 // indicate to client process that the track was disabled because of underrun;
2902 // it will then automatically call start() when data is available
2903 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2904 // remove from active list, but state remains ACTIVE [confusing but true]
2905 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002906 break;
2907 }
2908 // fall through
2909 case TrackBase::STOPPING_2:
2910 case TrackBase::PAUSED:
2911 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002912 case TrackBase::STOPPED:
2913 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002914 // Check for presentation complete if track is inactive
2915 // We have consumed all the buffers of this track.
2916 // This would be incomplete if we auto-paused on underrun
2917 {
2918 size_t audioHALFrames =
2919 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2920 size_t framesWritten =
2921 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2922 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2923 // track stays in active list until presentation is complete
2924 break;
2925 }
2926 }
2927 if (track->isStopping_2()) {
2928 track->mState = TrackBase::STOPPED;
2929 }
2930 if (track->isStopped()) {
2931 // Can't reset directly, as fast mixer is still polling this track
2932 // track->reset();
2933 // So instead mark this track as needing to be reset after push with ack
2934 resetMask |= 1 << i;
2935 }
2936 isActive = false;
2937 break;
2938 case TrackBase::IDLE:
2939 default:
2940 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002941 }
2942
2943 if (isActive) {
2944 // was it previously inactive?
2945 if (!(state->mTrackMask & (1 << j))) {
2946 ExtendedAudioBufferProvider *eabp = track;
2947 VolumeProvider *vp = track;
2948 fastTrack->mBufferProvider = eabp;
2949 fastTrack->mVolumeProvider = vp;
2950 fastTrack->mSampleRate = track->mSampleRate;
2951 fastTrack->mChannelMask = track->mChannelMask;
2952 fastTrack->mGeneration++;
2953 state->mTrackMask |= 1 << j;
2954 didModify = true;
2955 // no acknowledgement required for newly active tracks
2956 }
2957 // cache the combined master volume and stream type volume for fast mixer; this
2958 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2959 track->mCachedVolume = track->isMuted() ?
2960 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2961 ++fastTracks;
2962 } else {
2963 // was it previously active?
2964 if (state->mTrackMask & (1 << j)) {
2965 fastTrack->mBufferProvider = NULL;
2966 fastTrack->mGeneration++;
2967 state->mTrackMask &= ~(1 << j);
2968 didModify = true;
2969 // If any fast tracks were removed, we must wait for acknowledgement
2970 // because we're about to decrement the last sp<> on those tracks.
2971 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002972 } else {
2973 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002974 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002975 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002976 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07002977 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002978 }
2979 continue;
2980 }
2981
2982 { // local variable scope to avoid goto warning
2983
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 audio_track_cblk_t* cblk = track->cblk();
2985
2986 // The first time a track is added we wait
2987 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002988 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002989 // make sure that we have enough frames to mix one full buffer.
2990 // enforce this condition only once to enable draining the buffer in case the client
2991 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002992 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002993 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002994 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002995 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002996 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002997 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002998 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002999 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003000 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003001 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003002 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003003 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003004 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3005 // the minimum track buffer size is normally twice the number of frames necessary
3006 // to fill one buffer and the resampler should not leave more than one buffer worth
3007 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003008 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003009 }
3010 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003011 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 !track->isPaused() && !track->isTerminated())
3013 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003014 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015
3016 mixedTracks++;
3017
3018 // track->mainBuffer() != mMixBuffer means there is an effect chain
3019 // connected to the track
3020 chain.clear();
3021 if (track->mainBuffer() != mMixBuffer) {
3022 chain = getEffectChain_l(track->sessionId());
3023 // Delegate volume control to effect in track effect chain if needed
3024 if (chain != 0) {
3025 tracksWithEffect++;
3026 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003027 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003028 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003029 }
3030 }
3031
3032
3033 int param = AudioMixer::VOLUME;
3034 if (track->mFillingUpStatus == Track::FS_FILLED) {
3035 // no ramp for the first volume setting
3036 track->mFillingUpStatus = Track::FS_ACTIVE;
3037 if (track->mState == TrackBase::RESUMING) {
3038 track->mState = TrackBase::ACTIVE;
3039 param = AudioMixer::RAMP_VOLUME;
3040 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003041 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 } else if (cblk->server != 0) {
3043 // If the track is stopped before the first frame was mixed,
3044 // do not apply ramp
3045 param = AudioMixer::RAMP_VOLUME;
3046 }
3047
3048 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003049 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003050 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003051 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003052 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 if (track->isPausing()) {
3054 track->setPaused();
3055 }
3056 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003057
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003059 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003061 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003062 vl = vlr & 0xFFFF;
3063 vr = vlr >> 16;
3064 // track volumes come from shared memory, so can't be trusted and must be clamped
3065 if (vl > MAX_GAIN_INT) {
3066 ALOGV("Track left volume out of range: %04X", vl);
3067 vl = MAX_GAIN_INT;
3068 }
3069 if (vr > MAX_GAIN_INT) {
3070 ALOGV("Track right volume out of range: %04X", vr);
3071 vr = MAX_GAIN_INT;
3072 }
3073 // now apply the master volume and stream type volume
3074 vl = (uint32_t)(v * vl) << 12;
3075 vr = (uint32_t)(v * vr) << 12;
3076 // assuming master volume and stream type volume each go up to 1.0,
3077 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078
Glenn Kasten05632a52012-01-03 14:22:33 -08003079 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3080 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003081 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003082 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003083 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003084 }
3085 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003087 // Delegate volume control to effect in track effect chain if needed
3088 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3089 // Do not ramp volume if volume is controlled by effect
3090 param = AudioMixer::VOLUME;
3091 track->mHasVolumeController = true;
3092 } else {
3093 // force no volume ramp when volume controller was just disabled or removed
3094 // from effect chain to avoid volume spike
3095 if (track->mHasVolumeController) {
3096 param = AudioMixer::VOLUME;
3097 }
3098 track->mHasVolumeController = false;
3099 }
3100
3101 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003102 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003103 vl = (vl + (1 << 11)) >> 12;
3104 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3105 vr = (vr + (1 << 11)) >> 12;
3106 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003107
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003108 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109
Mathias Agopian65ab4712010-07-14 17:59:35 -07003110 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003111 mAudioMixer->setBufferProvider(name, track);
3112 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003114 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3115 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3116 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003118 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119 AudioMixer::TRACK,
3120 AudioMixer::FORMAT, (void *)track->format());
3121 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003122 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003124 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003126 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 AudioMixer::RESAMPLE,
3128 AudioMixer::SAMPLE_RATE,
3129 (void *)(cblk->sampleRate));
3130 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003131 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 AudioMixer::TRACK,
3133 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3134 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003135 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136 AudioMixer::TRACK,
3137 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3138
3139 // reset retry count
3140 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003141
Eric Laurent27741442012-01-17 19:20:12 -08003142 // If one track is ready, set the mixer ready if:
3143 // - the mixer was not ready during previous round OR
3144 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003145 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003146 mixerStatus != MIXER_TRACKS_ENABLED) {
3147 mixerStatus = MIXER_TRACKS_READY;
3148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003150 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurent83faee02012-04-27 18:24:29 -07003151 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3152 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 // We have consumed all the buffers of this track.
3154 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003155 // TODO: use actual buffer filling status instead of latency when available from
3156 // audio HAL
3157 size_t audioHALFrames =
3158 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3159 size_t framesWritten =
3160 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3161 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003162 if (track->isStopped()) {
3163 track->reset();
3164 }
Eric Laurenta011e352012-03-29 15:51:43 -07003165 tracksToRemove->add(track);
3166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 } else {
3168 // No buffers for this track. Give it a few chances to
3169 // fill a buffer, then remove it from active list.
3170 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003171 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003173 // indicate to client process that the track was disabled because of underrun;
3174 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003175 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003176 // If one track is not ready, mark the mixer also not ready if:
3177 // - the mixer was ready during previous round OR
3178 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003179 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003180 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 mixerStatus = MIXER_TRACKS_ENABLED;
3182 }
3183 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003184 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 }
Glenn Kasten58912562012-04-03 10:45:00 -07003186
3187 } // local variable scope to avoid goto warning
3188track_is_ready: ;
3189
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 }
3191
Glenn Kasten288ed212012-04-25 17:52:27 -07003192 // Push the new FastMixer state if necessary
3193 if (didModify) {
3194 state->mFastTracksGen++;
3195 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3196 if (kUseFastMixer == FastMixer_Dynamic &&
3197 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3198 state->mCommand = FastMixerState::COLD_IDLE;
3199 state->mColdFutexAddr = &mFastMixerFutex;
3200 state->mColdGen++;
3201 mFastMixerFutex = 0;
3202 if (kUseFastMixer == FastMixer_Dynamic) {
3203 mNormalSink = mOutputSink;
3204 }
3205 // If we go into cold idle, need to wait for acknowledgement
3206 // so that fast mixer stops doing I/O.
3207 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3208 }
3209 sq->end();
3210 }
3211 if (sq != NULL) {
3212 sq->end(didModify);
3213 sq->push(block);
3214 }
3215
3216 // Now perform the deferred reset on fast tracks that have stopped
3217 while (resetMask != 0) {
3218 size_t i = __builtin_ctz(resetMask);
3219 ALOG_ASSERT(i < count);
3220 resetMask &= ~(1 << i);
3221 sp<Track> t = mActiveTracks[i].promote();
3222 if (t == 0) continue;
3223 Track* track = t.get();
3224 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3225 track->reset();
3226 }
Glenn Kasten58912562012-04-03 10:45:00 -07003227
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 // remove all the tracks that need to be...
3229 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003230 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 for (size_t i=0 ; i<count ; i++) {
3232 const sp<Track>& track = tracksToRemove->itemAt(i);
3233 mActiveTracks.remove(track);
3234 if (track->mainBuffer() != mMixBuffer) {
3235 chain = getEffectChain_l(track->sessionId());
3236 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003237 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003238 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 }
3240 }
3241 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003242 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 }
3244 }
3245 }
3246
3247 // mix buffer must be cleared if all tracks are connected to an
3248 // effect chain as in this case the mixer will not write to
3249 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003250 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3251 // FIXME as a performance optimization, should remember previous zero status
3252 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 }
3254
Glenn Kasten58912562012-04-03 10:45:00 -07003255 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003256 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003257 if (fastTracks > 0) {
3258 mixerStatus = MIXER_TRACKS_READY;
3259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 return mixerStatus;
3261}
3262
Glenn Kasten66fcab92012-02-24 14:59:21 -08003263/*
3264The derived values that are cached:
3265 - mixBufferSize from frame count * frame size
3266 - activeSleepTime from activeSleepTimeUs()
3267 - idleSleepTime from idleSleepTimeUs()
3268 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3269 - maxPeriod from frame count and sample rate (MIXER only)
3270
3271The parameters that affect these derived values are:
3272 - frame count
3273 - frame size
3274 - sample rate
3275 - device type: A2DP or not
3276 - device latency
3277 - format: PCM or not
3278 - active sleep time
3279 - idle sleep time
3280*/
3281
3282void AudioFlinger::PlaybackThread::cacheParameters_l()
3283{
Glenn Kasten58912562012-04-03 10:45:00 -07003284 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003285 activeSleepTime = activeSleepTimeUs();
3286 idleSleepTime = idleSleepTimeUs();
3287}
3288
Glenn Kastenfff6d712012-01-12 16:38:12 -08003289void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290{
Steve Block3856b092011-10-20 11:56:00 +01003291 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003292 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003294
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 size_t size = mTracks.size();
3296 for (size_t i = 0; i < size; i++) {
3297 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003298 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003299 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 }
3302 }
3303}
3304
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003306int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003308 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309}
3310
3311// deleteTrackName_l() must be called with ThreadBase::mLock held
3312void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3313{
Steve Block3856b092011-10-20 11:56:00 +01003314 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 mAudioMixer->deleteTrackName(name);
3316}
3317
3318// checkForNewParameters_l() must be called with ThreadBase::mLock held
3319bool AudioFlinger::MixerThread::checkForNewParameters_l()
3320{
Glenn Kasten58912562012-04-03 10:45:00 -07003321 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3322 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 bool reconfig = false;
3324
3325 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003326
3327 if (mFastMixer != NULL) {
3328 FastMixerStateQueue *sq = mFastMixer->sq();
3329 FastMixerState *state = sq->begin();
3330 if (!(state->mCommand & FastMixerState::IDLE)) {
3331 previousCommand = state->mCommand;
3332 state->mCommand = FastMixerState::HOT_IDLE;
3333 sq->end();
3334 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3335 } else {
3336 sq->end(false /*didModify*/);
3337 }
3338 }
3339
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 status_t status = NO_ERROR;
3341 String8 keyValuePair = mNewParameters[0];
3342 AudioParameter param = AudioParameter(keyValuePair);
3343 int value;
3344
3345 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3346 reconfig = true;
3347 }
3348 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003349 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 status = BAD_VALUE;
3351 } else {
3352 reconfig = true;
3353 }
3354 }
3355 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003356 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 status = BAD_VALUE;
3358 } else {
3359 reconfig = true;
3360 }
3361 }
3362 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3363 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003364 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 // if frame count is changed after track creation
3366 if (!mTracks.isEmpty()) {
3367 status = INVALID_OPERATION;
3368 } else {
3369 reconfig = true;
3370 }
3371 }
3372 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003373#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003374 // when changing the audio output device, call addBatteryData to notify
3375 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003376 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003377 uint32_t params = 0;
3378 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003379 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003380 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3381 }
3382
3383 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003384 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003385 // check if any other device (except speaker) is on
3386 if (value & deviceWithoutSpeaker ) {
3387 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3388 }
3389
3390 if (params != 0) {
3391 addBatteryData(params);
3392 }
3393 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003394#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003395
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 // forward device change to effects that have requested to be
3397 // aware of attached audio device.
3398 mDevice = (uint32_t)value;
3399 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003400 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 }
3402 }
3403
3404 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003405 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003406 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003408 mOutput->stream->common.standby(&mOutput->stream->common);
3409 mStandby = true;
3410 mBytesWritten = 0;
3411 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003412 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 }
3414 if (status == NO_ERROR && reconfig) {
3415 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003416 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3417 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003419 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003421 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 if (name < 0) break;
3423 mTracks[i]->mName = name;
3424 // limit track sample rate to 2 x new output sample rate
3425 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3426 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3427 }
3428 }
3429 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3430 }
3431 }
3432
3433 mNewParameters.removeAt(0);
3434
3435 mParamStatus = status;
3436 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003437 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3438 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003439 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440 }
Glenn Kasten58912562012-04-03 10:45:00 -07003441
3442 if (!(previousCommand & FastMixerState::IDLE)) {
3443 ALOG_ASSERT(mFastMixer != NULL);
3444 FastMixerStateQueue *sq = mFastMixer->sq();
3445 FastMixerState *state = sq->begin();
3446 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3447 state->mCommand = previousCommand;
3448 sq->end();
3449 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3450 }
3451
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 return reconfig;
3453}
3454
3455status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3456{
3457 const size_t SIZE = 256;
3458 char buffer[SIZE];
3459 String8 result;
3460
3461 PlaybackThread::dumpInternals(fd, args);
3462
3463 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3464 result.append(buffer);
3465 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003466
3467 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3468 FastMixerDumpState copy = mFastMixerDumpState;
3469 copy.dump(fd);
3470
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003471 // Write the tee output to a .wav file
3472 NBAIO_Source *teeSource = mTeeSource.get();
3473 if (teeSource != NULL) {
3474 char teePath[64];
3475 struct timeval tv;
3476 gettimeofday(&tv, NULL);
3477 struct tm tm;
3478 localtime_r(&tv.tv_sec, &tm);
3479 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3480 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3481 if (teeFd >= 0) {
3482 char wavHeader[44];
3483 memcpy(wavHeader,
3484 "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",
3485 sizeof(wavHeader));
3486 NBAIO_Format format = teeSource->format();
3487 unsigned channelCount = Format_channelCount(format);
3488 ALOG_ASSERT(channelCount <= FCC_2);
3489 unsigned sampleRate = Format_sampleRate(format);
3490 wavHeader[22] = channelCount; // number of channels
3491 wavHeader[24] = sampleRate; // sample rate
3492 wavHeader[25] = sampleRate >> 8;
3493 wavHeader[32] = channelCount * 2; // block alignment
3494 write(teeFd, wavHeader, sizeof(wavHeader));
3495 size_t total = 0;
3496 bool firstRead = true;
3497 for (;;) {
3498#define TEE_SINK_READ 1024
3499 short buffer[TEE_SINK_READ * FCC_2];
3500 size_t count = TEE_SINK_READ;
3501 ssize_t actual = teeSource->read(buffer, count);
3502 bool wasFirstRead = firstRead;
3503 firstRead = false;
3504 if (actual <= 0) {
3505 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3506 continue;
3507 }
3508 break;
3509 }
3510 ALOG_ASSERT(actual <= count);
3511 write(teeFd, buffer, actual * channelCount * sizeof(short));
3512 total += actual;
3513 }
3514 lseek(teeFd, (off_t) 4, SEEK_SET);
3515 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3516 write(teeFd, &temp, sizeof(temp));
3517 lseek(teeFd, (off_t) 40, SEEK_SET);
3518 temp = total * channelCount * sizeof(short);
3519 write(teeFd, &temp, sizeof(temp));
3520 close(teeFd);
3521 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3522 } else {
3523 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3524 }
3525 }
3526
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 return NO_ERROR;
3528}
3529
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003530uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531{
Glenn Kasten58912562012-04-03 10:45:00 -07003532 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533}
3534
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003535uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003536{
Glenn Kasten58912562012-04-03 10:45:00 -07003537 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003538}
3539
Glenn Kasten66fcab92012-02-24 14:59:21 -08003540void AudioFlinger::MixerThread::cacheParameters_l()
3541{
3542 PlaybackThread::cacheParameters_l();
3543
3544 // FIXME: Relaxed timing because of a certain device that can't meet latency
3545 // Should be reduced to 2x after the vendor fixes the driver issue
3546 // increase threshold again due to low power audio mode. The way this warning
3547 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003548 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003549}
3550
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003552AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3553 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003554 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003555 // mLeftVolFloat, mRightVolFloat
3556 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003557{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558}
3559
3560AudioFlinger::DirectOutputThread::~DirectOutputThread()
3561{
3562}
3563
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003564AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3565 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003566)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003568 sp<Track> trackToRemove;
3569
Glenn Kastenfec279f2012-03-08 07:47:15 -08003570 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571
Glenn Kasten952eeb22012-03-06 11:30:57 -08003572 // find out which tracks need to be processed
3573 if (mActiveTracks.size() != 0) {
3574 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003575 // The track died recently
3576 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577
Glenn Kasten952eeb22012-03-06 11:30:57 -08003578 Track* const track = t.get();
3579 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580
Glenn Kasten952eeb22012-03-06 11:30:57 -08003581 // The first time a track is added we wait
3582 // for all its buffers to be filled before processing it
3583 if (cblk->framesReady() && track->isReady() &&
3584 !track->isPaused() && !track->isTerminated())
3585 {
3586 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587
Glenn Kasten952eeb22012-03-06 11:30:57 -08003588 if (track->mFillingUpStatus == Track::FS_FILLED) {
3589 track->mFillingUpStatus = Track::FS_ACTIVE;
3590 mLeftVolFloat = mRightVolFloat = 0;
3591 mLeftVolShort = mRightVolShort = 0;
3592 if (track->mState == TrackBase::RESUMING) {
3593 track->mState = TrackBase::ACTIVE;
3594 rampVolume = true;
3595 }
3596 } else if (cblk->server != 0) {
3597 // If the track is stopped before the first frame was mixed,
3598 // do not apply ramp
3599 rampVolume = true;
3600 }
3601 // compute volume for this track
3602 float left, right;
3603 if (track->isMuted() || mMasterMute || track->isPausing() ||
3604 mStreamTypes[track->streamType()].mute) {
3605 left = right = 0;
3606 if (track->isPausing()) {
3607 track->setPaused();
3608 }
3609 } else {
3610 float typeVolume = mStreamTypes[track->streamType()].volume;
3611 float v = mMasterVolume * typeVolume;
3612 uint32_t vlr = cblk->getVolumeLR();
3613 float v_clamped = v * (vlr & 0xFFFF);
3614 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3615 left = v_clamped/MAX_GAIN;
3616 v_clamped = v * (vlr >> 16);
3617 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3618 right = v_clamped/MAX_GAIN;
3619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620
Glenn Kasten952eeb22012-03-06 11:30:57 -08003621 if (left != mLeftVolFloat || right != mRightVolFloat) {
3622 mLeftVolFloat = left;
3623 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624
Glenn Kasten952eeb22012-03-06 11:30:57 -08003625 // If audio HAL implements volume control,
3626 // force software volume to nominal value
3627 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3628 left = 1.0f;
3629 right = 1.0f;
3630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631
Glenn Kasten952eeb22012-03-06 11:30:57 -08003632 // Convert volumes from float to 8.24
3633 uint32_t vl = (uint32_t)(left * (1 << 24));
3634 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635
Glenn Kasten952eeb22012-03-06 11:30:57 -08003636 // Delegate volume control to effect in track effect chain if needed
3637 // only one effect chain can be present on DirectOutputThread, so if
3638 // there is one, the track is connected to it
3639 if (!mEffectChains.isEmpty()) {
3640 // Do not ramp volume if volume is controlled by effect
3641 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 rampVolume = false;
3643 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003644 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645
Glenn Kasten952eeb22012-03-06 11:30:57 -08003646 // Convert volumes from 8.24 to 4.12 format
3647 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3648 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3649 leftVol = (uint16_t)v_clamped;
3650 v_clamped = (vr + (1 << 11)) >> 12;
3651 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3652 rightVol = (uint16_t)v_clamped;
3653 } else {
3654 leftVol = mLeftVolShort;
3655 rightVol = mRightVolShort;
3656 rampVolume = false;
3657 }
3658
3659 // reset retry count
3660 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003661 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003662 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003663 } else {
3664 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003665 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3666 // We have consumed all the buffers of this track.
3667 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003668 // TODO: implement behavior for compressed audio
3669 size_t audioHALFrames =
3670 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3671 size_t framesWritten =
3672 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3673 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003674 if (track->isStopped()) {
3675 track->reset();
3676 }
Eric Laurenta011e352012-03-29 15:51:43 -07003677 trackToRemove = track;
3678 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003679 } else {
3680 // No buffers for this track. Give it a few chances to
3681 // fill a buffer, then remove it from active list.
3682 if (--(track->mRetryCount) <= 0) {
3683 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3684 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003686 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687 }
3688 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 }
3690 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003692 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003693 // remove all the tracks that need to be...
3694 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003695 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003696 mActiveTracks.remove(trackToRemove);
3697 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003698 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003699 trackToRemove->sessionId());
3700 mEffectChains[0]->decActiveTrackCnt();
3701 }
3702 if (trackToRemove->isTerminated()) {
3703 removeTrack_l(trackToRemove);
3704 }
3705 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706
Glenn Kastenfec279f2012-03-08 07:47:15 -08003707 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003708}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709
Glenn Kasten000f0e32012-03-01 17:10:56 -08003710void AudioFlinger::DirectOutputThread::threadLoop_mix()
3711{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003712 AudioBufferProvider::Buffer buffer;
3713 size_t frameCount = mFrameCount;
3714 int8_t *curBuf = (int8_t *)mMixBuffer;
3715 // output audio to hardware
3716 while (frameCount) {
3717 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003718 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003719 if (CC_UNLIKELY(buffer.raw == NULL)) {
3720 memset(curBuf, 0, frameCount * mFrameSize);
3721 break;
3722 }
3723 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3724 frameCount -= buffer.frameCount;
3725 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003726 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003727 }
3728 sleepTime = 0;
3729 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003730 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003731
3732 // apply volume
3733
3734 // Do not apply volume on compressed audio
3735 if (!audio_is_linear_pcm(mFormat)) {
3736 return;
3737 }
3738
3739 // convert to signed 16 bit before volume calculation
3740 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3741 size_t count = mFrameCount * mChannelCount;
3742 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3743 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003744 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003745 *dst-- = (int16_t)(*src--^0x80) << 8;
3746 }
3747 }
3748
3749 frameCount = mFrameCount;
3750 int16_t *out = mMixBuffer;
3751 if (rampVolume) {
3752 if (mChannelCount == 1) {
3753 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3754 int32_t vlInc = d / (int32_t)frameCount;
3755 int32_t vl = ((int32_t)mLeftVolShort << 16);
3756 do {
3757 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3758 out++;
3759 vl += vlInc;
3760 } while (--frameCount);
3761
3762 } else {
3763 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3764 int32_t vlInc = d / (int32_t)frameCount;
3765 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3766 int32_t vrInc = d / (int32_t)frameCount;
3767 int32_t vl = ((int32_t)mLeftVolShort << 16);
3768 int32_t vr = ((int32_t)mRightVolShort << 16);
3769 do {
3770 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3771 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3772 out += 2;
3773 vl += vlInc;
3774 vr += vrInc;
3775 } while (--frameCount);
3776 }
3777 } else {
3778 if (mChannelCount == 1) {
3779 do {
3780 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3781 out++;
3782 } while (--frameCount);
3783 } else {
3784 do {
3785 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3786 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3787 out += 2;
3788 } while (--frameCount);
3789 }
3790 }
3791
3792 // convert back to unsigned 8 bit after volume calculation
3793 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3794 size_t count = mFrameCount * mChannelCount;
3795 int16_t *src = mMixBuffer;
3796 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003797 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003798 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3799 }
3800 }
3801
3802 mLeftVolShort = leftVol;
3803 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003804}
3805
3806void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3807{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003808 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003809 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003810 sleepTime = activeSleepTime;
3811 } else {
3812 sleepTime = idleSleepTime;
3813 }
3814 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003815 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003816 sleepTime = 0;
3817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818}
3819
3820// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003821int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822{
3823 return 0;
3824}
3825
3826// deleteTrackName_l() must be called with ThreadBase::mLock held
3827void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3828{
3829}
3830
3831// checkForNewParameters_l() must be called with ThreadBase::mLock held
3832bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3833{
3834 bool reconfig = false;
3835
3836 while (!mNewParameters.isEmpty()) {
3837 status_t status = NO_ERROR;
3838 String8 keyValuePair = mNewParameters[0];
3839 AudioParameter param = AudioParameter(keyValuePair);
3840 int value;
3841
3842 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3843 // do not accept frame count changes if tracks are open as the track buffer
3844 // size depends on frame count and correct behavior would not be garantied
3845 // if frame count is changed after track creation
3846 if (!mTracks.isEmpty()) {
3847 status = INVALID_OPERATION;
3848 } else {
3849 reconfig = true;
3850 }
3851 }
3852 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003853 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003854 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003855 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003856 mOutput->stream->common.standby(&mOutput->stream->common);
3857 mStandby = true;
3858 mBytesWritten = 0;
3859 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003860 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861 }
3862 if (status == NO_ERROR && reconfig) {
3863 readOutputParameters();
3864 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3865 }
3866 }
3867
3868 mNewParameters.removeAt(0);
3869
3870 mParamStatus = status;
3871 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003872 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3873 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003874 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875 }
3876 return reconfig;
3877}
3878
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003879uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880{
3881 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003882 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003883 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003884 } else {
3885 time = 10000;
3886 }
3887 return time;
3888}
3889
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003890uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891{
3892 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003893 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003894 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 } else {
3896 time = 10000;
3897 }
3898 return time;
3899}
3900
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003901uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003902{
3903 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003904 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003905 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3906 } else {
3907 time = 10000;
3908 }
3909 return time;
3910}
3911
Glenn Kasten66fcab92012-02-24 14:59:21 -08003912void AudioFlinger::DirectOutputThread::cacheParameters_l()
3913{
3914 PlaybackThread::cacheParameters_l();
3915
3916 // use shorter standby delay as on normal output to release
3917 // hardware resources as soon as possible
3918 standbyDelay = microseconds(activeSleepTime*2);
3919}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003920
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921// ----------------------------------------------------------------------------
3922
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003923AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003924 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003925 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3926 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928 addOutputTrack(mainThread);
3929}
3930
3931AudioFlinger::DuplicatingThread::~DuplicatingThread()
3932{
3933 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3934 mOutputTracks[i]->destroy();
3935 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936}
3937
Glenn Kasten000f0e32012-03-01 17:10:56 -08003938void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003940 // mix buffers...
3941 if (outputsReady(outputTracks)) {
3942 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3943 } else {
3944 memset(mMixBuffer, 0, mixBufferSize);
3945 }
3946 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003947 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003948}
3949
3950void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3951{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003952 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003953 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003954 sleepTime = activeSleepTime;
3955 } else {
3956 sleepTime = idleSleepTime;
3957 }
3958 } else if (mBytesWritten != 0) {
3959 // flush remaining overflow buffers in output tracks
3960 for (size_t i = 0; i < outputTracks.size(); i++) {
3961 if (outputTracks[i]->isActive()) {
3962 sleepTime = 0;
3963 writeFrames = 0;
3964 memset(mMixBuffer, 0, mixBufferSize);
3965 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003967 }
3968 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003969}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003970
Glenn Kasten000f0e32012-03-01 17:10:56 -08003971void AudioFlinger::DuplicatingThread::threadLoop_write()
3972{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003973 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003974 for (size_t i = 0; i < outputTracks.size(); i++) {
3975 outputTracks[i]->write(mMixBuffer, writeFrames);
3976 }
3977 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003978}
Glenn Kasten688a6402012-02-29 07:57:06 -08003979
Glenn Kasten000f0e32012-03-01 17:10:56 -08003980void AudioFlinger::DuplicatingThread::threadLoop_standby()
3981{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003982 // DuplicatingThread implements standby by stopping all tracks
3983 for (size_t i = 0; i < outputTracks.size(); i++) {
3984 outputTracks[i]->stop();
3985 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986}
3987
Glenn Kastenfa26a852012-03-06 11:28:04 -08003988void AudioFlinger::DuplicatingThread::saveOutputTracks()
3989{
3990 outputTracks = mOutputTracks;
3991}
3992
3993void AudioFlinger::DuplicatingThread::clearOutputTracks()
3994{
3995 outputTracks.clear();
3996}
3997
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3999{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004000 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004001 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004002 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004003 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004 this,
4005 mSampleRate,
4006 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004007 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 frameCount);
4009 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004010 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004012 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004013 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 }
4015}
4016
4017void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4018{
4019 Mutex::Autolock _l(mLock);
4020 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004021 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022 mOutputTracks[i]->destroy();
4023 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004024 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025 return;
4026 }
4027 }
Steve Block3856b092011-10-20 11:56:00 +01004028 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029}
4030
Glenn Kasten438b0362012-03-06 11:24:48 -08004031// caller must hold mLock
4032void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033{
4034 mWaitTimeMs = UINT_MAX;
4035 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4036 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004037 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4039 if (waitTimeMs < mWaitTimeMs) {
4040 mWaitTimeMs = waitTimeMs;
4041 }
4042 }
4043 }
4044}
4045
4046
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004047bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048{
4049 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004050 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004052 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053 return false;
4054 }
4055 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4056 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004057 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058 return false;
4059 }
4060 }
4061 return true;
4062}
4063
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004064uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065{
4066 return (mWaitTimeMs * 1000) / 2;
4067}
4068
Glenn Kasten66fcab92012-02-24 14:59:21 -08004069void AudioFlinger::DuplicatingThread::cacheParameters_l()
4070{
4071 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4072 updateWaitTime_l();
4073
4074 MixerThread::cacheParameters_l();
4075}
4076
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077// ----------------------------------------------------------------------------
4078
4079// TrackBase constructor must be called with AudioFlinger::mLock held
4080AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004081 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082 const sp<Client>& client,
4083 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004084 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004085 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087 const sp<IMemory>& sharedBuffer,
4088 int sessionId)
4089 : RefBase(),
4090 mThread(thread),
4091 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004092 mCblk(NULL),
4093 // mBuffer
4094 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095 mFrameCount(0),
4096 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004097 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004099 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004101 // mChannelCount
4102 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103{
Steve Block3856b092011-10-20 11:56:00 +01004104 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105
Steve Blockb8a80522011-12-20 16:23:08 +00004106 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004107 size_t size = sizeof(audio_track_cblk_t);
4108 uint8_t channelCount = popcount(channelMask);
4109 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4110 if (sharedBuffer == 0) {
4111 size += bufferSize;
4112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004114 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 mCblkMemory = client->heap()->allocate(size);
4116 if (mCblkMemory != 0) {
4117 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004118 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119 new(mCblk) audio_track_cblk_t();
4120 // clear all buffers
4121 mCblk->frameCount = frameCount;
4122 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004123// uncomment the following lines to quickly test 32-bit wraparound
4124// mCblk->user = 0xffff0000;
4125// mCblk->server = 0xffff0000;
4126// mCblk->userBase = 0xffff0000;
4127// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004128 mChannelCount = channelCount;
4129 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 if (sharedBuffer == 0) {
4131 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4132 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4133 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004134 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135 mCblk->flags = CBLK_UNDERRUN_ON;
4136 } else {
4137 mBuffer = sharedBuffer->pointer();
4138 }
4139 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4140 }
4141 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004142 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 client->heap()->dump("AudioTrack");
4144 return;
4145 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004146 } else {
4147 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004148 // construct the shared structure in-place.
4149 new(mCblk) audio_track_cblk_t();
4150 // clear all buffers
4151 mCblk->frameCount = frameCount;
4152 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004153// uncomment the following lines to quickly test 32-bit wraparound
4154// mCblk->user = 0xffff0000;
4155// mCblk->server = 0xffff0000;
4156// mCblk->userBase = 0xffff0000;
4157// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004158 mChannelCount = channelCount;
4159 mChannelMask = channelMask;
4160 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4161 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4162 // Force underrun condition to avoid false underrun callback until first data is
4163 // written to buffer (other flags are cleared)
4164 mCblk->flags = CBLK_UNDERRUN_ON;
4165 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167}
4168
4169AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4170{
Glenn Kastena0d68332012-01-27 16:47:15 -08004171 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004172 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004174 } else {
4175 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 }
4177 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004178 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004179 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004180 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004182 // If the client's reference count drops to zero, the associated destructor
4183 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4184 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185 mClient.clear();
4186 }
4187}
4188
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004189// AudioBufferProvider interface
4190// getNextBuffer() = 0;
4191// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4193{
Glenn Kastene0feee32011-12-13 11:53:26 -08004194 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004196 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004197 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 buffer->frameCount = 0;
4199}
4200
4201bool AudioFlinger::ThreadBase::TrackBase::step() {
4202 bool result;
4203 audio_track_cblk_t* cblk = this->cblk();
4204
4205 result = cblk->stepServer(mFrameCount);
4206 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004207 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004208 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209 }
4210 return result;
4211}
4212
4213void AudioFlinger::ThreadBase::TrackBase::reset() {
4214 audio_track_cblk_t* cblk = this->cblk();
4215
4216 cblk->user = 0;
4217 cblk->server = 0;
4218 cblk->userBase = 0;
4219 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004220 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004221 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222}
4223
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4225 return (int)mCblk->sampleRate;
4226}
4227
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4229 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004230 size_t frameSize = cblk->frameSize;
4231 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4232 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233
4234 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004235 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4236 "TrackBase::getBuffer buffer out of range:\n"
4237 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4238 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004240 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
4242 return bufferStart;
4243}
4244
Eric Laurenta011e352012-03-29 15:51:43 -07004245status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4246{
4247 mSyncEvents.add(event);
4248 return NO_ERROR;
4249}
4250
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251// ----------------------------------------------------------------------------
4252
4253// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4254AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004255 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004257 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004259 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004260 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 int frameCount,
4262 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004263 int sessionId,
4264 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004265 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004266 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004267 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004268 // mRetryCount initialized later when needed
4269 mSharedBuffer(sharedBuffer),
4270 mStreamType(streamType),
4271 mName(-1), // see note below
4272 mMainBuffer(thread->mixBuffer()),
4273 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004274 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004275 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004276 mFlags(flags),
4277 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004278 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004279 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280{
4281 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4283 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004284 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004285 if (flags & IAudioFlinger::TRACK_FAST) {
4286 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4287 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4288 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004289 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004290 // FIXME This is too eager. We allocate a fast track index before the
4291 // fast track becomes active. Since fast tracks are a scarce resource,
4292 // this means we are potentially denying other more important fast tracks from
4293 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004294 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004295 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004296 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004297 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004298 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004299 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004300 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004301 if (mName < 0) {
4302 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004303 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4304 // then we leak a fast track index. Should swap these two sections, or better yet
4305 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004308 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309}
4310
4311AudioFlinger::PlaybackThread::Track::~Track()
4312{
Steve Block3856b092011-10-20 11:56:00 +01004313 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 sp<ThreadBase> thread = mThread.promote();
4315 if (thread != 0) {
4316 Mutex::Autolock _l(thread->mLock);
4317 mState = TERMINATED;
4318 }
4319}
4320
4321void AudioFlinger::PlaybackThread::Track::destroy()
4322{
4323 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4324 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004325 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 // we must acquire a strong reference on this Track before locking mLock
4327 // here so that the destructor is called only when exiting this function.
4328 // On the other hand, as long as Track::destroy() is only called by
4329 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4330 // this Track with its member mTrack.
4331 sp<Track> keep(this);
4332 { // scope for mLock
4333 sp<ThreadBase> thread = mThread.promote();
4334 if (thread != 0) {
4335 if (!isOutputTrack()) {
4336 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004337 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004338
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004339#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004340 // to track the speaker usage
4341 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004342#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343 }
4344 AudioSystem::releaseOutput(thread->id());
4345 }
4346 Mutex::Autolock _l(thread->mLock);
4347 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4348 playbackThread->destroyTrack_l(this);
4349 }
4350 }
4351}
4352
Glenn Kasten288ed212012-04-25 17:52:27 -07004353/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4354{
Glenn Kastene213c862012-04-25 13:46:15 -07004355 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4356 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004357}
4358
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4360{
Glenn Kasten83d86532012-01-17 14:39:34 -08004361 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004362 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004363 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004364 } else {
4365 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4366 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004367 track_state state = mState;
4368 char stateChar;
4369 switch (state) {
4370 case IDLE:
4371 stateChar = 'I';
4372 break;
4373 case TERMINATED:
4374 stateChar = 'T';
4375 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004376 case STOPPING_1:
4377 stateChar = 's';
4378 break;
4379 case STOPPING_2:
4380 stateChar = '5';
4381 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004382 case STOPPED:
4383 stateChar = 'S';
4384 break;
4385 case RESUMING:
4386 stateChar = 'R';
4387 break;
4388 case ACTIVE:
4389 stateChar = 'A';
4390 break;
4391 case PAUSING:
4392 stateChar = 'p';
4393 break;
4394 case PAUSED:
4395 stateChar = 'P';
4396 break;
Eric Laurent29864602012-05-08 18:57:51 -07004397 case FLUSHED:
4398 stateChar = 'F';
4399 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004400 default:
4401 stateChar = '?';
4402 break;
4403 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004404 char nowInUnderrun;
4405 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4406 case UNDERRUN_FULL:
4407 nowInUnderrun = ' ';
4408 break;
4409 case UNDERRUN_PARTIAL:
4410 nowInUnderrun = '<';
4411 break;
4412 case UNDERRUN_EMPTY:
4413 nowInUnderrun = '*';
4414 break;
4415 default:
4416 nowInUnderrun = '?';
4417 break;
4418 }
Glenn Kastene213c862012-04-25 13:46:15 -07004419 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4420 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004421 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 mStreamType,
4423 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004424 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 mSessionId,
4426 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004427 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004428 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 mMute,
4430 mFillingUpStatus,
4431 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004432 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4433 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 mCblk->server,
4435 mCblk->user,
4436 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004437 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004438 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004439 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004440 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441}
4442
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004443// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004444status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004445 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004447 audio_track_cblk_t* cblk = this->cblk();
4448 uint32_t framesReady;
4449 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004451 // Check if last stepServer failed, try to step now
4452 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004453 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4454 // Since the fast mixer is higher priority than client callback thread,
4455 // it does not result in priority inversion for client.
4456 // But a non-blocking solution would be preferable to avoid
4457 // fast mixer being unable to tryLock(), and
4458 // to avoid the extra context switches if the client wakes up,
4459 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004460 if (!step()) goto getNextBuffer_exit;
4461 ALOGV("stepServer recovered");
4462 mStepServerFailed = false;
4463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464
Glenn Kasten288ed212012-04-25 17:52:27 -07004465 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004466 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004468 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004469 uint32_t s = cblk->server;
4470 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4471
4472 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4473 if (framesReq > framesReady) {
4474 framesReq = framesReady;
4475 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004476 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477 framesReq = bufferEnd - s;
4478 }
4479
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004480 buffer->raw = getBuffer(s, framesReq);
4481 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004483 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486
4487getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004488 buffer->raw = NULL;
4489 buffer->frameCount = 0;
4490 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4491 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492}
4493
Glenn Kasten288ed212012-04-25 17:52:27 -07004494// Note that framesReady() takes a mutex on the control block using tryLock().
4495// This could result in priority inversion if framesReady() is called by the normal mixer,
4496// as the normal mixer thread runs at lower
4497// priority than the client's callback thread: there is a short window within framesReady()
4498// during which the normal mixer could be preempted, and the client callback would block.
4499// Another problem can occur if framesReady() is called by the fast mixer:
4500// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4501// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4502size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004503 return mCblk->framesReady();
4504}
4505
Glenn Kasten288ed212012-04-25 17:52:27 -07004506// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004508 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509
John Grossman4ff14ba2012-02-08 16:37:41 -08004510 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4512 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004513 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 return true;
4515 }
4516 return false;
4517}
4518
Glenn Kasten3acbd052012-02-28 10:39:56 -08004519status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004520 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521{
4522 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004523 ALOGV("start(%d), calling pid %d session %d",
4524 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004525
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 sp<ThreadBase> thread = mThread.promote();
4527 if (thread != 0) {
4528 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004529 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 // here the track could be either new, or restarted
4531 // in both cases "unstop" the track
4532 if (mState == PAUSED) {
4533 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004534 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 } else {
4536 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004537 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 }
4539
4540 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4541 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004542 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004544
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004545#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004546 // to track the speaker usage
4547 if (status == NO_ERROR) {
4548 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4549 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004550#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 }
4552 if (status == NO_ERROR) {
4553 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4554 playbackThread->addTrack_l(this);
4555 } else {
4556 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004557 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558 }
4559 } else {
4560 status = BAD_VALUE;
4561 }
4562 return status;
4563}
4564
4565void AudioFlinger::PlaybackThread::Track::stop()
4566{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004567 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 sp<ThreadBase> thread = mThread.promote();
4569 if (thread != 0) {
4570 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004571 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004572 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 // If the track is not active (PAUSED and buffers full), flush buffers
4574 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4575 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4576 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004577 mState = STOPPED;
4578 } else if (!isFastTrack()) {
4579 mState = STOPPED;
4580 } else {
4581 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4582 // and then to STOPPED and reset() when presentation is complete
4583 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004585 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 }
4587 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4588 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004589 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004591
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004592#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004593 // to track the speaker usage
4594 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004595#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 }
4597 }
4598}
4599
4600void AudioFlinger::PlaybackThread::Track::pause()
4601{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004602 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 sp<ThreadBase> thread = mThread.promote();
4604 if (thread != 0) {
4605 Mutex::Autolock _l(thread->mLock);
4606 if (mState == ACTIVE || mState == RESUMING) {
4607 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004608 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609 if (!isOutputTrack()) {
4610 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004611 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004613
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004614#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004615 // to track the speaker usage
4616 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004617#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004618 }
4619 }
4620 }
4621}
4622
4623void AudioFlinger::PlaybackThread::Track::flush()
4624{
Steve Block3856b092011-10-20 11:56:00 +01004625 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004626 sp<ThreadBase> thread = mThread.promote();
4627 if (thread != 0) {
4628 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004629 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4630 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 return;
4632 }
4633 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004634 // FLUSHED state
4635 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004636 // do not reset the track if it is still in the process of being stopped or paused.
4637 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004638 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004639 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004640 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4641 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4642 reset();
4643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644 }
4645}
4646
4647void AudioFlinger::PlaybackThread::Track::reset()
4648{
4649 // Do not reset twice to avoid discarding data written just after a flush and before
4650 // the audioflinger thread detects the track is stopped.
4651 if (!mResetDone) {
4652 TrackBase::reset();
4653 // Force underrun condition to avoid false underrun callback until first data is
4654 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004655 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4656 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 mFillingUpStatus = FS_FILLING;
4658 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004659 if (mState == FLUSHED) {
4660 mState = IDLE;
4661 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 }
4663}
4664
4665void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4666{
4667 mMute = muted;
4668}
4669
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4671{
4672 status_t status = DEAD_OBJECT;
4673 sp<ThreadBase> thread = mThread.promote();
4674 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004675 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4676 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 }
4678 return status;
4679}
4680
4681void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4682{
4683 mAuxEffectId = EffectId;
4684 mAuxBuffer = buffer;
4685}
4686
Eric Laurenta011e352012-03-29 15:51:43 -07004687bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4688 size_t audioHalFrames)
4689{
4690 // a track is considered presented when the total number of frames written to audio HAL
4691 // corresponds to the number of frames written when presentationComplete() is called for the
4692 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4693 if (mPresentationCompleteFrames == 0) {
4694 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4695 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4696 mPresentationCompleteFrames, audioHalFrames);
4697 }
4698 if (framesWritten >= mPresentationCompleteFrames) {
4699 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4700 mSessionId, framesWritten);
4701 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004702 return true;
4703 }
4704 return false;
4705}
4706
4707void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4708{
4709 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4710 if (mSyncEvents[i]->type() == type) {
4711 mSyncEvents[i]->trigger();
4712 mSyncEvents.removeAt(i);
4713 i--;
4714 }
4715 }
4716}
4717
Glenn Kasten58912562012-04-03 10:45:00 -07004718// implement VolumeBufferProvider interface
4719
4720uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4721{
4722 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4723 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4724 uint32_t vlr = mCblk->getVolumeLR();
4725 uint32_t vl = vlr & 0xFFFF;
4726 uint32_t vr = vlr >> 16;
4727 // track volumes come from shared memory, so can't be trusted and must be clamped
4728 if (vl > MAX_GAIN_INT) {
4729 vl = MAX_GAIN_INT;
4730 }
4731 if (vr > MAX_GAIN_INT) {
4732 vr = MAX_GAIN_INT;
4733 }
4734 // now apply the cached master volume and stream type volume;
4735 // this is trusted but lacks any synchronization or barrier so may be stale
4736 float v = mCachedVolume;
4737 vl *= v;
4738 vr *= v;
4739 // re-combine into U4.16
4740 vlr = (vr << 16) | (vl & 0xFFFF);
4741 // FIXME look at mute, pause, and stop flags
4742 return vlr;
4743}
Eric Laurenta011e352012-03-29 15:51:43 -07004744
Eric Laurent29864602012-05-08 18:57:51 -07004745status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4746{
4747 if (mState == TERMINATED || mState == PAUSED ||
4748 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4749 (mState == STOPPED)))) {
4750 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4751 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4752 event->cancel();
4753 return INVALID_OPERATION;
4754 }
4755 TrackBase::setSyncEvent(event);
4756 return NO_ERROR;
4757}
4758
John Grossman4ff14ba2012-02-08 16:37:41 -08004759// timed audio tracks
4760
4761sp<AudioFlinger::PlaybackThread::TimedTrack>
4762AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004763 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004764 const sp<Client>& client,
4765 audio_stream_type_t streamType,
4766 uint32_t sampleRate,
4767 audio_format_t format,
4768 uint32_t channelMask,
4769 int frameCount,
4770 const sp<IMemory>& sharedBuffer,
4771 int sessionId) {
4772 if (!client->reserveTimedTrack())
4773 return NULL;
4774
Glenn Kastena0356762012-03-19 10:38:51 -07004775 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004776 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4777 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004778}
4779
4780AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004781 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004782 const sp<Client>& client,
4783 audio_stream_type_t streamType,
4784 uint32_t sampleRate,
4785 audio_format_t format,
4786 uint32_t channelMask,
4787 int frameCount,
4788 const sp<IMemory>& sharedBuffer,
4789 int sessionId)
4790 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004791 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004792 mQueueHeadInFlight(false),
4793 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004794 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004795 mTimedSilenceBuffer(NULL),
4796 mTimedSilenceBufferSize(0),
4797 mTimedAudioOutputOnTime(false),
4798 mMediaTimeTransformValid(false)
4799{
4800 LocalClock lc;
4801 mLocalTimeFreq = lc.getLocalFreq();
4802
4803 mLocalTimeToSampleTransform.a_zero = 0;
4804 mLocalTimeToSampleTransform.b_zero = 0;
4805 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4806 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4807 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4808 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004809
4810 mMediaTimeToSampleTransform.a_zero = 0;
4811 mMediaTimeToSampleTransform.b_zero = 0;
4812 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4813 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4814 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4815 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004816}
4817
4818AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4819 mClient->releaseTimedTrack();
4820 delete [] mTimedSilenceBuffer;
4821}
4822
4823status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4824 size_t size, sp<IMemory>* buffer) {
4825
4826 Mutex::Autolock _l(mTimedBufferQueueLock);
4827
4828 trimTimedBufferQueue_l();
4829
4830 // lazily initialize the shared memory heap for timed buffers
4831 if (mTimedMemoryDealer == NULL) {
4832 const int kTimedBufferHeapSize = 512 << 10;
4833
4834 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4835 "AudioFlingerTimed");
4836 if (mTimedMemoryDealer == NULL)
4837 return NO_MEMORY;
4838 }
4839
4840 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4841 if (newBuffer == NULL) {
4842 newBuffer = mTimedMemoryDealer->allocate(size);
4843 if (newBuffer == NULL)
4844 return NO_MEMORY;
4845 }
4846
4847 *buffer = newBuffer;
4848 return NO_ERROR;
4849}
4850
4851// caller must hold mTimedBufferQueueLock
4852void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4853 int64_t mediaTimeNow;
4854 {
4855 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4856 if (!mMediaTimeTransformValid)
4857 return;
4858
4859 int64_t targetTimeNow;
4860 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4861 ? mCCHelper.getCommonTime(&targetTimeNow)
4862 : mCCHelper.getLocalTime(&targetTimeNow);
4863
4864 if (OK != res)
4865 return;
4866
4867 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4868 &mediaTimeNow)) {
4869 return;
4870 }
4871 }
4872
John Grossman1c345192012-03-27 14:00:17 -07004873 size_t trimEnd;
4874 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004875 int64_t bufEnd;
4876
John Grossmanc95cfbb2012-04-12 11:53:11 -07004877 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4878 // We have a next buffer. Just use its PTS as the PTS of the frame
4879 // following the last frame in this buffer. If the stream is sparse
4880 // (ie, there are deliberate gaps left in the stream which should be
4881 // filled with silence by the TimedAudioTrack), then this can result
4882 // in one extra buffer being left un-trimmed when it could have
4883 // been. In general, this is not typical, and we would rather
4884 // optimized away the TS calculation below for the more common case
4885 // where PTSes are contiguous.
4886 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4887 } else {
4888 // We have no next buffer. Compute the PTS of the frame following
4889 // the last frame in this buffer by computing the duration of of
4890 // this frame in media time units and adding it to the PTS of the
4891 // buffer.
4892 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4893 / mCblk->frameSize;
4894
4895 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4896 &bufEnd)) {
4897 ALOGE("Failed to convert frame count of %lld to media time"
4898 " duration" " (scale factor %d/%u) in %s",
4899 frameCount,
4900 mMediaTimeToSampleTransform.a_to_b_numer,
4901 mMediaTimeToSampleTransform.a_to_b_denom,
4902 __PRETTY_FUNCTION__);
4903 break;
4904 }
4905 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004906 }
John Grossman9fbdee12012-03-26 17:51:46 -07004907
4908 if (bufEnd > mediaTimeNow)
4909 break;
4910
4911 // Is the buffer we want to use in the middle of a mix operation right
4912 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4913 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004914 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004915 mTrimQueueHeadOnRelease = true;
4916 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004917 }
4918
John Grossman9fbdee12012-03-26 17:51:46 -07004919 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004920 if (trimStart < trimEnd) {
4921 // Update the bookkeeping for framesReady()
4922 for (size_t i = trimStart; i < trimEnd; ++i) {
4923 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4924 }
4925
4926 // Now actually remove the buffers from the queue.
4927 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004928 }
4929}
4930
John Grossman1c345192012-03-27 14:00:17 -07004931void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4932 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004933 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4934 "%s called (reason \"%s\"), but timed buffer queue has no"
4935 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004936
4937 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4938 mTimedBufferQueue.removeAt(0);
4939}
4940
4941void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4942 const TimedBuffer& buf,
4943 const char* logTag) {
4944 uint32_t bufBytes = buf.buffer()->size();
4945 uint32_t consumedAlready = buf.position();
4946
Eric Laurentb388e532012-04-14 13:32:48 -07004947 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004948 "Bad bookkeeping while updating frames pending. Timed buffer is"
4949 " only %u bytes long, but claims to have consumed %u"
4950 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004951 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004952
4953 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004954 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4955 "Bad bookkeeping while updating frames pending. Should have at"
4956 " least %u queued frames, but we think we have only %u. (update"
4957 " reason: \"%s\")",
4958 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004959
4960 mFramesPendingInQueue -= bufFrames;
4961}
4962
John Grossman4ff14ba2012-02-08 16:37:41 -08004963status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4964 const sp<IMemory>& buffer, int64_t pts) {
4965
4966 {
4967 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4968 if (!mMediaTimeTransformValid)
4969 return INVALID_OPERATION;
4970 }
4971
4972 Mutex::Autolock _l(mTimedBufferQueueLock);
4973
John Grossman1c345192012-03-27 14:00:17 -07004974 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4975 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004976 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4977
4978 return NO_ERROR;
4979}
4980
4981status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4982 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4983
John Grossman1c345192012-03-27 14:00:17 -07004984 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4985 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4986 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004987
4988 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4989 target == TimedAudioTrack::COMMON_TIME)) {
4990 return BAD_VALUE;
4991 }
4992
4993 Mutex::Autolock lock(mMediaTimeTransformLock);
4994 mMediaTimeTransform = xform;
4995 mMediaTimeTransformTarget = target;
4996 mMediaTimeTransformValid = true;
4997
4998 return NO_ERROR;
4999}
5000
5001#define min(a, b) ((a) < (b) ? (a) : (b))
5002
5003// implementation of getNextBuffer for tracks whose buffers have timestamps
5004status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5005 AudioBufferProvider::Buffer* buffer, int64_t pts)
5006{
5007 if (pts == AudioBufferProvider::kInvalidPTS) {
5008 buffer->raw = 0;
5009 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005010 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005011 return INVALID_OPERATION;
5012 }
5013
John Grossman4ff14ba2012-02-08 16:37:41 -08005014 Mutex::Autolock _l(mTimedBufferQueueLock);
5015
John Grossman9fbdee12012-03-26 17:51:46 -07005016 ALOG_ASSERT(!mQueueHeadInFlight,
5017 "getNextBuffer called without releaseBuffer!");
5018
John Grossman4ff14ba2012-02-08 16:37:41 -08005019 while (true) {
5020
5021 // if we have no timed buffers, then fail
5022 if (mTimedBufferQueue.isEmpty()) {
5023 buffer->raw = 0;
5024 buffer->frameCount = 0;
5025 return NOT_ENOUGH_DATA;
5026 }
5027
5028 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5029
5030 // calculate the PTS of the head of the timed buffer queue expressed in
5031 // local time
5032 int64_t headLocalPTS;
5033 {
5034 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5035
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005036 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005037
5038 if (mMediaTimeTransform.a_to_b_denom == 0) {
5039 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005040 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005041 return NO_ERROR;
5042 }
5043
5044 int64_t transformedPTS;
5045 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5046 &transformedPTS)) {
5047 // the transform failed. this shouldn't happen, but if it does
5048 // then just drop this buffer
5049 ALOGW("timedGetNextBuffer transform failed");
5050 buffer->raw = 0;
5051 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005052 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005053 return NO_ERROR;
5054 }
5055
5056 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5057 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5058 &headLocalPTS)) {
5059 buffer->raw = 0;
5060 buffer->frameCount = 0;
5061 return INVALID_OPERATION;
5062 }
5063 } else {
5064 headLocalPTS = transformedPTS;
5065 }
5066 }
5067
5068 // adjust the head buffer's PTS to reflect the portion of the head buffer
5069 // that has already been consumed
5070 int64_t effectivePTS = headLocalPTS +
5071 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5072
5073 // Calculate the delta in samples between the head of the input buffer
5074 // queue and the start of the next output buffer that will be written.
5075 // If the transformation fails because of over or underflow, it means
5076 // that the sample's position in the output stream is so far out of
5077 // whack that it should just be dropped.
5078 int64_t sampleDelta;
5079 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5080 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005081 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5082 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005083 continue;
5084 }
5085 if (!mLocalTimeToSampleTransform.doForwardTransform(
5086 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005087 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005088 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005089 continue;
5090 }
5091
John Grossman1c345192012-03-27 14:00:17 -07005092 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5093 " sampleDelta=[%d.%08x]",
5094 head.pts(), head.position(), pts,
5095 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5096 + (sampleDelta >> 32)),
5097 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005098
5099 // if the delta between the ideal placement for the next input sample and
5100 // the current output position is within this threshold, then we will
5101 // concatenate the next input samples to the previous output
5102 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005103 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005104
5105 // if this is the first buffer of audio that we're emitting from this track
5106 // then it should be almost exactly on time.
5107 const int64_t kSampleStartupThreshold = 1LL << 32;
5108
5109 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005110 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005111 // the next input is close enough to being on time, so concatenate it
5112 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005113 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005114
John Grossman1c345192012-03-27 14:00:17 -07005115 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5116 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005117 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005118 }
5119
5120 // Looks like our output is not on time. Reset our on timed status.
5121 // Next time we mix samples from our input queue, then should be within
5122 // the StartupThreshold.
5123 mTimedAudioOutputOnTime = false;
5124 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005125 // the gap between the current output position and the proper start of
5126 // the next input sample is too big, so fill it with silence
5127 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5128
John Grossman9fbdee12012-03-26 17:51:46 -07005129 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005130 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5131 return NO_ERROR;
5132 } else {
5133 // the next input sample is late
5134 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5135 size_t onTimeSamplePosition =
5136 head.position() + lateFrames * mCblk->frameSize;
5137
5138 if (onTimeSamplePosition > head.buffer()->size()) {
5139 // all the remaining samples in the head are too late, so
5140 // drop it and move on
5141 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005142 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005143 continue;
5144 } else {
5145 // skip over the late samples
5146 head.setPosition(onTimeSamplePosition);
5147
5148 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005149 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005150
5151 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5152 return NO_ERROR;
5153 }
5154 }
5155 }
5156}
5157
5158// Yield samples from the timed buffer queue head up to the given output
5159// buffer's capacity.
5160//
5161// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005162void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005163 AudioBufferProvider::Buffer* buffer) {
5164
5165 const TimedBuffer& head = mTimedBufferQueue[0];
5166
5167 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5168 head.position());
5169
5170 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5171 mCblk->frameSize);
5172 size_t framesRequested = buffer->frameCount;
5173 buffer->frameCount = min(framesLeftInHead, framesRequested);
5174
John Grossman9fbdee12012-03-26 17:51:46 -07005175 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005176 mTimedAudioOutputOnTime = true;
5177}
5178
5179// Yield samples of silence up to the given output buffer's capacity
5180//
5181// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005182void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005183 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5184
5185 // lazily allocate a buffer filled with silence
5186 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5187 delete [] mTimedSilenceBuffer;
5188 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5189 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5190 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5191 }
5192
5193 buffer->raw = mTimedSilenceBuffer;
5194 size_t framesRequested = buffer->frameCount;
5195 buffer->frameCount = min(numFrames, framesRequested);
5196
5197 mTimedAudioOutputOnTime = false;
5198}
5199
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005200// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005201void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5202 AudioBufferProvider::Buffer* buffer) {
5203
5204 Mutex::Autolock _l(mTimedBufferQueueLock);
5205
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005206 // If the buffer which was just released is part of the buffer at the head
5207 // of the queue, be sure to update the amt of the buffer which has been
5208 // consumed. If the buffer being returned is not part of the head of the
5209 // queue, its either because the buffer is part of the silence buffer, or
5210 // because the head of the timed queue was trimmed after the mixer called
5211 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005212 if (buffer->raw == mTimedSilenceBuffer) {
5213 ALOG_ASSERT(!mQueueHeadInFlight,
5214 "Queue head in flight during release of silence buffer!");
5215 goto done;
5216 }
5217
5218 ALOG_ASSERT(mQueueHeadInFlight,
5219 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5220 " head in flight.");
5221
5222 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005223 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005224
5225 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005226 void* end = reinterpret_cast<void*>(
5227 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5228 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005229
John Grossman9fbdee12012-03-26 17:51:46 -07005230 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5231 "released buffer not within the head of the timed buffer"
5232 " queue; qHead = [%p, %p], released buffer = %p",
5233 start, end, buffer->raw);
5234
5235 head.setPosition(head.position() +
5236 (buffer->frameCount * mCblk->frameSize));
5237 mQueueHeadInFlight = false;
5238
John Grossman1c345192012-03-27 14:00:17 -07005239 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5240 "Bad bookkeeping during releaseBuffer! Should have at"
5241 " least %u queued frames, but we think we have only %u",
5242 buffer->frameCount, mFramesPendingInQueue);
5243
5244 mFramesPendingInQueue -= buffer->frameCount;
5245
John Grossman9fbdee12012-03-26 17:51:46 -07005246 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5247 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005248 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005249 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005250 }
John Grossman9fbdee12012-03-26 17:51:46 -07005251 } else {
5252 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5253 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005254 }
5255
John Grossman9fbdee12012-03-26 17:51:46 -07005256done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005257 buffer->raw = 0;
5258 buffer->frameCount = 0;
5259}
5260
Glenn Kasten288ed212012-04-25 17:52:27 -07005261size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005262 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005263 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005264}
5265
5266AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5267 : mPTS(0), mPosition(0) {}
5268
5269AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5270 const sp<IMemory>& buffer, int64_t pts)
5271 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5272
Mathias Agopian65ab4712010-07-14 17:59:35 -07005273// ----------------------------------------------------------------------------
5274
5275// RecordTrack constructor must be called with AudioFlinger::mLock held
5276AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005277 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005278 const sp<Client>& client,
5279 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005280 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005281 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005283 int sessionId)
5284 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005285 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005286 mOverflow(false)
5287{
5288 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005289 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5290 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5291 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5292 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5293 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5294 } else {
5295 mCblk->frameSize = sizeof(int8_t);
5296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297 }
5298}
5299
5300AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5301{
5302 sp<ThreadBase> thread = mThread.promote();
5303 if (thread != 0) {
5304 AudioSystem::releaseInput(thread->id());
5305 }
5306}
5307
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005308// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005309status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005310{
5311 audio_track_cblk_t* cblk = this->cblk();
5312 uint32_t framesAvail;
5313 uint32_t framesReq = buffer->frameCount;
5314
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005315 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005316 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005318 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005319 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320 }
5321
5322 framesAvail = cblk->framesAvailable_l();
5323
Glenn Kastenf6b16782011-12-15 09:51:17 -08005324 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 uint32_t s = cblk->server;
5326 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5327
5328 if (framesReq > framesAvail) {
5329 framesReq = framesAvail;
5330 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005331 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332 framesReq = bufferEnd - s;
5333 }
5334
5335 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005336 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337
5338 buffer->frameCount = framesReq;
5339 return NO_ERROR;
5340 }
5341
5342getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005343 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 buffer->frameCount = 0;
5345 return NOT_ENOUGH_DATA;
5346}
5347
Glenn Kasten3acbd052012-02-28 10:39:56 -08005348status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005349 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350{
5351 sp<ThreadBase> thread = mThread.promote();
5352 if (thread != 0) {
5353 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005354 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355 } else {
5356 return BAD_VALUE;
5357 }
5358}
5359
5360void AudioFlinger::RecordThread::RecordTrack::stop()
5361{
5362 sp<ThreadBase> thread = mThread.promote();
5363 if (thread != 0) {
5364 RecordThread *recordThread = (RecordThread *)thread.get();
5365 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005366 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005367 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005368 // read from buffer
5369 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370 }
5371}
5372
5373void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5374{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005375 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005376 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005378 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 mSessionId,
5380 mFrameCount,
5381 mState,
5382 mCblk->sampleRate,
5383 mCblk->server,
5384 mCblk->user);
5385}
5386
5387
5388// ----------------------------------------------------------------------------
5389
5390AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005391 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 DuplicatingThread *sourceThread,
5393 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005394 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005395 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005397 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5398 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 mActive(false), mSourceThread(sourceThread)
5400{
5401
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402 if (mCblk != NULL) {
5403 mCblk->flags |= CBLK_DIRECTION_OUT;
5404 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405 mOutBuffer.frameCount = 0;
5406 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005407 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005408 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5409 mCblk, mBuffer, mCblk->buffers,
5410 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005412 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 }
5414}
5415
5416AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5417{
5418 clearBufferQueue();
5419}
5420
Glenn Kasten3acbd052012-02-28 10:39:56 -08005421status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005422 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005424 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 if (status != NO_ERROR) {
5426 return status;
5427 }
5428
5429 mActive = true;
5430 mRetryCount = 127;
5431 return status;
5432}
5433
5434void AudioFlinger::PlaybackThread::OutputTrack::stop()
5435{
5436 Track::stop();
5437 clearBufferQueue();
5438 mOutBuffer.frameCount = 0;
5439 mActive = false;
5440}
5441
5442bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5443{
5444 Buffer *pInBuffer;
5445 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005446 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447 bool outputBufferFull = false;
5448 inBuffer.frameCount = frames;
5449 inBuffer.i16 = data;
5450
5451 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5452
5453 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005454 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 sp<ThreadBase> thread = mThread.promote();
5456 if (thread != 0) {
5457 MixerThread *mixerThread = (MixerThread *)thread.get();
5458 if (mCblk->frameCount > frames){
5459 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5460 uint32_t startFrames = (mCblk->frameCount - frames);
5461 pInBuffer = new Buffer;
5462 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5463 pInBuffer->frameCount = startFrames;
5464 pInBuffer->i16 = pInBuffer->mBuffer;
5465 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5466 mBufferQueue.add(pInBuffer);
5467 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005468 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 }
5470 }
5471 }
5472 }
5473
5474 while (waitTimeLeftMs) {
5475 // First write pending buffers, then new data
5476 if (mBufferQueue.size()) {
5477 pInBuffer = mBufferQueue.itemAt(0);
5478 } else {
5479 pInBuffer = &inBuffer;
5480 }
5481
5482 if (pInBuffer->frameCount == 0) {
5483 break;
5484 }
5485
5486 if (mOutBuffer.frameCount == 0) {
5487 mOutBuffer.frameCount = pInBuffer->frameCount;
5488 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005489 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005490 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 outputBufferFull = true;
5492 break;
5493 }
5494 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5495 if (waitTimeLeftMs >= waitTimeMs) {
5496 waitTimeLeftMs -= waitTimeMs;
5497 } else {
5498 waitTimeLeftMs = 0;
5499 }
5500 }
5501
5502 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5503 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5504 mCblk->stepUser(outFrames);
5505 pInBuffer->frameCount -= outFrames;
5506 pInBuffer->i16 += outFrames * channelCount;
5507 mOutBuffer.frameCount -= outFrames;
5508 mOutBuffer.i16 += outFrames * channelCount;
5509
5510 if (pInBuffer->frameCount == 0) {
5511 if (mBufferQueue.size()) {
5512 mBufferQueue.removeAt(0);
5513 delete [] pInBuffer->mBuffer;
5514 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005515 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 } else {
5517 break;
5518 }
5519 }
5520 }
5521
5522 // If we could not write all frames, allocate a buffer and queue it for next time.
5523 if (inBuffer.frameCount) {
5524 sp<ThreadBase> thread = mThread.promote();
5525 if (thread != 0 && !thread->standby()) {
5526 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5527 pInBuffer = new Buffer;
5528 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5529 pInBuffer->frameCount = inBuffer.frameCount;
5530 pInBuffer->i16 = pInBuffer->mBuffer;
5531 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5532 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005533 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005535 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 }
5537 }
5538 }
5539
5540 // Calling write() with a 0 length buffer, means that no more data will be written:
5541 // If no more buffers are pending, fill output track buffer to make sure it is started
5542 // by output mixer.
5543 if (frames == 0 && mBufferQueue.size() == 0) {
5544 if (mCblk->user < mCblk->frameCount) {
5545 frames = mCblk->frameCount - mCblk->user;
5546 pInBuffer = new Buffer;
5547 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5548 pInBuffer->frameCount = frames;
5549 pInBuffer->i16 = pInBuffer->mBuffer;
5550 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5551 mBufferQueue.add(pInBuffer);
5552 } else if (mActive) {
5553 stop();
5554 }
5555 }
5556
5557 return outputBufferFull;
5558}
5559
5560status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5561{
5562 int active;
5563 status_t result;
5564 audio_track_cblk_t* cblk = mCblk;
5565 uint32_t framesReq = buffer->frameCount;
5566
Steve Block3856b092011-10-20 11:56:00 +01005567// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005568 buffer->frameCount = 0;
5569
5570 uint32_t framesAvail = cblk->framesAvailable();
5571
5572
5573 if (framesAvail == 0) {
5574 Mutex::Autolock _l(cblk->lock);
5575 goto start_loop_here;
5576 while (framesAvail == 0) {
5577 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005578 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005579 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005580 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 }
5582 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5583 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005584 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 }
5586 // read the server count again
5587 start_loop_here:
5588 framesAvail = cblk->framesAvailable_l();
5589 }
5590 }
5591
5592// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005593// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594// }
5595
5596 if (framesReq > framesAvail) {
5597 framesReq = framesAvail;
5598 }
5599
5600 uint32_t u = cblk->user;
5601 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5602
Marco Nelissena1472d92012-03-30 14:36:54 -07005603 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604 framesReq = bufferEnd - u;
5605 }
5606
5607 buffer->frameCount = framesReq;
5608 buffer->raw = (void *)cblk->buffer(u);
5609 return NO_ERROR;
5610}
5611
5612
5613void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5614{
5615 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616
5617 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005618 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619 delete [] pBuffer->mBuffer;
5620 delete pBuffer;
5621 }
5622 mBufferQueue.clear();
5623}
5624
5625// ----------------------------------------------------------------------------
5626
5627AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5628 : RefBase(),
5629 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005630 // 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 -07005631 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005632 mPid(pid),
5633 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634{
5635 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5636}
5637
5638// Client destructor must be called with AudioFlinger::mLock held
5639AudioFlinger::Client::~Client()
5640{
5641 mAudioFlinger->removeClient_l(mPid);
5642}
5643
Glenn Kasten435dbe62012-01-30 10:15:48 -08005644sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645{
5646 return mMemoryDealer;
5647}
5648
John Grossman4ff14ba2012-02-08 16:37:41 -08005649// Reserve one of the limited slots for a timed audio track associated
5650// with this client
5651bool AudioFlinger::Client::reserveTimedTrack()
5652{
5653 const int kMaxTimedTracksPerClient = 4;
5654
5655 Mutex::Autolock _l(mTimedTrackLock);
5656
5657 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5658 ALOGW("can not create timed track - pid %d has exceeded the limit",
5659 mPid);
5660 return false;
5661 }
5662
5663 mTimedTrackCount++;
5664 return true;
5665}
5666
5667// Release a slot for a timed audio track
5668void AudioFlinger::Client::releaseTimedTrack()
5669{
5670 Mutex::Autolock _l(mTimedTrackLock);
5671 mTimedTrackCount--;
5672}
5673
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674// ----------------------------------------------------------------------------
5675
5676AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5677 const sp<IAudioFlingerClient>& client,
5678 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005679 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680{
5681}
5682
5683AudioFlinger::NotificationClient::~NotificationClient()
5684{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685}
5686
5687void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5688{
5689 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005690 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691}
5692
5693// ----------------------------------------------------------------------------
5694
5695AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5696 : BnAudioTrack(),
5697 mTrack(track)
5698{
5699}
5700
5701AudioFlinger::TrackHandle::~TrackHandle() {
5702 // just stop the track on deletion, associated resources
5703 // will be freed from the main thread once all pending buffers have
5704 // been played. Unless it's not in the active track list, in which
5705 // case we free everything now...
5706 mTrack->destroy();
5707}
5708
Glenn Kasten90716c52012-01-26 13:40:12 -08005709sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5710 return mTrack->getCblk();
5711}
5712
Glenn Kasten3acbd052012-02-28 10:39:56 -08005713status_t AudioFlinger::TrackHandle::start() {
5714 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715}
5716
5717void AudioFlinger::TrackHandle::stop() {
5718 mTrack->stop();
5719}
5720
5721void AudioFlinger::TrackHandle::flush() {
5722 mTrack->flush();
5723}
5724
5725void AudioFlinger::TrackHandle::mute(bool e) {
5726 mTrack->mute(e);
5727}
5728
5729void AudioFlinger::TrackHandle::pause() {
5730 mTrack->pause();
5731}
5732
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5734{
5735 return mTrack->attachAuxEffect(EffectId);
5736}
5737
John Grossman4ff14ba2012-02-08 16:37:41 -08005738status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5739 sp<IMemory>* buffer) {
5740 if (!mTrack->isTimedTrack())
5741 return INVALID_OPERATION;
5742
5743 PlaybackThread::TimedTrack* tt =
5744 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5745 return tt->allocateTimedBuffer(size, buffer);
5746}
5747
5748status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5749 int64_t pts) {
5750 if (!mTrack->isTimedTrack())
5751 return INVALID_OPERATION;
5752
5753 PlaybackThread::TimedTrack* tt =
5754 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5755 return tt->queueTimedBuffer(buffer, pts);
5756}
5757
5758status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5759 const LinearTransform& xform, int target) {
5760
5761 if (!mTrack->isTimedTrack())
5762 return INVALID_OPERATION;
5763
5764 PlaybackThread::TimedTrack* tt =
5765 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5766 return tt->setMediaTimeTransform(
5767 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5768}
5769
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770status_t AudioFlinger::TrackHandle::onTransact(
5771 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5772{
5773 return BnAudioTrack::onTransact(code, data, reply, flags);
5774}
5775
5776// ----------------------------------------------------------------------------
5777
5778sp<IAudioRecord> AudioFlinger::openRecord(
5779 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005780 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005782 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005783 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005785 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786 int *sessionId,
5787 status_t *status)
5788{
5789 sp<RecordThread::RecordTrack> recordTrack;
5790 sp<RecordHandle> recordHandle;
5791 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792 status_t lStatus;
5793 RecordThread *thread;
5794 size_t inFrameCount;
5795 int lSessionId;
5796
5797 // check calling permissions
5798 if (!recordingAllowed()) {
5799 lStatus = PERMISSION_DENIED;
5800 goto Exit;
5801 }
5802
5803 // add client to list
5804 { // scope for mLock
5805 Mutex::Autolock _l(mLock);
5806 thread = checkRecordThread_l(input);
5807 if (thread == NULL) {
5808 lStatus = BAD_VALUE;
5809 goto Exit;
5810 }
5811
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005812 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813
5814 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005815 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816 lSessionId = *sessionId;
5817 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005818 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005819 if (sessionId != NULL) {
5820 *sessionId = lSessionId;
5821 }
5822 }
5823 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005824 recordTrack = thread->createRecordTrack_l(client,
5825 sampleRate,
5826 format,
5827 channelMask,
5828 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005829 lSessionId,
5830 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005832 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5834 // destructor is called by the TrackBase destructor with mLock held
5835 client.clear();
5836 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005837 goto Exit;
5838 }
5839
5840 // return to handle to client
5841 recordHandle = new RecordHandle(recordTrack);
5842 lStatus = NO_ERROR;
5843
5844Exit:
5845 if (status) {
5846 *status = lStatus;
5847 }
5848 return recordHandle;
5849}
5850
5851// ----------------------------------------------------------------------------
5852
5853AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5854 : BnAudioRecord(),
5855 mRecordTrack(recordTrack)
5856{
5857}
5858
5859AudioFlinger::RecordHandle::~RecordHandle() {
5860 stop();
5861}
5862
Glenn Kasten90716c52012-01-26 13:40:12 -08005863sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5864 return mRecordTrack->getCblk();
5865}
5866
Glenn Kasten3acbd052012-02-28 10:39:56 -08005867status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005868 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005869 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870}
5871
5872void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005873 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 mRecordTrack->stop();
5875}
5876
Mathias Agopian65ab4712010-07-14 17:59:35 -07005877status_t AudioFlinger::RecordHandle::onTransact(
5878 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5879{
5880 return BnAudioRecord::onTransact(code, data, reply, flags);
5881}
5882
5883// ----------------------------------------------------------------------------
5884
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005885AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5886 AudioStreamIn *input,
5887 uint32_t sampleRate,
5888 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005889 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005890 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005891 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005892 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5893 // mRsmpInIndex and mInputBytes set by readInputParameters()
5894 mReqChannelCount(popcount(channels)),
5895 mReqSampleRate(sampleRate)
5896 // mBytesRead is only meaningful while active, and so is cleared in start()
5897 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898{
Glenn Kasten480b4682012-02-28 12:30:08 -08005899 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005900
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901 readInputParameters();
5902}
5903
5904
5905AudioFlinger::RecordThread::~RecordThread()
5906{
5907 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005908 delete mResampler;
5909 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910}
5911
5912void AudioFlinger::RecordThread::onFirstRef()
5913{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005914 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915}
5916
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005917status_t AudioFlinger::RecordThread::readyToRun()
5918{
5919 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005920 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005921 return status;
5922}
5923
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924bool AudioFlinger::RecordThread::threadLoop()
5925{
5926 AudioBufferProvider::Buffer buffer;
5927 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005928 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929
Eric Laurent44d98482010-09-30 16:12:31 -07005930 nsecs_t lastWarning = 0;
5931
Eric Laurentfeb0db62011-07-22 09:04:31 -07005932 acquireWakeLock();
5933
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 // start recording
5935 while (!exitPending()) {
5936
5937 processConfigEvents();
5938
5939 { // scope for mLock
5940 Mutex::Autolock _l(mLock);
5941 checkForNewParameters_l();
5942 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5943 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005944 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 mStandby = true;
5946 }
5947
5948 if (exitPending()) break;
5949
Eric Laurentfeb0db62011-07-22 09:04:31 -07005950 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005951 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 // go to sleep
5953 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005954 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005955 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 continue;
5957 }
5958 if (mActiveTrack != 0) {
5959 if (mActiveTrack->mState == TrackBase::PAUSING) {
5960 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005961 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 mStandby = true;
5963 }
5964 mActiveTrack.clear();
5965 mStartStopCond.broadcast();
5966 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5967 if (mReqChannelCount != mActiveTrack->channelCount()) {
5968 mActiveTrack.clear();
5969 mStartStopCond.broadcast();
5970 } else if (mBytesRead != 0) {
5971 // record start succeeds only if first read from audio input
5972 // succeeds
5973 if (mBytesRead > 0) {
5974 mActiveTrack->mState = TrackBase::ACTIVE;
5975 } else {
5976 mActiveTrack.clear();
5977 }
5978 mStartStopCond.broadcast();
5979 }
5980 mStandby = false;
5981 }
5982 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005983 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 }
5985
5986 if (mActiveTrack != 0) {
5987 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5988 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005989 unlockEffectChains(effectChains);
5990 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 continue;
5992 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005993 for (size_t i = 0; i < effectChains.size(); i ++) {
5994 effectChains[i]->process_l();
5995 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005996
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005998 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006000 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 // no resampling
6002 while (framesOut) {
6003 size_t framesIn = mFrameCount - mRsmpInIndex;
6004 if (framesIn) {
6005 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6006 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6007 if (framesIn > framesOut)
6008 framesIn = framesOut;
6009 mRsmpInIndex += framesIn;
6010 framesOut -= framesIn;
6011 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006012 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 memcpy(dst, src, framesIn * mFrameSize);
6014 } else {
6015 int16_t *src16 = (int16_t *)src;
6016 int16_t *dst16 = (int16_t *)dst;
6017 if (mChannelCount == 1) {
6018 while (framesIn--) {
6019 *dst16++ = *src16;
6020 *dst16++ = *src16++;
6021 }
6022 } else {
6023 while (framesIn--) {
6024 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6025 src16 += 2;
6026 }
6027 }
6028 }
6029 }
6030 if (framesOut && mFrameCount == mRsmpInIndex) {
6031 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006032 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006033 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034 framesOut = 0;
6035 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006036 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 mRsmpInIndex = 0;
6038 }
6039 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006040 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6042 // Force input into standby so that it tries to
6043 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006044 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006045 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 }
6047 mRsmpInIndex = mFrameCount;
6048 framesOut = 0;
6049 buffer.frameCount = 0;
6050 }
6051 }
6052 }
6053 } else {
6054 // resampling
6055
6056 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6057 // alter output frame count as if we were expecting stereo samples
6058 if (mChannelCount == 1 && mReqChannelCount == 1) {
6059 framesOut >>= 1;
6060 }
6061 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6062 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6063 // are 32 bit aligned which should be always true.
6064 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006065 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066 // the resampler always outputs stereo samples: do post stereo to mono conversion
6067 int16_t *src = (int16_t *)mRsmpOutBuffer;
6068 int16_t *dst = buffer.i16;
6069 while (framesOut--) {
6070 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6071 src += 2;
6072 }
6073 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006074 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 }
6076
6077 }
Eric Laurenta011e352012-03-29 15:51:43 -07006078 if (mFramestoDrop == 0) {
6079 mActiveTrack->releaseBuffer(&buffer);
6080 } else {
6081 if (mFramestoDrop > 0) {
6082 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006083 if (mFramestoDrop <= 0) {
6084 clearSyncStartEvent();
6085 }
6086 } else {
6087 mFramestoDrop += buffer.frameCount;
6088 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6089 mSyncStartEvent->isCancelled()) {
6090 ALOGW("Synced record %s, session %d, trigger session %d",
6091 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6092 mActiveTrack->sessionId(),
6093 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6094 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006095 }
6096 }
6097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 mActiveTrack->overflow();
6099 }
6100 // client isn't retrieving buffers fast enough
6101 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006102 if (!mActiveTrack->setOverflow()) {
6103 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006104 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006105 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006106 lastWarning = now;
6107 }
6108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 // Release the processor for a while before asking for a new buffer.
6110 // This will give the application more chance to read from the buffer and
6111 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006112 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 }
6114 }
Eric Laurentec437d82011-07-26 20:54:46 -07006115 // enable changes in effect chain
6116 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006117 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 }
6119
6120 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006121 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 }
6123 mActiveTrack.clear();
6124
6125 mStartStopCond.broadcast();
6126
Eric Laurentfeb0db62011-07-22 09:04:31 -07006127 releaseWakeLock();
6128
Steve Block3856b092011-10-20 11:56:00 +01006129 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 return false;
6131}
6132
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006133
6134sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6135 const sp<AudioFlinger::Client>& client,
6136 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006137 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006138 int channelMask,
6139 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006140 int sessionId,
6141 status_t *status)
6142{
6143 sp<RecordTrack> track;
6144 status_t lStatus;
6145
6146 lStatus = initCheck();
6147 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006148 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006149 goto Exit;
6150 }
6151
6152 { // scope for mLock
6153 Mutex::Autolock _l(mLock);
6154
6155 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006156 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006157
Glenn Kasten7378ca52012-01-20 13:44:40 -08006158 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006159 lStatus = NO_MEMORY;
6160 goto Exit;
6161 }
6162
6163 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006164 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6165 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006166 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006167 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6168 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006169 }
6170 lStatus = NO_ERROR;
6171
6172Exit:
6173 if (status) {
6174 *status = lStatus;
6175 }
6176 return track;
6177}
6178
Eric Laurenta011e352012-03-29 15:51:43 -07006179status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006180 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006181 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182{
Glenn Kasten58912562012-04-03 10:45:00 -07006183 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006184 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006186
6187 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006188 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006189 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6190 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6191 triggerSession,
6192 recordTrack->sessionId(),
6193 syncStartEventCallback,
6194 this);
Eric Laurent29864602012-05-08 18:57:51 -07006195 // Sync event can be cancelled by the trigger session if the track is not in a
6196 // compatible state in which case we start record immediately
6197 if (mSyncStartEvent->isCancelled()) {
6198 clearSyncStartEvent();
6199 } else {
6200 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6201 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6202 }
Eric Laurenta011e352012-03-29 15:51:43 -07006203 }
6204
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006206 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 if (mActiveTrack != 0) {
6208 if (recordTrack != mActiveTrack.get()) {
6209 status = -EBUSY;
6210 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6211 mActiveTrack->mState = TrackBase::ACTIVE;
6212 }
6213 return status;
6214 }
6215
6216 recordTrack->mState = TrackBase::IDLE;
6217 mActiveTrack = recordTrack;
6218 mLock.unlock();
6219 status_t status = AudioSystem::startInput(mId);
6220 mLock.lock();
6221 if (status != NO_ERROR) {
6222 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006223 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 return status;
6225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 mRsmpInIndex = mFrameCount;
6227 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006228 if (mResampler != NULL) {
6229 mResampler->reset();
6230 }
6231 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006233 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 mWaitWorkCV.signal();
6235 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006236 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237 mActiveTrack.clear();
6238 status = INVALID_OPERATION;
6239 goto startError;
6240 }
6241 mStartStopCond.wait(mLock);
6242 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006243 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244 status = BAD_VALUE;
6245 goto startError;
6246 }
Steve Block3856b092011-10-20 11:56:00 +01006247 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 return status;
6249 }
6250startError:
6251 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006252 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 return status;
6254}
6255
Eric Laurenta011e352012-03-29 15:51:43 -07006256void AudioFlinger::RecordThread::clearSyncStartEvent()
6257{
6258 if (mSyncStartEvent != 0) {
6259 mSyncStartEvent->cancel();
6260 }
6261 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006262 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006263}
6264
6265void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6266{
6267 sp<SyncEvent> strongEvent = event.promote();
6268
6269 if (strongEvent != 0) {
6270 RecordThread *me = (RecordThread *)strongEvent->cookie();
6271 me->handleSyncStartEvent(strongEvent);
6272 }
6273}
6274
6275void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6276{
Eric Laurent29864602012-05-08 18:57:51 -07006277 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006278 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6279 // from audio HAL
6280 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006281 }
6282}
6283
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006285 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006286 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006288 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6290 mActiveTrack->mState = TrackBase::PAUSING;
6291 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006292 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 return;
6294 }
6295 mStartStopCond.wait(mLock);
6296 // if we have been restarted, recordTrack == mActiveTrack.get() here
6297 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6298 mLock.unlock();
6299 AudioSystem::stopInput(mId);
6300 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006301 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006302 }
6303 }
6304 }
6305}
6306
Eric Laurenta011e352012-03-29 15:51:43 -07006307bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6308{
6309 return false;
6310}
6311
6312status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6313{
6314 if (!isValidSyncEvent(event)) {
6315 return BAD_VALUE;
6316 }
6317
6318 Mutex::Autolock _l(mLock);
6319
6320 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6321 mTrack->setSyncEvent(event);
6322 return NO_ERROR;
6323 }
6324 return NAME_NOT_FOUND;
6325}
6326
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6328{
6329 const size_t SIZE = 256;
6330 char buffer[SIZE];
6331 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006332
6333 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6334 result.append(buffer);
6335
6336 if (mActiveTrack != 0) {
6337 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006338 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 mActiveTrack->dump(buffer, SIZE);
6340 result.append(buffer);
6341
6342 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6343 result.append(buffer);
6344 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6345 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006346 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 result.append(buffer);
6348 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6349 result.append(buffer);
6350 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6351 result.append(buffer);
6352
6353
6354 } else {
6355 result.append("No record client\n");
6356 }
6357 write(fd, result.string(), result.size());
6358
6359 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006360 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361
6362 return NO_ERROR;
6363}
6364
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006365// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006366status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006367{
6368 size_t framesReq = buffer->frameCount;
6369 size_t framesReady = mFrameCount - mRsmpInIndex;
6370 int channelCount;
6371
6372 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006373 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006375 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6377 // Force input into standby so that it tries to
6378 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006379 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006380 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006382 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 buffer->frameCount = 0;
6384 return NOT_ENOUGH_DATA;
6385 }
6386 mRsmpInIndex = 0;
6387 framesReady = mFrameCount;
6388 }
6389
6390 if (framesReq > framesReady) {
6391 framesReq = framesReady;
6392 }
6393
6394 if (mChannelCount == 1 && mReqChannelCount == 2) {
6395 channelCount = 1;
6396 } else {
6397 channelCount = 2;
6398 }
6399 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6400 buffer->frameCount = framesReq;
6401 return NO_ERROR;
6402}
6403
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006404// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6406{
6407 mRsmpInIndex += buffer->frameCount;
6408 buffer->frameCount = 0;
6409}
6410
6411bool AudioFlinger::RecordThread::checkForNewParameters_l()
6412{
6413 bool reconfig = false;
6414
6415 while (!mNewParameters.isEmpty()) {
6416 status_t status = NO_ERROR;
6417 String8 keyValuePair = mNewParameters[0];
6418 AudioParameter param = AudioParameter(keyValuePair);
6419 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006420 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 int reqSamplingRate = mReqSampleRate;
6422 int reqChannelCount = mReqChannelCount;
6423
6424 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6425 reqSamplingRate = value;
6426 reconfig = true;
6427 }
6428 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006429 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430 reconfig = true;
6431 }
6432 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006433 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006434 reconfig = true;
6435 }
6436 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6437 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006438 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 // if frame count is changed after track creation
6440 if (mActiveTrack != 0) {
6441 status = INVALID_OPERATION;
6442 } else {
6443 reconfig = true;
6444 }
6445 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006446 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6447 // forward device change to effects that have requested to be
6448 // aware of attached audio device.
6449 for (size_t i = 0; i < mEffectChains.size(); i++) {
6450 mEffectChains[i]->setDevice_l(value);
6451 }
6452 // store input device and output device but do not forward output device to audio HAL.
6453 // Note that status is ignored by the caller for output device
6454 // (see AudioFlinger::setParameters()
6455 if (value & AUDIO_DEVICE_OUT_ALL) {
6456 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6457 status = BAD_VALUE;
6458 } else {
6459 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006460 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6461 if (mTrack != NULL) {
6462 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006463 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006464 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6465 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6466 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006467 }
6468 mDevice |= (uint32_t)value;
6469 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006470 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006471 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006473 mInput->stream->common.standby(&mInput->stream->common);
6474 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6475 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 }
6477 if (reconfig) {
6478 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006479 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006480 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006481 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006482 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6483 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484 status = NO_ERROR;
6485 }
6486 if (status == NO_ERROR) {
6487 readInputParameters();
6488 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6489 }
6490 }
6491 }
6492
6493 mNewParameters.removeAt(0);
6494
6495 mParamStatus = status;
6496 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006497 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6498 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006499 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 }
6501 return reconfig;
6502}
6503
6504String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6505{
Dima Zavinfce7a472011-04-19 22:30:36 -07006506 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006507 String8 out_s8 = String8();
6508
6509 Mutex::Autolock _l(mLock);
6510 if (initCheck() != NO_ERROR) {
6511 return out_s8;
6512 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006513
Dima Zavin799a70e2011-04-18 16:57:27 -07006514 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006515 out_s8 = String8(s);
6516 free(s);
6517 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518}
6519
6520void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6521 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006522 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523
6524 switch (event) {
6525 case AudioSystem::INPUT_OPENED:
6526 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006527 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528 desc.samplingRate = mSampleRate;
6529 desc.format = mFormat;
6530 desc.frameCount = mFrameCount;
6531 desc.latency = 0;
6532 param2 = &desc;
6533 break;
6534
6535 case AudioSystem::INPUT_CLOSED:
6536 default:
6537 break;
6538 }
6539 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6540}
6541
6542void AudioFlinger::RecordThread::readInputParameters()
6543{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006544 delete mRsmpInBuffer;
6545 // mRsmpInBuffer is always assigned a new[] below
6546 delete mRsmpOutBuffer;
6547 mRsmpOutBuffer = NULL;
6548 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006549 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550
Dima Zavin799a70e2011-04-18 16:57:27 -07006551 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006552 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6553 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006554 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006555 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006556 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006558 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6560
Glenn Kasten53d76db2012-03-08 12:32:47 -08006561 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562 {
6563 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006564 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6565 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566 if (mChannelCount == 1 && mReqChannelCount == 2) {
6567 channelCount = 1;
6568 } else {
6569 channelCount = 2;
6570 }
6571 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6572 mResampler->setSampleRate(mSampleRate);
6573 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6574 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6575
6576 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6577 if (mChannelCount == 1 && mReqChannelCount == 1) {
6578 mFrameCount >>= 1;
6579 }
6580
6581 }
6582 mRsmpInIndex = mFrameCount;
6583}
6584
6585unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6586{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006587 Mutex::Autolock _l(mLock);
6588 if (initCheck() != NO_ERROR) {
6589 return 0;
6590 }
6591
Dima Zavin799a70e2011-04-18 16:57:27 -07006592 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593}
6594
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006595uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6596{
6597 Mutex::Autolock _l(mLock);
6598 uint32_t result = 0;
6599 if (getEffectChain_l(sessionId) != 0) {
6600 result = EFFECT_SESSION;
6601 }
6602
6603 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6604 result |= TRACK_SESSION;
6605 }
6606
6607 return result;
6608}
6609
Eric Laurent59bd0da2011-08-01 09:52:20 -07006610AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6611{
6612 Mutex::Autolock _l(mLock);
6613 return mTrack;
6614}
6615
Glenn Kastenaed850d2012-01-26 09:46:34 -08006616AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006617{
6618 Mutex::Autolock _l(mLock);
6619 return mInput;
6620}
6621
6622AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6623{
6624 Mutex::Autolock _l(mLock);
6625 AudioStreamIn *input = mInput;
6626 mInput = NULL;
6627 return input;
6628}
6629
6630// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006631audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006632{
6633 if (mInput == NULL) {
6634 return NULL;
6635 }
6636 return &mInput->stream->common;
6637}
6638
6639
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640// ----------------------------------------------------------------------------
6641
Eric Laurenta4c5a552012-03-29 10:12:40 -07006642audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6643{
6644 if (!settingsAllowed()) {
6645 return 0;
6646 }
6647 Mutex::Autolock _l(mLock);
6648 return loadHwModule_l(name);
6649}
6650
6651// loadHwModule_l() must be called with AudioFlinger::mLock held
6652audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6653{
6654 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6655 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6656 ALOGW("loadHwModule() module %s already loaded", name);
6657 return mAudioHwDevs.keyAt(i);
6658 }
6659 }
6660
Eric Laurenta4c5a552012-03-29 10:12:40 -07006661 audio_hw_device_t *dev;
6662
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006663 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006664 if (rc) {
6665 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6666 return 0;
6667 }
6668
6669 mHardwareStatus = AUDIO_HW_INIT;
6670 rc = dev->init_check(dev);
6671 mHardwareStatus = AUDIO_HW_IDLE;
6672 if (rc) {
6673 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6674 return 0;
6675 }
6676
6677 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6678 (NULL != dev->set_master_volume)) {
6679 AutoMutex lock(mHardwareLock);
6680 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6681 dev->set_master_volume(dev, mMasterVolume);
6682 mHardwareStatus = AUDIO_HW_IDLE;
6683 }
6684
6685 audio_module_handle_t handle = nextUniqueId();
6686 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6687
6688 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006689 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006690
6691 return handle;
6692
6693}
6694
6695audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6696 audio_devices_t *pDevices,
6697 uint32_t *pSamplingRate,
6698 audio_format_t *pFormat,
6699 audio_channel_mask_t *pChannelMask,
6700 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006701 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702{
6703 status_t status;
6704 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006705 struct audio_config config = {
6706 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6707 channel_mask: pChannelMask ? *pChannelMask : 0,
6708 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6709 };
6710 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006711 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712
Eric Laurenta4c5a552012-03-29 10:12:40 -07006713 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6714 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006715 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006716 config.sample_rate,
6717 config.format,
6718 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006719 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720
6721 if (pDevices == NULL || *pDevices == 0) {
6722 return 0;
6723 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006724
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 Mutex::Autolock _l(mLock);
6726
Eric Laurenta4c5a552012-03-29 10:12:40 -07006727 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006728 if (outHwDev == NULL)
6729 return 0;
6730
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006731 audio_io_handle_t id = nextUniqueId();
6732
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006733 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006734
6735 status = outHwDev->open_output_stream(outHwDev,
6736 id,
6737 *pDevices,
6738 (audio_output_flags_t)flags,
6739 &config,
6740 &outStream);
6741
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006742 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006743 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006744 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006745 config.sample_rate,
6746 config.format,
6747 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006748 status);
6749
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006750 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006751 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006752
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006753 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006754 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6755 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006757 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 } else {
6759 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006760 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761 }
6762 mPlaybackThreads.add(id, thread);
6763
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006764 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6765 if (pFormat != NULL) *pFormat = config.format;
6766 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006767 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768
6769 // notify client processes of the new output creation
6770 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006771
6772 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006773 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006774 ALOGI("Using module %d has the primary audio interface", module);
6775 mPrimaryHardwareDev = outHwDev;
6776
6777 AutoMutex lock(mHardwareLock);
6778 mHardwareStatus = AUDIO_HW_SET_MODE;
6779 outHwDev->set_mode(outHwDev, mMode);
6780
6781 // Determine the level of master volume support the primary audio HAL has,
6782 // and set the initial master volume at the same time.
6783 float initialVolume = 1.0;
6784 mMasterVolumeSupportLvl = MVS_NONE;
6785
6786 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6787 if ((NULL != outHwDev->get_master_volume) &&
6788 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6789 mMasterVolumeSupportLvl = MVS_FULL;
6790 } else {
6791 mMasterVolumeSupportLvl = MVS_SETONLY;
6792 initialVolume = 1.0;
6793 }
6794
6795 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6796 if ((NULL == outHwDev->set_master_volume) ||
6797 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6798 mMasterVolumeSupportLvl = MVS_NONE;
6799 }
6800 // now that we have a primary device, initialize master volume on other devices
6801 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6802 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6803
6804 if ((dev != mPrimaryHardwareDev) &&
6805 (NULL != dev->set_master_volume)) {
6806 dev->set_master_volume(dev, initialVolume);
6807 }
6808 }
6809 mHardwareStatus = AUDIO_HW_IDLE;
6810 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6811 ? initialVolume
6812 : 1.0;
6813 mMasterVolume = initialVolume;
6814 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006815 return id;
6816 }
6817
6818 return 0;
6819}
6820
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006821audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6822 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823{
6824 Mutex::Autolock _l(mLock);
6825 MixerThread *thread1 = checkMixerThread_l(output1);
6826 MixerThread *thread2 = checkMixerThread_l(output2);
6827
6828 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006829 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006830 return 0;
6831 }
6832
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006833 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6835 thread->addOutputTrack(thread2);
6836 mPlaybackThreads.add(id, thread);
6837 // notify client processes of the new output creation
6838 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6839 return id;
6840}
6841
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006842status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843{
6844 // keep strong reference on the playback thread so that
6845 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006846 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847 {
6848 Mutex::Autolock _l(mLock);
6849 thread = checkPlaybackThread_l(output);
6850 if (thread == NULL) {
6851 return BAD_VALUE;
6852 }
6853
Steve Block3856b092011-10-20 11:56:00 +01006854 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006856 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006858 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6860 dupThread->removeOutputTrack((MixerThread *)thread.get());
6861 }
6862 }
6863 }
Glenn Kastena1117922012-01-26 10:53:32 -08006864 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 mPlaybackThreads.removeItem(output);
6866 }
6867 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006868 // The thread entity (active unit of execution) is no longer running here,
6869 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006871 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006872 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006873 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006874 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006875 out->hwDev->close_output_stream(out->hwDev, out->stream);
6876 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 }
6878 return NO_ERROR;
6879}
6880
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006881status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882{
6883 Mutex::Autolock _l(mLock);
6884 PlaybackThread *thread = checkPlaybackThread_l(output);
6885
6886 if (thread == NULL) {
6887 return BAD_VALUE;
6888 }
6889
Steve Block3856b092011-10-20 11:56:00 +01006890 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 thread->suspend();
6892
6893 return NO_ERROR;
6894}
6895
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006896status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897{
6898 Mutex::Autolock _l(mLock);
6899 PlaybackThread *thread = checkPlaybackThread_l(output);
6900
6901 if (thread == NULL) {
6902 return BAD_VALUE;
6903 }
6904
Steve Block3856b092011-10-20 11:56:00 +01006905 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906
6907 thread->restore();
6908
6909 return NO_ERROR;
6910}
6911
Eric Laurenta4c5a552012-03-29 10:12:40 -07006912audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6913 audio_devices_t *pDevices,
6914 uint32_t *pSamplingRate,
6915 audio_format_t *pFormat,
6916 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917{
6918 status_t status;
6919 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006920 struct audio_config config = {
6921 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6922 channel_mask: pChannelMask ? *pChannelMask : 0,
6923 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6924 };
6925 uint32_t reqSamplingRate = config.sample_rate;
6926 audio_format_t reqFormat = config.format;
6927 audio_channel_mask_t reqChannels = config.channel_mask;
6928 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006929 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930
6931 if (pDevices == NULL || *pDevices == 0) {
6932 return 0;
6933 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006934
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935 Mutex::Autolock _l(mLock);
6936
Eric Laurenta4c5a552012-03-29 10:12:40 -07006937 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006938 if (inHwDev == NULL)
6939 return 0;
6940
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006941 audio_io_handle_t id = nextUniqueId();
6942
6943 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006944 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006945 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006946 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006947 config.sample_rate,
6948 config.format,
6949 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 status);
6951
6952 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6953 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6954 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006955 if (status == BAD_VALUE &&
6956 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6957 (config.sample_rate <= 2 * reqSamplingRate) &&
6958 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006959 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006960 inStream = NULL;
6961 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 }
6963
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006964 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006965 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6966
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006967 // Start record thread
6968 // RecorThread require both input and output device indication to forward to audio
6969 // pre processing modules
6970 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6971 thread = new RecordThread(this,
6972 input,
6973 reqSamplingRate,
6974 reqChannels,
6975 id,
6976 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006978 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006979 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006980 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006981 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982
Dima Zavin799a70e2011-04-18 16:57:27 -07006983 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984
6985 // notify client processes of the new input creation
6986 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6987 return id;
6988 }
6989
6990 return 0;
6991}
6992
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006993status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994{
6995 // keep strong reference on the record thread so that
6996 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006997 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 {
6999 Mutex::Autolock _l(mLock);
7000 thread = checkRecordThread_l(input);
7001 if (thread == NULL) {
7002 return BAD_VALUE;
7003 }
7004
Steve Block3856b092011-10-20 11:56:00 +01007005 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007006 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 mRecordThreads.removeItem(input);
7008 }
7009 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007010 // The thread entity (active unit of execution) is no longer running here,
7011 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007013 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007014 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007015 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007016 in->hwDev->close_input_stream(in->hwDev, in->stream);
7017 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018
7019 return NO_ERROR;
7020}
7021
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007022status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023{
7024 Mutex::Autolock _l(mLock);
7025 MixerThread *dstThread = checkMixerThread_l(output);
7026 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007027 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 return BAD_VALUE;
7029 }
7030
Steve Block3856b092011-10-20 11:56:00 +01007031 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
7033
7034 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7035 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08007036 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037 MixerThread *srcThread = (MixerThread *)thread;
7038 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007039 }
Eric Laurentde070132010-07-13 04:45:46 -07007040 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041
7042 return NO_ERROR;
7043}
7044
7045
7046int AudioFlinger::newAudioSessionId()
7047{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007048 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049}
7050
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007051void AudioFlinger::acquireAudioSessionId(int audioSession)
7052{
7053 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007054 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007055 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007056 size_t num = mAudioSessionRefs.size();
7057 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007058 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007059 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7060 ref->mCnt++;
7061 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007062 return;
7063 }
7064 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007065 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7066 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007067}
7068
7069void AudioFlinger::releaseAudioSessionId(int audioSession)
7070{
7071 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007072 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007073 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007074 size_t num = mAudioSessionRefs.size();
7075 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007076 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007077 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7078 ref->mCnt--;
7079 ALOGV(" decremented refcount to %d", ref->mCnt);
7080 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007081 mAudioSessionRefs.removeAt(i);
7082 delete ref;
7083 purgeStaleEffects_l();
7084 }
7085 return;
7086 }
7087 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007088 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007089}
7090
7091void AudioFlinger::purgeStaleEffects_l() {
7092
Steve Block3856b092011-10-20 11:56:00 +01007093 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007094
7095 Vector< sp<EffectChain> > chains;
7096
7097 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7098 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7099 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7100 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007101 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7102 chains.push(ec);
7103 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007104 }
7105 }
7106 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7107 sp<RecordThread> t = mRecordThreads.valueAt(i);
7108 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7109 sp<EffectChain> ec = t->mEffectChains[j];
7110 chains.push(ec);
7111 }
7112 }
7113
7114 for (size_t i = 0; i < chains.size(); i++) {
7115 sp<EffectChain> ec = chains[i];
7116 int sessionid = ec->sessionId();
7117 sp<ThreadBase> t = ec->mThread.promote();
7118 if (t == 0) {
7119 continue;
7120 }
7121 size_t numsessionrefs = mAudioSessionRefs.size();
7122 bool found = false;
7123 for (size_t k = 0; k < numsessionrefs; k++) {
7124 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007125 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007126 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007127 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007128 found = true;
7129 break;
7130 }
7131 }
7132 if (!found) {
7133 // remove all effects from the chain
7134 while (ec->mEffects.size()) {
7135 sp<EffectModule> effect = ec->mEffects[0];
7136 effect->unPin();
7137 Mutex::Autolock _l (t->mLock);
7138 t->removeEffect_l(effect);
7139 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7140 sp<EffectHandle> handle = effect->mHandles[j].promote();
7141 if (handle != 0) {
7142 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007143 if (handle->mHasControl && handle->mEnabled) {
7144 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7145 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007146 }
7147 }
7148 AudioSystem::unregisterEffect(effect->id());
7149 }
7150 }
7151 }
7152 return;
7153}
7154
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007156AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157{
Glenn Kastena1117922012-01-26 10:53:32 -08007158 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159}
7160
7161// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007162AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163{
7164 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007165 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166}
7167
7168// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007169AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170{
Glenn Kastena1117922012-01-26 10:53:32 -08007171 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172}
7173
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007174uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007176 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177}
7178
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007179AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180{
7181 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7182 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007183 AudioStreamOut *output = thread->getOutput();
7184 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007185 return thread;
7186 }
7187 }
7188 return NULL;
7189}
7190
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007191uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007192{
7193 PlaybackThread *thread = primaryPlaybackThread_l();
7194
7195 if (thread == NULL) {
7196 return 0;
7197 }
7198
7199 return thread->device();
7200}
7201
Eric Laurenta011e352012-03-29 15:51:43 -07007202sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7203 int triggerSession,
7204 int listenerSession,
7205 sync_event_callback_t callBack,
7206 void *cookie)
7207{
7208 Mutex::Autolock _l(mLock);
7209
7210 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7211 status_t playStatus = NAME_NOT_FOUND;
7212 status_t recStatus = NAME_NOT_FOUND;
7213 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7214 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7215 if (playStatus == NO_ERROR) {
7216 return event;
7217 }
7218 }
7219 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7220 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7221 if (recStatus == NO_ERROR) {
7222 return event;
7223 }
7224 }
7225 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7226 mPendingSyncEvents.add(event);
7227 } else {
7228 ALOGV("createSyncEvent() invalid event %d", event->type());
7229 event.clear();
7230 }
7231 return event;
7232}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007233
Mathias Agopian65ab4712010-07-14 17:59:35 -07007234// ----------------------------------------------------------------------------
7235// Effect management
7236// ----------------------------------------------------------------------------
7237
7238
Glenn Kastenf587ba52012-01-26 16:25:10 -08007239status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240{
7241 Mutex::Autolock _l(mLock);
7242 return EffectQueryNumberEffects(numEffects);
7243}
7244
Glenn Kastenf587ba52012-01-26 16:25:10 -08007245status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246{
7247 Mutex::Autolock _l(mLock);
7248 return EffectQueryEffect(index, descriptor);
7249}
7250
Glenn Kasten5e92a782012-01-30 07:40:52 -08007251status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007252 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007253{
7254 Mutex::Autolock _l(mLock);
7255 return EffectGetDescriptor(pUuid, descriptor);
7256}
7257
7258
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7260 effect_descriptor_t *pDesc,
7261 const sp<IEffectClient>& effectClient,
7262 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007263 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264 int sessionId,
7265 status_t *status,
7266 int *id,
7267 int *enabled)
7268{
7269 status_t lStatus = NO_ERROR;
7270 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007272
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007273 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007274 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275
7276 if (pDesc == NULL) {
7277 lStatus = BAD_VALUE;
7278 goto Exit;
7279 }
7280
Eric Laurent84e9a102010-09-23 16:10:16 -07007281 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007282 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007283 lStatus = PERMISSION_DENIED;
7284 goto Exit;
7285 }
7286
Dima Zavinfce7a472011-04-19 22:30:36 -07007287 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007288 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007289 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007290 lStatus = PERMISSION_DENIED;
7291 goto Exit;
7292 }
7293
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007294 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007295 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007296 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007297 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007298 lStatus = BAD_VALUE;
7299 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007300 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007301 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007302 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007303 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007305 }
7306 }
7307
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 {
7309 Mutex::Autolock _l(mLock);
7310
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311
7312 if (!EffectIsNullUuid(&pDesc->uuid)) {
7313 // if uuid is specified, request effect descriptor
7314 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7315 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007316 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317 goto Exit;
7318 }
7319 } else {
7320 // if uuid is not specified, look for an available implementation
7321 // of the required type in effect factory
7322 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007323 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 lStatus = BAD_VALUE;
7325 goto Exit;
7326 }
7327 uint32_t numEffects = 0;
7328 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007329 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 bool found = false;
7331
7332 lStatus = EffectQueryNumberEffects(&numEffects);
7333 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007334 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335 goto Exit;
7336 }
7337 for (uint32_t i = 0; i < numEffects; i++) {
7338 lStatus = EffectQueryEffect(i, &desc);
7339 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007340 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 continue;
7342 }
7343 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7344 // If matching type found save effect descriptor. If the session is
7345 // 0 and the effect is not auxiliary, continue enumeration in case
7346 // an auxiliary version of this effect type is available
7347 found = true;
7348 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007349 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7351 break;
7352 }
7353 }
7354 }
7355 if (!found) {
7356 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007357 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 goto Exit;
7359 }
7360 // For same effect type, chose auxiliary version over insert version if
7361 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007362 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7364 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7365 }
7366 }
7367
7368 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007369 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7371 lStatus = INVALID_OPERATION;
7372 goto Exit;
7373 }
7374
Eric Laurent59255e42011-07-27 19:49:51 -07007375 // check recording permission for visualizer
7376 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7377 !recordingAllowed()) {
7378 lStatus = PERMISSION_DENIED;
7379 goto Exit;
7380 }
7381
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 // return effect descriptor
7383 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7384
7385 // If output is not specified try to find a matching audio session ID in one of the
7386 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007387 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7388 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007389 // Note: io is never 0 when creating an effect on an input
7390 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007391 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007392 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7393 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007394 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007395 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007396 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007398 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007399 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7400 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7401 io = mRecordThreads.keyAt(i);
7402 break;
7403 }
7404 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007405 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007406 // If no output thread contains the requested session ID, default to
7407 // first output. The effect chain will be moved to the correct output
7408 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007409 if (io == 0 && mPlaybackThreads.size()) {
7410 io = mPlaybackThreads.keyAt(0);
7411 }
Steve Block3856b092011-10-20 11:56:00 +01007412 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007413 }
7414 ThreadBase *thread = checkRecordThread_l(io);
7415 if (thread == NULL) {
7416 thread = checkPlaybackThread_l(io);
7417 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007418 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007419 lStatus = BAD_VALUE;
7420 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007423
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007424 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007426 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007427 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7428 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 if (handle != 0 && id != NULL) {
7430 *id = handle->id();
7431 }
7432 }
7433
7434Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007435 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 *status = lStatus;
7437 }
7438 return handle;
7439}
7440
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007441status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7442 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007443{
Steve Block3856b092011-10-20 11:56:00 +01007444 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007445 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007446 Mutex::Autolock _l(mLock);
7447 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007448 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007449 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 }
Eric Laurentde070132010-07-13 04:45:46 -07007451 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7452 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007453 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007454 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455 }
Eric Laurentde070132010-07-13 04:45:46 -07007456 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7457 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007458 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007459 return BAD_VALUE;
7460 }
7461
7462 Mutex::Autolock _dl(dstThread->mLock);
7463 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007464 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007465
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 return NO_ERROR;
7467}
7468
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007469// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007470status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007471 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007472 AudioFlinger::PlaybackThread *dstThread,
7473 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007474{
Steve Block3856b092011-10-20 11:56:00 +01007475 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007476 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007477
Eric Laurent59255e42011-07-27 19:49:51 -07007478 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007479 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007480 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007481 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007482 return INVALID_OPERATION;
7483 }
7484
Eric Laurent39e94f82010-07-28 01:32:47 -07007485 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007486 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007487 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007488 // removed.
7489 srcThread->removeEffectChain_l(chain);
7490
7491 // transfer all effects one by one so that new effect chain is created on new thread with
7492 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007493 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007494 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007495 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007496 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7497 while (effect != 0) {
7498 srcThread->removeEffect_l(effect);
7499 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007500 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7501 if (effect->state() == EffectModule::ACTIVE ||
7502 effect->state() == EffectModule::STOPPING) {
7503 effect->start();
7504 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007505 // if the move request is not received from audio policy manager, the effect must be
7506 // re-registered with the new strategy and output
7507 if (dstChain == 0) {
7508 dstChain = effect->chain().promote();
7509 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007510 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007511 srcThread->addEffect_l(effect);
7512 return NO_INIT;
7513 }
7514 strategy = dstChain->strategy();
7515 }
7516 if (reRegister) {
7517 AudioSystem::unregisterEffect(effect->id());
7518 AudioSystem::registerEffect(&effect->desc(),
7519 dstOutput,
7520 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007521 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007522 effect->id());
7523 }
Eric Laurentde070132010-07-13 04:45:46 -07007524 effect = chain->getEffectFromId_l(0);
7525 }
7526
7527 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007528}
7529
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007530
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007532sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007533 const sp<AudioFlinger::Client>& client,
7534 const sp<IEffectClient>& effectClient,
7535 int32_t priority,
7536 int sessionId,
7537 effect_descriptor_t *desc,
7538 int *enabled,
7539 status_t *status
7540 )
7541{
7542 sp<EffectModule> effect;
7543 sp<EffectHandle> handle;
7544 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007545 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007546 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547 bool effectCreated = false;
7548 bool effectRegistered = false;
7549
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007550 lStatus = initCheck();
7551 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007552 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 goto Exit;
7554 }
7555
7556 // Do not allow effects with session ID 0 on direct output or duplicating threads
7557 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007558 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007559 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007560 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561 lStatus = BAD_VALUE;
7562 goto Exit;
7563 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007564 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007565 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007566 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007567 desc->name, desc->flags, mType);
7568 lStatus = BAD_VALUE;
7569 goto Exit;
7570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571
Steve Block3856b092011-10-20 11:56:00 +01007572 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573
7574 { // scope for mLock
7575 Mutex::Autolock _l(mLock);
7576
7577 // check for existing effect chain with the requested audio session
7578 chain = getEffectChain_l(sessionId);
7579 if (chain == 0) {
7580 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007581 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582 chain = new EffectChain(this, sessionId);
7583 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007584 chain->setStrategy(getStrategyForSession_l(sessionId));
7585 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007587 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 }
7589
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007590 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591
7592 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007593 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007595 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 if (lStatus != NO_ERROR) {
7597 goto Exit;
7598 }
7599 effectRegistered = true;
7600 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007601 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 lStatus = effect->status();
7603 if (lStatus != NO_ERROR) {
7604 goto Exit;
7605 }
Eric Laurentcab11242010-07-15 12:50:15 -07007606 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007607 if (lStatus != NO_ERROR) {
7608 goto Exit;
7609 }
7610 effectCreated = true;
7611
7612 effect->setDevice(mDevice);
7613 effect->setMode(mAudioFlinger->getMode());
7614 }
7615 // create effect handle and connect it to effect module
7616 handle = new EffectHandle(effect, client, effectClient, priority);
7617 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007618 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 *enabled = (int)effect->isEnabled();
7620 }
7621 }
7622
7623Exit:
7624 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007625 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007627 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628 }
7629 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007630 AudioSystem::unregisterEffect(effect->id());
7631 }
7632 if (chainCreated) {
7633 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634 }
7635 handle.clear();
7636 }
7637
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007638 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007639 *status = lStatus;
7640 }
7641 return handle;
7642}
7643
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007644sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7645{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007646 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007647 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007648}
7649
Eric Laurentde070132010-07-13 04:45:46 -07007650// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7651// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007652status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007653{
7654 // check for existing effect chain with the requested audio session
7655 int sessionId = effect->sessionId();
7656 sp<EffectChain> chain = getEffectChain_l(sessionId);
7657 bool chainCreated = false;
7658
7659 if (chain == 0) {
7660 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007661 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007662 chain = new EffectChain(this, sessionId);
7663 addEffectChain_l(chain);
7664 chain->setStrategy(getStrategyForSession_l(sessionId));
7665 chainCreated = true;
7666 }
Steve Block3856b092011-10-20 11:56:00 +01007667 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007668
7669 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007670 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007671 this, effect->desc().name, chain.get());
7672 return BAD_VALUE;
7673 }
7674
7675 status_t status = chain->addEffect_l(effect);
7676 if (status != NO_ERROR) {
7677 if (chainCreated) {
7678 removeEffectChain_l(chain);
7679 }
7680 return status;
7681 }
7682
7683 effect->setDevice(mDevice);
7684 effect->setMode(mAudioFlinger->getMode());
7685 return NO_ERROR;
7686}
7687
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007688void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007689
Steve Block3856b092011-10-20 11:56:00 +01007690 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007692 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7693 detachAuxEffect_l(effect->id());
7694 }
7695
7696 sp<EffectChain> chain = effect->chain().promote();
7697 if (chain != 0) {
7698 // remove effect chain if removing last effect
7699 if (chain->removeEffect_l(effect) == 0) {
7700 removeEffectChain_l(chain);
7701 }
7702 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007703 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007704 }
7705}
7706
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007707void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007708 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007709{
7710 effectChains = mEffectChains;
7711 for (size_t i = 0; i < mEffectChains.size(); i++) {
7712 mEffectChains[i]->lock();
7713 }
7714}
7715
7716void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007717 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007718{
7719 for (size_t i = 0; i < effectChains.size(); i++) {
7720 effectChains[i]->unlock();
7721 }
7722}
7723
7724sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7725{
7726 Mutex::Autolock _l(mLock);
7727 return getEffectChain_l(sessionId);
7728}
7729
7730sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7731{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007732 size_t size = mEffectChains.size();
7733 for (size_t i = 0; i < size; i++) {
7734 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007735 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007736 }
7737 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007738 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007739}
7740
Glenn Kastenf78aee72012-01-04 11:00:47 -08007741void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007742{
7743 Mutex::Autolock _l(mLock);
7744 size_t size = mEffectChains.size();
7745 for (size_t i = 0; i < size; i++) {
7746 mEffectChains[i]->setMode_l(mode);
7747 }
7748}
7749
7750void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007751 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007752 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007753
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007755 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 // delete the effect module if removing last handle on it
7757 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007758 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007759 removeEffect_l(effect);
7760 AudioSystem::unregisterEffect(effect->id());
7761 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 }
7763}
7764
7765status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7766{
7767 int session = chain->sessionId();
7768 int16_t *buffer = mMixBuffer;
7769 bool ownsBuffer = false;
7770
Steve Block3856b092011-10-20 11:56:00 +01007771 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772 if (session > 0) {
7773 // Only one effect chain can be present in direct output thread and it uses
7774 // the mix buffer as input
7775 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007776 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007777 buffer = new int16_t[numSamples];
7778 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007779 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 ownsBuffer = true;
7781 }
7782
7783 // Attach all tracks with same session ID to this chain.
7784 for (size_t i = 0; i < mTracks.size(); ++i) {
7785 sp<Track> track = mTracks[i];
7786 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007787 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007789 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790 }
7791 }
7792
7793 // indicate all active tracks in the chain
7794 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7795 sp<Track> track = mActiveTracks[i].promote();
7796 if (track == 0) continue;
7797 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007798 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007799 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800 }
7801 }
7802 }
7803
7804 chain->setInBuffer(buffer, ownsBuffer);
7805 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007806 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007807 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007808 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7809 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007811 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7812 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007813 // Effect chain for other sessions are inserted at beginning of effect
7814 // chains list to be processed before output mix effects. Relative order between other
7815 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816 size_t size = mEffectChains.size();
7817 size_t i = 0;
7818 for (i = 0; i < size; i++) {
7819 if (mEffectChains[i]->sessionId() < session) break;
7820 }
7821 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007822 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823
7824 return NO_ERROR;
7825}
7826
7827size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7828{
7829 int session = chain->sessionId();
7830
Steve Block3856b092011-10-20 11:56:00 +01007831 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007832
7833 for (size_t i = 0; i < mEffectChains.size(); i++) {
7834 if (chain == mEffectChains[i]) {
7835 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007836 // detach all active tracks from the chain
7837 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7838 sp<Track> track = mActiveTracks[i].promote();
7839 if (track == 0) continue;
7840 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007841 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007842 chain.get(), session);
7843 chain->decActiveTrackCnt();
7844 }
7845 }
7846
Mathias Agopian65ab4712010-07-14 17:59:35 -07007847 // detach all tracks with same session ID from this chain
7848 for (size_t i = 0; i < mTracks.size(); ++i) {
7849 sp<Track> track = mTracks[i];
7850 if (session == track->sessionId()) {
7851 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007852 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853 }
7854 }
Eric Laurentde070132010-07-13 04:45:46 -07007855 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856 }
7857 }
7858 return mEffectChains.size();
7859}
7860
Eric Laurentde070132010-07-13 04:45:46 -07007861status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7862 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863{
7864 Mutex::Autolock _l(mLock);
7865 return attachAuxEffect_l(track, EffectId);
7866}
7867
Eric Laurentde070132010-07-13 04:45:46 -07007868status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7869 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007870{
7871 status_t status = NO_ERROR;
7872
7873 if (EffectId == 0) {
7874 track->setAuxBuffer(0, NULL);
7875 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007876 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7877 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 if (effect != 0) {
7879 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7880 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7881 } else {
7882 status = INVALID_OPERATION;
7883 }
7884 } else {
7885 status = BAD_VALUE;
7886 }
7887 }
7888 return status;
7889}
7890
7891void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7892{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007893 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894 sp<Track> track = mTracks[i];
7895 if (track->auxEffectId() == effectId) {
7896 attachAuxEffect_l(track, 0);
7897 }
7898 }
7899}
7900
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007901status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7902{
7903 // only one chain per input thread
7904 if (mEffectChains.size() != 0) {
7905 return INVALID_OPERATION;
7906 }
Steve Block3856b092011-10-20 11:56:00 +01007907 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007908
7909 chain->setInBuffer(NULL);
7910 chain->setOutBuffer(NULL);
7911
Eric Laurent59255e42011-07-27 19:49:51 -07007912 checkSuspendOnAddEffectChain_l(chain);
7913
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007914 mEffectChains.add(chain);
7915
7916 return NO_ERROR;
7917}
7918
7919size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7920{
Steve Block3856b092011-10-20 11:56:00 +01007921 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007922 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007923 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7924 chain.get(), mEffectChains.size(), this);
7925 if (mEffectChains.size() == 1) {
7926 mEffectChains.removeAt(0);
7927 }
7928 return 0;
7929}
7930
Mathias Agopian65ab4712010-07-14 17:59:35 -07007931// ----------------------------------------------------------------------------
7932// EffectModule implementation
7933// ----------------------------------------------------------------------------
7934
7935#undef LOG_TAG
7936#define LOG_TAG "AudioFlinger::EffectModule"
7937
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007938AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007939 const wp<AudioFlinger::EffectChain>& chain,
7940 effect_descriptor_t *desc,
7941 int id,
7942 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007943 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007944 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007945{
Steve Block3856b092011-10-20 11:56:00 +01007946 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007948 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 return;
7950 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951
7952 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7953
7954 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007955 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956
7957 if (mStatus != NO_ERROR) {
7958 return;
7959 }
7960 lStatus = init();
7961 if (lStatus < 0) {
7962 mStatus = lStatus;
7963 goto Error;
7964 }
7965
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007966 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7967 mPinned = true;
7968 }
Steve Block3856b092011-10-20 11:56:00 +01007969 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970 return;
7971Error:
7972 EffectRelease(mEffectInterface);
7973 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007974 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975}
7976
7977AudioFlinger::EffectModule::~EffectModule()
7978{
Steve Block3856b092011-10-20 11:56:00 +01007979 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007981 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7982 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7983 sp<ThreadBase> thread = mThread.promote();
7984 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007985 audio_stream_t *stream = thread->stream();
7986 if (stream != NULL) {
7987 stream->remove_audio_effect(stream, mEffectInterface);
7988 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007989 }
7990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991 // release effect engine
7992 EffectRelease(mEffectInterface);
7993 }
7994}
7995
Glenn Kasten435dbe62012-01-30 10:15:48 -08007996status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997{
7998 status_t status;
7999
8000 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001 int priority = handle->priority();
8002 size_t size = mHandles.size();
8003 sp<EffectHandle> h;
8004 size_t i;
8005 for (i = 0; i < size; i++) {
8006 h = mHandles[i].promote();
8007 if (h == 0) continue;
8008 if (h->priority() <= priority) break;
8009 }
8010 // if inserted in first place, move effect control from previous owner to this handle
8011 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008012 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008014 enabled = h->enabled();
8015 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016 }
Eric Laurent59255e42011-07-27 19:49:51 -07008017 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 status = NO_ERROR;
8019 } else {
8020 status = ALREADY_EXISTS;
8021 }
Steve Block3856b092011-10-20 11:56:00 +01008022 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008023 mHandles.insertAt(handle, i);
8024 return status;
8025}
8026
8027size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
8028{
8029 Mutex::Autolock _l(mLock);
8030 size_t size = mHandles.size();
8031 size_t i;
8032 for (i = 0; i < size; i++) {
8033 if (mHandles[i] == handle) break;
8034 }
8035 if (i == size) {
8036 return size;
8037 }
Steve Block3856b092011-10-20 11:56:00 +01008038 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07008039
8040 bool enabled = false;
8041 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08008042 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01008043 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07008044 enabled = hdl->enabled();
8045 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008046 mHandles.removeAt(i);
8047 size = mHandles.size();
8048 // if removed from first place, move effect control from this handle to next in line
8049 if (i == 0 && size != 0) {
8050 sp<EffectHandle> h = mHandles[0].promote();
8051 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008052 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053 }
8054 }
8055
Eric Laurentec437d82011-07-26 20:54:46 -07008056 // Prevent calls to process() and other functions on effect interface from now on.
8057 // The effect engine will be released by the destructor when the last strong reference on
8058 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008059 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008060 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008061 }
8062
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063 return size;
8064}
8065
Eric Laurent59255e42011-07-27 19:49:51 -07008066sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8067{
8068 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08008069 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008070}
8071
Glenn Kasten58123c32012-02-03 10:32:24 -08008072void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073{
Glenn Kasten90bebef2012-01-27 15:24:38 -08008074 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075 // keep a strong reference on this EffectModule to avoid calling the
8076 // destructor before we exit
8077 sp<EffectModule> keep(this);
8078 {
8079 sp<ThreadBase> thread = mThread.promote();
8080 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008081 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082 }
8083 }
8084}
8085
8086void AudioFlinger::EffectModule::updateState() {
8087 Mutex::Autolock _l(mLock);
8088
8089 switch (mState) {
8090 case RESTART:
8091 reset_l();
8092 // FALL THROUGH
8093
8094 case STARTING:
8095 // clear auxiliary effect input buffer for next accumulation
8096 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8097 memset(mConfig.inputCfg.buffer.raw,
8098 0,
8099 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8100 }
8101 start_l();
8102 mState = ACTIVE;
8103 break;
8104 case STOPPING:
8105 stop_l();
8106 mDisableWaitCnt = mMaxDisableWaitCnt;
8107 mState = STOPPED;
8108 break;
8109 case STOPPED:
8110 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8111 // turn off sequence.
8112 if (--mDisableWaitCnt == 0) {
8113 reset_l();
8114 mState = IDLE;
8115 }
8116 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008117 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118 break;
8119 }
8120}
8121
8122void AudioFlinger::EffectModule::process()
8123{
8124 Mutex::Autolock _l(mLock);
8125
Eric Laurentec437d82011-07-26 20:54:46 -07008126 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008127 mConfig.inputCfg.buffer.raw == NULL ||
8128 mConfig.outputCfg.buffer.raw == NULL) {
8129 return;
8130 }
8131
Eric Laurent8f45bd72010-08-31 13:50:07 -07008132 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008133 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8134 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008135 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008136 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008137 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 }
8139
8140 // do the actual processing in the effect engine
8141 int ret = (*mEffectInterface)->process(mEffectInterface,
8142 &mConfig.inputCfg.buffer,
8143 &mConfig.outputCfg.buffer);
8144
8145 // force transition to IDLE state when engine is ready
8146 if (mState == STOPPED && ret == -ENODATA) {
8147 mDisableWaitCnt = 1;
8148 }
8149
8150 // clear auxiliary effect input buffer for next accumulation
8151 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008152 memset(mConfig.inputCfg.buffer.raw, 0,
8153 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 }
8155 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008156 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8157 // If an insert effect is idle and input buffer is different from output buffer,
8158 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008159 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008160 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008161 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8162 int16_t *in = mConfig.inputCfg.buffer.s16;
8163 int16_t *out = mConfig.outputCfg.buffer.s16;
8164 for (size_t i = 0; i < frameCnt; i++) {
8165 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167 }
8168 }
8169}
8170
8171void AudioFlinger::EffectModule::reset_l()
8172{
8173 if (mEffectInterface == NULL) {
8174 return;
8175 }
8176 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8177}
8178
8179status_t AudioFlinger::EffectModule::configure()
8180{
8181 uint32_t channels;
8182 if (mEffectInterface == NULL) {
8183 return NO_INIT;
8184 }
8185
8186 sp<ThreadBase> thread = mThread.promote();
8187 if (thread == 0) {
8188 return DEAD_OBJECT;
8189 }
8190
8191 // TODO: handle configuration of effects replacing track process
8192 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008193 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008194 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008195 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196 }
8197
8198 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008199 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 } else {
8201 mConfig.inputCfg.channels = channels;
8202 }
8203 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008204 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8205 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008206 mConfig.inputCfg.samplingRate = thread->sampleRate();
8207 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8208 mConfig.inputCfg.bufferProvider.cookie = NULL;
8209 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8210 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8211 mConfig.outputCfg.bufferProvider.cookie = NULL;
8212 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8213 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8214 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8215 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008216 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008217 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 // - in other sessions:
8219 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8220 // other effect: overwrites output buffer: input buffer == output buffer
8221 // Auxiliary effect:
8222 // accumulates in output buffer: input buffer != output buffer
8223 // Therefore: accumulate <=> input buffer != output buffer
8224 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8225 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8226 } else {
8227 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8228 }
8229 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8230 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8231 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8232 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8233
Steve Block3856b092011-10-20 11:56:00 +01008234 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008235 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8236
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008238 uint32_t size = sizeof(int);
8239 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008240 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008241 sizeof(effect_config_t),
8242 &mConfig,
8243 &size,
8244 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008245 if (status == 0) {
8246 status = cmdStatus;
8247 }
8248
8249 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8250 (1000 * mConfig.outputCfg.buffer.frameCount);
8251
8252 return status;
8253}
8254
8255status_t AudioFlinger::EffectModule::init()
8256{
8257 Mutex::Autolock _l(mLock);
8258 if (mEffectInterface == NULL) {
8259 return NO_INIT;
8260 }
8261 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008262 uint32_t size = sizeof(status_t);
8263 status_t status = (*mEffectInterface)->command(mEffectInterface,
8264 EFFECT_CMD_INIT,
8265 0,
8266 NULL,
8267 &size,
8268 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008269 if (status == 0) {
8270 status = cmdStatus;
8271 }
8272 return status;
8273}
8274
Eric Laurentec35a142011-10-05 17:42:25 -07008275status_t AudioFlinger::EffectModule::start()
8276{
8277 Mutex::Autolock _l(mLock);
8278 return start_l();
8279}
8280
Mathias Agopian65ab4712010-07-14 17:59:35 -07008281status_t AudioFlinger::EffectModule::start_l()
8282{
8283 if (mEffectInterface == NULL) {
8284 return NO_INIT;
8285 }
8286 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008287 uint32_t size = sizeof(status_t);
8288 status_t status = (*mEffectInterface)->command(mEffectInterface,
8289 EFFECT_CMD_ENABLE,
8290 0,
8291 NULL,
8292 &size,
8293 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294 if (status == 0) {
8295 status = cmdStatus;
8296 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008297 if (status == 0 &&
8298 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8299 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8300 sp<ThreadBase> thread = mThread.promote();
8301 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008302 audio_stream_t *stream = thread->stream();
8303 if (stream != NULL) {
8304 stream->add_audio_effect(stream, mEffectInterface);
8305 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008306 }
8307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308 return status;
8309}
8310
Eric Laurentec437d82011-07-26 20:54:46 -07008311status_t AudioFlinger::EffectModule::stop()
8312{
8313 Mutex::Autolock _l(mLock);
8314 return stop_l();
8315}
8316
Mathias Agopian65ab4712010-07-14 17:59:35 -07008317status_t AudioFlinger::EffectModule::stop_l()
8318{
8319 if (mEffectInterface == NULL) {
8320 return NO_INIT;
8321 }
8322 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008323 uint32_t size = sizeof(status_t);
8324 status_t status = (*mEffectInterface)->command(mEffectInterface,
8325 EFFECT_CMD_DISABLE,
8326 0,
8327 NULL,
8328 &size,
8329 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 if (status == 0) {
8331 status = cmdStatus;
8332 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008333 if (status == 0 &&
8334 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8335 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8336 sp<ThreadBase> thread = mThread.promote();
8337 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008338 audio_stream_t *stream = thread->stream();
8339 if (stream != NULL) {
8340 stream->remove_audio_effect(stream, mEffectInterface);
8341 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008342 }
8343 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008344 return status;
8345}
8346
Eric Laurent25f43952010-07-28 05:40:18 -07008347status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8348 uint32_t cmdSize,
8349 void *pCmdData,
8350 uint32_t *replySize,
8351 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008352{
8353 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008354// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355
Eric Laurentec437d82011-07-26 20:54:46 -07008356 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 return NO_INIT;
8358 }
Eric Laurent25f43952010-07-28 05:40:18 -07008359 status_t status = (*mEffectInterface)->command(mEffectInterface,
8360 cmdCode,
8361 cmdSize,
8362 pCmdData,
8363 replySize,
8364 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008365 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008366 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008367 for (size_t i = 1; i < mHandles.size(); i++) {
8368 sp<EffectHandle> h = mHandles[i].promote();
8369 if (h != 0) {
8370 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8371 }
8372 }
8373 }
8374 return status;
8375}
8376
8377status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8378{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008379
Mathias Agopian65ab4712010-07-14 17:59:35 -07008380 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008381 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382
8383 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008384 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8385 if (enabled && status != NO_ERROR) {
8386 return status;
8387 }
8388
Mathias Agopian65ab4712010-07-14 17:59:35 -07008389 switch (mState) {
8390 // going from disabled to enabled
8391 case IDLE:
8392 mState = STARTING;
8393 break;
8394 case STOPPED:
8395 mState = RESTART;
8396 break;
8397 case STOPPING:
8398 mState = ACTIVE;
8399 break;
8400
8401 // going from enabled to disabled
8402 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008403 mState = STOPPED;
8404 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 case STARTING:
8406 mState = IDLE;
8407 break;
8408 case ACTIVE:
8409 mState = STOPPING;
8410 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008411 case DESTROYED:
8412 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413 }
8414 for (size_t i = 1; i < mHandles.size(); i++) {
8415 sp<EffectHandle> h = mHandles[i].promote();
8416 if (h != 0) {
8417 h->setEnabled(enabled);
8418 }
8419 }
8420 }
8421 return NO_ERROR;
8422}
8423
Glenn Kastenc59c0042012-02-02 14:06:11 -08008424bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425{
8426 switch (mState) {
8427 case RESTART:
8428 case STARTING:
8429 case ACTIVE:
8430 return true;
8431 case IDLE:
8432 case STOPPING:
8433 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008434 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008435 default:
8436 return false;
8437 }
8438}
8439
Glenn Kastenc59c0042012-02-02 14:06:11 -08008440bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008441{
8442 switch (mState) {
8443 case RESTART:
8444 case ACTIVE:
8445 case STOPPING:
8446 case STOPPED:
8447 return true;
8448 case IDLE:
8449 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008450 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008451 default:
8452 return false;
8453 }
8454}
8455
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8457{
8458 Mutex::Autolock _l(mLock);
8459 status_t status = NO_ERROR;
8460
8461 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8462 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008463 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008464 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8465 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008466 status_t cmdStatus;
8467 uint32_t volume[2];
8468 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008469 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470 volume[0] = *left;
8471 volume[1] = *right;
8472 if (controller) {
8473 pVolume = volume;
8474 }
Eric Laurent25f43952010-07-28 05:40:18 -07008475 status = (*mEffectInterface)->command(mEffectInterface,
8476 EFFECT_CMD_SET_VOLUME,
8477 size,
8478 volume,
8479 &size,
8480 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008481 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8482 *left = volume[0];
8483 *right = volume[1];
8484 }
8485 }
8486 return status;
8487}
8488
8489status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8490{
8491 Mutex::Autolock _l(mLock);
8492 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008493 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8494 // audio pre processing modules on RecordThread can receive both output and
8495 // input device indication in the same call
8496 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8497 if (dev) {
8498 status_t cmdStatus;
8499 uint32_t size = sizeof(status_t);
8500
8501 status = (*mEffectInterface)->command(mEffectInterface,
8502 EFFECT_CMD_SET_DEVICE,
8503 sizeof(uint32_t),
8504 &dev,
8505 &size,
8506 &cmdStatus);
8507 if (status == NO_ERROR) {
8508 status = cmdStatus;
8509 }
8510 }
8511 dev = device & AUDIO_DEVICE_IN_ALL;
8512 if (dev) {
8513 status_t cmdStatus;
8514 uint32_t size = sizeof(status_t);
8515
8516 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8517 EFFECT_CMD_SET_INPUT_DEVICE,
8518 sizeof(uint32_t),
8519 &dev,
8520 &size,
8521 &cmdStatus);
8522 if (status2 == NO_ERROR) {
8523 status2 = cmdStatus;
8524 }
8525 if (status == NO_ERROR) {
8526 status = status2;
8527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528 }
8529 }
8530 return status;
8531}
8532
Glenn Kastenf78aee72012-01-04 11:00:47 -08008533status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008534{
8535 Mutex::Autolock _l(mLock);
8536 status_t status = NO_ERROR;
8537 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008539 uint32_t size = sizeof(status_t);
8540 status = (*mEffectInterface)->command(mEffectInterface,
8541 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008542 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008543 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008544 &size,
8545 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008546 if (status == NO_ERROR) {
8547 status = cmdStatus;
8548 }
8549 }
8550 return status;
8551}
8552
Eric Laurent59255e42011-07-27 19:49:51 -07008553void AudioFlinger::EffectModule::setSuspended(bool suspended)
8554{
8555 Mutex::Autolock _l(mLock);
8556 mSuspended = suspended;
8557}
Glenn Kastena3a85482012-01-04 11:01:11 -08008558
8559bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008560{
8561 Mutex::Autolock _l(mLock);
8562 return mSuspended;
8563}
8564
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8566{
8567 const size_t SIZE = 256;
8568 char buffer[SIZE];
8569 String8 result;
8570
8571 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8572 result.append(buffer);
8573
8574 bool locked = tryLock(mLock);
8575 // failed to lock - AudioFlinger is probably deadlocked
8576 if (!locked) {
8577 result.append("\t\tCould not lock Fx mutex:\n");
8578 }
8579
8580 result.append("\t\tSession Status State Engine:\n");
8581 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8582 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8583 result.append(buffer);
8584
8585 result.append("\t\tDescriptor:\n");
8586 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8587 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8588 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8589 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8590 result.append(buffer);
8591 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8592 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8593 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8594 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8595 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008596 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008597 mDescriptor.apiVersion,
8598 mDescriptor.flags);
8599 result.append(buffer);
8600 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8601 mDescriptor.name);
8602 result.append(buffer);
8603 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8604 mDescriptor.implementor);
8605 result.append(buffer);
8606
8607 result.append("\t\t- Input configuration:\n");
8608 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8609 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8610 (uint32_t)mConfig.inputCfg.buffer.raw,
8611 mConfig.inputCfg.buffer.frameCount,
8612 mConfig.inputCfg.samplingRate,
8613 mConfig.inputCfg.channels,
8614 mConfig.inputCfg.format);
8615 result.append(buffer);
8616
8617 result.append("\t\t- Output configuration:\n");
8618 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8619 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8620 (uint32_t)mConfig.outputCfg.buffer.raw,
8621 mConfig.outputCfg.buffer.frameCount,
8622 mConfig.outputCfg.samplingRate,
8623 mConfig.outputCfg.channels,
8624 mConfig.outputCfg.format);
8625 result.append(buffer);
8626
8627 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8628 result.append(buffer);
8629 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8630 for (size_t i = 0; i < mHandles.size(); ++i) {
8631 sp<EffectHandle> handle = mHandles[i].promote();
8632 if (handle != 0) {
8633 handle->dump(buffer, SIZE);
8634 result.append(buffer);
8635 }
8636 }
8637
8638 result.append("\n");
8639
8640 write(fd, result.string(), result.length());
8641
8642 if (locked) {
8643 mLock.unlock();
8644 }
8645
8646 return NO_ERROR;
8647}
8648
8649// ----------------------------------------------------------------------------
8650// EffectHandle implementation
8651// ----------------------------------------------------------------------------
8652
8653#undef LOG_TAG
8654#define LOG_TAG "AudioFlinger::EffectHandle"
8655
8656AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8657 const sp<AudioFlinger::Client>& client,
8658 const sp<IEffectClient>& effectClient,
8659 int32_t priority)
8660 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008661 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008662 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008663{
Steve Block3856b092011-10-20 11:56:00 +01008664 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008665
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008666 if (client == 0) {
8667 return;
8668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008669 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8670 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8671 if (mCblkMemory != 0) {
8672 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8673
Glenn Kastena0d68332012-01-27 16:47:15 -08008674 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008675 new(mCblk) effect_param_cblk_t();
8676 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008678 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008679 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008680 return;
8681 }
8682}
8683
8684AudioFlinger::EffectHandle::~EffectHandle()
8685{
Steve Block3856b092011-10-20 11:56:00 +01008686 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008687 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008688 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008689}
8690
8691status_t AudioFlinger::EffectHandle::enable()
8692{
Steve Block3856b092011-10-20 11:56:00 +01008693 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008694 if (!mHasControl) return INVALID_OPERATION;
8695 if (mEffect == 0) return DEAD_OBJECT;
8696
Eric Laurentdb7c0792011-08-10 10:37:50 -07008697 if (mEnabled) {
8698 return NO_ERROR;
8699 }
8700
Eric Laurent59255e42011-07-27 19:49:51 -07008701 mEnabled = true;
8702
8703 sp<ThreadBase> thread = mEffect->thread().promote();
8704 if (thread != 0) {
8705 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8706 }
8707
8708 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8709 if (mEffect->suspended()) {
8710 return NO_ERROR;
8711 }
8712
Eric Laurentdb7c0792011-08-10 10:37:50 -07008713 status_t status = mEffect->setEnabled(true);
8714 if (status != NO_ERROR) {
8715 if (thread != 0) {
8716 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8717 }
8718 mEnabled = false;
8719 }
8720 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008721}
8722
8723status_t AudioFlinger::EffectHandle::disable()
8724{
Steve Block3856b092011-10-20 11:56:00 +01008725 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008726 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008727 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008728
Eric Laurentdb7c0792011-08-10 10:37:50 -07008729 if (!mEnabled) {
8730 return NO_ERROR;
8731 }
Eric Laurent59255e42011-07-27 19:49:51 -07008732 mEnabled = false;
8733
8734 if (mEffect->suspended()) {
8735 return NO_ERROR;
8736 }
8737
8738 status_t status = mEffect->setEnabled(false);
8739
8740 sp<ThreadBase> thread = mEffect->thread().promote();
8741 if (thread != 0) {
8742 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8743 }
8744
8745 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746}
8747
8748void AudioFlinger::EffectHandle::disconnect()
8749{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008750 disconnect(true);
8751}
8752
Glenn Kasten58123c32012-02-03 10:32:24 -08008753void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008754{
Glenn Kasten58123c32012-02-03 10:32:24 -08008755 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756 if (mEffect == 0) {
8757 return;
8758 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008759 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008760
Eric Laurenta85a74a2011-10-19 11:44:54 -07008761 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008762 sp<ThreadBase> thread = mEffect->thread().promote();
8763 if (thread != 0) {
8764 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8765 }
Eric Laurent59255e42011-07-27 19:49:51 -07008766 }
8767
Mathias Agopian65ab4712010-07-14 17:59:35 -07008768 // release sp on module => module destructor can be called now
8769 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008770 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008771 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008772 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008773 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8774 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008775 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008776 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008777 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8778 mClient.clear();
8779 }
8780}
8781
Eric Laurent25f43952010-07-28 05:40:18 -07008782status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8783 uint32_t cmdSize,
8784 void *pCmdData,
8785 uint32_t *replySize,
8786 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008787{
Steve Block3856b092011-10-20 11:56:00 +01008788// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008789// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790
8791 // only get parameter command is permitted for applications not controlling the effect
8792 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8793 return INVALID_OPERATION;
8794 }
8795 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008796 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008797
8798 // handle commands that are not forwarded transparently to effect engine
8799 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8800 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8801 // no risk to block the whole media server process or mixer threads is we are stuck here
8802 Mutex::Autolock _l(mCblk->lock);
8803 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8804 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8805 mCblk->serverIndex = 0;
8806 mCblk->clientIndex = 0;
8807 return BAD_VALUE;
8808 }
8809 status_t status = NO_ERROR;
8810 while (mCblk->serverIndex < mCblk->clientIndex) {
8811 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008812 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 int *p = (int *)(mBuffer + mCblk->serverIndex);
8814 int size = *p++;
8815 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008816 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008817 break;
8818 }
8819 effect_param_t *param = (effect_param_t *)p;
8820 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008821 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008822 mCblk->serverIndex += size;
8823 continue;
8824 }
Eric Laurent25f43952010-07-28 05:40:18 -07008825 uint32_t psize = sizeof(effect_param_t) +
8826 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8827 param->vsize;
8828 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8829 psize,
8830 p,
8831 &rsize,
8832 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008833 // stop at first error encountered
8834 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008836 *(int *)pReplyData = reply;
8837 break;
8838 } else if (reply != NO_ERROR) {
8839 *(int *)pReplyData = reply;
8840 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008841 }
8842 mCblk->serverIndex += size;
8843 }
8844 mCblk->serverIndex = 0;
8845 mCblk->clientIndex = 0;
8846 return status;
8847 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008848 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008849 return enable();
8850 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008851 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008852 return disable();
8853 }
8854
8855 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8856}
8857
Eric Laurent59255e42011-07-27 19:49:51 -07008858void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008859{
Steve Block3856b092011-10-20 11:56:00 +01008860 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008861
8862 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008863 mEnabled = enabled;
8864
Mathias Agopian65ab4712010-07-14 17:59:35 -07008865 if (signal && mEffectClient != 0) {
8866 mEffectClient->controlStatusChanged(hasControl);
8867 }
8868}
8869
Eric Laurent25f43952010-07-28 05:40:18 -07008870void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8871 uint32_t cmdSize,
8872 void *pCmdData,
8873 uint32_t replySize,
8874 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008875{
8876 if (mEffectClient != 0) {
8877 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8878 }
8879}
8880
8881
8882
8883void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8884{
8885 if (mEffectClient != 0) {
8886 mEffectClient->enableStatusChanged(enabled);
8887 }
8888}
8889
8890status_t AudioFlinger::EffectHandle::onTransact(
8891 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8892{
8893 return BnEffect::onTransact(code, data, reply, flags);
8894}
8895
8896
8897void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8898{
Glenn Kastena0d68332012-01-27 16:47:15 -08008899 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008900
8901 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008902 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903 mPriority,
8904 mHasControl,
8905 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008906 mCblk ? mCblk->clientIndex : 0,
8907 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008908 );
8909
8910 if (locked) {
8911 mCblk->lock.unlock();
8912 }
8913}
8914
8915#undef LOG_TAG
8916#define LOG_TAG "AudioFlinger::EffectChain"
8917
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008918AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008919 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008920 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008921 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8922 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008923{
Dima Zavinfce7a472011-04-19 22:30:36 -07008924 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008925 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008926 return;
8927 }
8928 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8929 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008930}
8931
8932AudioFlinger::EffectChain::~EffectChain()
8933{
8934 if (mOwnInBuffer) {
8935 delete mInBuffer;
8936 }
8937
8938}
8939
Eric Laurent59255e42011-07-27 19:49:51 -07008940// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008941sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008942{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008943 size_t size = mEffects.size();
8944
8945 for (size_t i = 0; i < size; i++) {
8946 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008947 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008948 }
8949 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008950 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008951}
8952
Eric Laurent59255e42011-07-27 19:49:51 -07008953// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008954sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008955{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008956 size_t size = mEffects.size();
8957
8958 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008959 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8960 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008961 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008962 }
8963 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008964 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008965}
8966
Eric Laurent59255e42011-07-27 19:49:51 -07008967// getEffectFromType_l() must be called with ThreadBase::mLock held
8968sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8969 const effect_uuid_t *type)
8970{
Eric Laurent59255e42011-07-27 19:49:51 -07008971 size_t size = mEffects.size();
8972
8973 for (size_t i = 0; i < size; i++) {
8974 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008975 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008976 }
8977 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008978 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008979}
8980
Mathias Agopian65ab4712010-07-14 17:59:35 -07008981// Must be called with EffectChain::mLock locked
8982void AudioFlinger::EffectChain::process_l()
8983{
Eric Laurentdac69112010-09-28 14:09:57 -07008984 sp<ThreadBase> thread = mThread.promote();
8985 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008986 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008987 return;
8988 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008989 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8990 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008991 // always process effects unless no more tracks are on the session and the effect tail
8992 // has been rendered
8993 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008994 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008995 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008996
Eric Laurent544fe9b2011-11-11 15:42:52 -08008997 if (!tracksOnSession && mTailBufferCount == 0) {
8998 doProcess = false;
8999 }
9000
9001 if (activeTrackCnt() == 0) {
9002 // if no track is active and the effect tail has not been rendered,
9003 // the input buffer must be cleared here as the mixer process will not do it
9004 if (tracksOnSession || mTailBufferCount > 0) {
9005 size_t numSamples = thread->frameCount() * thread->channelCount();
9006 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9007 if (mTailBufferCount > 0) {
9008 mTailBufferCount--;
9009 }
9010 }
9011 }
Eric Laurentdac69112010-09-28 14:09:57 -07009012 }
9013
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009015 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009016 for (size_t i = 0; i < size; i++) {
9017 mEffects[i]->process();
9018 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009019 }
9020 for (size_t i = 0; i < size; i++) {
9021 mEffects[i]->updateState();
9022 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023}
9024
Eric Laurentcab11242010-07-15 12:50:15 -07009025// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009026status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027{
9028 effect_descriptor_t desc = effect->desc();
9029 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9030
9031 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009032 effect->setChain(this);
9033 sp<ThreadBase> thread = mThread.promote();
9034 if (thread == 0) {
9035 return NO_INIT;
9036 }
9037 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038
9039 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9040 // Auxiliary effects are inserted at the beginning of mEffects vector as
9041 // they are processed first and accumulated in chain input buffer
9042 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009043
Mathias Agopian65ab4712010-07-14 17:59:35 -07009044 // the input buffer for auxiliary effect contains mono samples in
9045 // 32 bit format. This is to avoid saturation in AudoMixer
9046 // accumulation stage. Saturation is done in EffectModule::process() before
9047 // calling the process in effect engine
9048 size_t numSamples = thread->frameCount();
9049 int32_t *buffer = new int32_t[numSamples];
9050 memset(buffer, 0, numSamples * sizeof(int32_t));
9051 effect->setInBuffer((int16_t *)buffer);
9052 // auxiliary effects output samples to chain input buffer for further processing
9053 // by insert effects
9054 effect->setOutBuffer(mInBuffer);
9055 } else {
9056 // Insert effects are inserted at the end of mEffects vector as they are processed
9057 // after track and auxiliary effects.
9058 // Insert effect order as a function of indicated preference:
9059 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9060 // another effect is present
9061 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9062 // last effect claiming first position
9063 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9064 // first effect claiming last position
9065 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9066 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9067 // already present
9068
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009069 size_t size = mEffects.size();
9070 size_t idx_insert = size;
9071 ssize_t idx_insert_first = -1;
9072 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009073
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009074 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009075 effect_descriptor_t d = mEffects[i]->desc();
9076 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9077 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9078 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9079 // check invalid effect chaining combinations
9080 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9081 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009082 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009083 return INVALID_OPERATION;
9084 }
9085 // remember position of first insert effect and by default
9086 // select this as insert position for new effect
9087 if (idx_insert == size) {
9088 idx_insert = i;
9089 }
9090 // remember position of last insert effect claiming
9091 // first position
9092 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9093 idx_insert_first = i;
9094 }
9095 // remember position of first insert effect claiming
9096 // last position
9097 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9098 idx_insert_last == -1) {
9099 idx_insert_last = i;
9100 }
9101 }
9102 }
9103
9104 // modify idx_insert from first position if needed
9105 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9106 if (idx_insert_last != -1) {
9107 idx_insert = idx_insert_last;
9108 } else {
9109 idx_insert = size;
9110 }
9111 } else {
9112 if (idx_insert_first != -1) {
9113 idx_insert = idx_insert_first + 1;
9114 }
9115 }
9116
9117 // always read samples from chain input buffer
9118 effect->setInBuffer(mInBuffer);
9119
9120 // if last effect in the chain, output samples to chain
9121 // output buffer, otherwise to chain input buffer
9122 if (idx_insert == size) {
9123 if (idx_insert != 0) {
9124 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9125 mEffects[idx_insert-1]->configure();
9126 }
9127 effect->setOutBuffer(mOutBuffer);
9128 } else {
9129 effect->setOutBuffer(mInBuffer);
9130 }
9131 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009132
Steve Block3856b092011-10-20 11:56:00 +01009133 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009134 }
9135 effect->configure();
9136 return NO_ERROR;
9137}
9138
Eric Laurentcab11242010-07-15 12:50:15 -07009139// removeEffect_l() must be called with PlaybackThread::mLock held
9140size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009141{
9142 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009143 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009144 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9145
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009146 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009147 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009148 // calling stop here will remove pre-processing effect from the audio HAL.
9149 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9150 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009151 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9152 mEffects[i]->state() == EffectModule::STOPPING) {
9153 mEffects[i]->stop();
9154 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009155 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9156 delete[] effect->inBuffer();
9157 } else {
9158 if (i == size - 1 && i != 0) {
9159 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9160 mEffects[i - 1]->configure();
9161 }
9162 }
9163 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009164 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009165 break;
9166 }
9167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009168
9169 return mEffects.size();
9170}
9171
Eric Laurentcab11242010-07-15 12:50:15 -07009172// setDevice_l() must be called with PlaybackThread::mLock held
9173void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009174{
9175 size_t size = mEffects.size();
9176 for (size_t i = 0; i < size; i++) {
9177 mEffects[i]->setDevice(device);
9178 }
9179}
9180
Eric Laurentcab11242010-07-15 12:50:15 -07009181// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009182void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009183{
9184 size_t size = mEffects.size();
9185 for (size_t i = 0; i < size; i++) {
9186 mEffects[i]->setMode(mode);
9187 }
9188}
9189
Eric Laurentcab11242010-07-15 12:50:15 -07009190// setVolume_l() must be called with PlaybackThread::mLock held
9191bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009192{
9193 uint32_t newLeft = *left;
9194 uint32_t newRight = *right;
9195 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009196 int ctrlIdx = -1;
9197 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009198
Eric Laurentcab11242010-07-15 12:50:15 -07009199 // first update volume controller
9200 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009201 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009202 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9203 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009204 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009205 break;
9206 }
9207 }
9208
9209 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009210 if (hasControl) {
9211 *left = mNewLeftVolume;
9212 *right = mNewRightVolume;
9213 }
9214 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009215 }
9216
9217 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009218 mLeftVolume = newLeft;
9219 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009220
9221 // second get volume update from volume controller
9222 if (ctrlIdx >= 0) {
9223 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009224 mNewLeftVolume = newLeft;
9225 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009226 }
9227 // then indicate volume to all other effects in chain.
9228 // Pass altered volume to effects before volume controller
9229 // and requested volume to effects after controller
9230 uint32_t lVol = newLeft;
9231 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009232
Mathias Agopian65ab4712010-07-14 17:59:35 -07009233 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009234 if ((int)i == ctrlIdx) continue;
9235 // this also works for ctrlIdx == -1 when there is no volume controller
9236 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237 lVol = *left;
9238 rVol = *right;
9239 }
9240 mEffects[i]->setVolume(&lVol, &rVol, false);
9241 }
9242 *left = newLeft;
9243 *right = newRight;
9244
9245 return hasControl;
9246}
9247
Mathias Agopian65ab4712010-07-14 17:59:35 -07009248status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9249{
9250 const size_t SIZE = 256;
9251 char buffer[SIZE];
9252 String8 result;
9253
9254 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9255 result.append(buffer);
9256
9257 bool locked = tryLock(mLock);
9258 // failed to lock - AudioFlinger is probably deadlocked
9259 if (!locked) {
9260 result.append("\tCould not lock mutex:\n");
9261 }
9262
Eric Laurentcab11242010-07-15 12:50:15 -07009263 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9264 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009265 mEffects.size(),
9266 (uint32_t)mInBuffer,
9267 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009268 mActiveTrackCnt);
9269 result.append(buffer);
9270 write(fd, result.string(), result.size());
9271
9272 for (size_t i = 0; i < mEffects.size(); ++i) {
9273 sp<EffectModule> effect = mEffects[i];
9274 if (effect != 0) {
9275 effect->dump(fd, args);
9276 }
9277 }
9278
9279 if (locked) {
9280 mLock.unlock();
9281 }
9282
9283 return NO_ERROR;
9284}
9285
Eric Laurent59255e42011-07-27 19:49:51 -07009286// must be called with ThreadBase::mLock held
9287void AudioFlinger::EffectChain::setEffectSuspended_l(
9288 const effect_uuid_t *type, bool suspend)
9289{
9290 sp<SuspendedEffectDesc> desc;
9291 // use effect type UUID timelow as key as there is no real risk of identical
9292 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009293 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009294 if (suspend) {
9295 if (index >= 0) {
9296 desc = mSuspendedEffects.valueAt(index);
9297 } else {
9298 desc = new SuspendedEffectDesc();
9299 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9300 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009301 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009302 }
9303 if (desc->mRefCount++ == 0) {
9304 sp<EffectModule> effect = getEffectIfEnabled(type);
9305 if (effect != 0) {
9306 desc->mEffect = effect;
9307 effect->setSuspended(true);
9308 effect->setEnabled(false);
9309 }
9310 }
9311 } else {
9312 if (index < 0) {
9313 return;
9314 }
9315 desc = mSuspendedEffects.valueAt(index);
9316 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009317 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009318 desc->mRefCount = 1;
9319 }
9320 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009321 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009322 if (desc->mEffect != 0) {
9323 sp<EffectModule> effect = desc->mEffect.promote();
9324 if (effect != 0) {
9325 effect->setSuspended(false);
9326 sp<EffectHandle> handle = effect->controlHandle();
9327 if (handle != 0) {
9328 effect->setEnabled(handle->enabled());
9329 }
9330 }
9331 desc->mEffect.clear();
9332 }
9333 mSuspendedEffects.removeItemsAt(index);
9334 }
9335 }
9336}
9337
9338// must be called with ThreadBase::mLock held
9339void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9340{
9341 sp<SuspendedEffectDesc> desc;
9342
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009343 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009344 if (suspend) {
9345 if (index >= 0) {
9346 desc = mSuspendedEffects.valueAt(index);
9347 } else {
9348 desc = new SuspendedEffectDesc();
9349 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009350 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009351 }
9352 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009353 Vector< sp<EffectModule> > effects;
9354 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009355 for (size_t i = 0; i < effects.size(); i++) {
9356 setEffectSuspended_l(&effects[i]->desc().type, true);
9357 }
9358 }
9359 } else {
9360 if (index < 0) {
9361 return;
9362 }
9363 desc = mSuspendedEffects.valueAt(index);
9364 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009365 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009366 desc->mRefCount = 1;
9367 }
9368 if (--desc->mRefCount == 0) {
9369 Vector<const effect_uuid_t *> types;
9370 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9371 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9372 continue;
9373 }
9374 types.add(&mSuspendedEffects.valueAt(i)->mType);
9375 }
9376 for (size_t i = 0; i < types.size(); i++) {
9377 setEffectSuspended_l(types[i], false);
9378 }
Steve Block3856b092011-10-20 11:56:00 +01009379 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009380 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9381 }
9382 }
9383}
9384
Eric Laurent6bffdb82011-09-23 08:40:41 -07009385
9386// The volume effect is used for automated tests only
9387#ifndef OPENSL_ES_H_
9388static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9389 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9390const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9391#endif //OPENSL_ES_H_
9392
Eric Laurentdb7c0792011-08-10 10:37:50 -07009393bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9394{
9395 // auxiliary effects and visualizer are never suspended on output mix
9396 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9397 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009398 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9399 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009400 return false;
9401 }
9402 return true;
9403}
9404
Glenn Kastend0539712012-01-30 12:56:03 -08009405void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009406{
Glenn Kastend0539712012-01-30 12:56:03 -08009407 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009408 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009409 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9410 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009411 }
Eric Laurent59255e42011-07-27 19:49:51 -07009412 }
Eric Laurent59255e42011-07-27 19:49:51 -07009413}
9414
9415sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9416 const effect_uuid_t *type)
9417{
Glenn Kasten090f0192012-01-30 13:00:02 -08009418 sp<EffectModule> effect = getEffectFromType_l(type);
9419 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009420}
9421
9422void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9423 bool enabled)
9424{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009425 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009426 if (enabled) {
9427 if (index < 0) {
9428 // if the effect is not suspend check if all effects are suspended
9429 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9430 if (index < 0) {
9431 return;
9432 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009433 if (!isEffectEligibleForSuspend(effect->desc())) {
9434 return;
9435 }
Eric Laurent59255e42011-07-27 19:49:51 -07009436 setEffectSuspended_l(&effect->desc().type, enabled);
9437 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009438 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009439 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009440 return;
9441 }
Eric Laurent59255e42011-07-27 19:49:51 -07009442 }
Steve Block3856b092011-10-20 11:56:00 +01009443 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009444 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009445 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9446 // if effect is requested to suspended but was not yet enabled, supend it now.
9447 if (desc->mEffect == 0) {
9448 desc->mEffect = effect;
9449 effect->setEnabled(false);
9450 effect->setSuspended(true);
9451 }
9452 } else {
9453 if (index < 0) {
9454 return;
9455 }
Steve Block3856b092011-10-20 11:56:00 +01009456 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009457 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009458 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9459 desc->mEffect.clear();
9460 effect->setSuspended(false);
9461 }
9462}
9463
Mathias Agopian65ab4712010-07-14 17:59:35 -07009464#undef LOG_TAG
9465#define LOG_TAG "AudioFlinger"
9466
9467// ----------------------------------------------------------------------------
9468
9469status_t AudioFlinger::onTransact(
9470 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9471{
9472 return BnAudioFlinger::onTransact(code, data, reply, flags);
9473}
9474
Mathias Agopian65ab4712010-07-14 17:59:35 -07009475}; // namespace android