blob: bf4088607a7aabd339fd828d7769eac9f877ff48 [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());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001608 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609
1610 dumpBase(fd, args);
1611
1612 return NO_ERROR;
1613}
1614
1615// Thread virtuals
1616status_t AudioFlinger::PlaybackThread::readyToRun()
1617{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001618 status_t status = initCheck();
1619 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001620 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001621 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001622 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001624 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625}
1626
1627void AudioFlinger::PlaybackThread::onFirstRef()
1628{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001629 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630}
1631
1632// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001633sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001635 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001637 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001638 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 int frameCount,
1640 const sp<IMemory>& sharedBuffer,
1641 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001642 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001643 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644 status_t *status)
1645{
1646 sp<Track> track;
1647 status_t lStatus;
1648
Glenn Kasten73d22752012-03-19 13:38:30 -07001649 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1650
1651 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001652 if (flags & IAudioFlinger::TRACK_FAST) {
1653 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001654 // not timed
1655 (!isTimed) &&
1656 // either of these use cases:
1657 (
1658 // use case 1: shared buffer with any frame count
1659 (
1660 (sharedBuffer != 0)
1661 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001662 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001663 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001664 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001665 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001666 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001667 )
1668 ) &&
1669 // PCM data
1670 audio_is_linear_pcm(format) &&
1671 // mono or stereo
1672 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1673 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001674#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001675 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001676 (sampleRate == mSampleRate) &&
1677#endif
1678 // normal mixer has an associated fast mixer
1679 hasFastMixer() &&
1680 // there are sufficient fast track slots available
1681 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001682 // FIXME test that MixerThread for this fast track has a capable output HAL
1683 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001684 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001685 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1686 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001687 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001688 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001689 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001690 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001691 } else {
1692 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001693 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1694 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1695 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1696 audio_is_linear_pcm(format),
1697 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001698 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001699 // For compatibility with AudioTrack calculation, buffer depth is forced
1700 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1701 // This is probably too conservative, but legacy application code may depend on it.
1702 // If you change this calculation, also review the start threshold which is related.
1703 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1704 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1705 if (minBufCount < 2) {
1706 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001707 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001708 int minFrameCount = mNormalFrameCount * minBufCount;
1709 if (frameCount < minFrameCount) {
1710 frameCount = minFrameCount;
1711 }
1712 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001713 }
1714
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001716 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1717 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001718 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001719 "for output %p with format %d",
1720 sampleRate, format, channelMask, mOutput, mFormat);
1721 lStatus = BAD_VALUE;
1722 goto Exit;
1723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 }
1725 } else {
1726 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1727 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001728 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 lStatus = BAD_VALUE;
1730 goto Exit;
1731 }
1732 }
1733
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001734 lStatus = initCheck();
1735 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001736 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737 goto Exit;
1738 }
1739
1740 { // scope for mLock
1741 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001742
1743 // all tracks in same audio session must share the same routing strategy otherwise
1744 // conflicts will happen when tracks are moved from one output to another by audio policy
1745 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001746 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001747 for (size_t i = 0; i < mTracks.size(); ++i) {
1748 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001749 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001750 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001751 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001752 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001753 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001754 lStatus = BAD_VALUE;
1755 goto Exit;
1756 }
1757 }
1758 }
1759
John Grossman4ff14ba2012-02-08 16:37:41 -08001760 if (!isTimed) {
1761 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001762 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001763 } else {
1764 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1765 channelMask, frameCount, sharedBuffer, sessionId);
1766 }
1767 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 lStatus = NO_MEMORY;
1769 goto Exit;
1770 }
1771 mTracks.add(track);
1772
1773 sp<EffectChain> chain = getEffectChain_l(sessionId);
1774 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001775 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001777 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001778 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 }
1780 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001781
1782#ifdef HAVE_REQUEST_PRIORITY
1783 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1784 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1785 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1786 // so ask activity manager to do this on our behalf
1787 int err = requestPriority(callingPid, tid, 1);
1788 if (err != 0) {
1789 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1790 1, callingPid, tid, err);
1791 }
1792 }
1793#endif
1794
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 lStatus = NO_ERROR;
1796
1797Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001798 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 *status = lStatus;
1800 }
1801 return track;
1802}
1803
Eric Laurente737cda2012-05-22 18:55:44 -07001804uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1805{
1806 if (mFastMixer != NULL) {
1807 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1808 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1809 }
1810 return latency;
1811}
1812
1813uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1814{
1815 return latency;
1816}
1817
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818uint32_t AudioFlinger::PlaybackThread::latency() const
1819{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001820 Mutex::Autolock _l(mLock);
1821 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001822 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001823 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 return 0;
1825 }
1826}
1827
Glenn Kasten6637baa2012-01-09 09:40:36 -08001828void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001830 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832}
1833
Glenn Kasten6637baa2012-01-09 09:40:36 -08001834void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001836 Mutex::Autolock _l(mLock);
1837 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838}
1839
Glenn Kasten6637baa2012-01-09 09:40:36 -08001840void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001842 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844}
1845
Glenn Kasten6637baa2012-01-09 09:40:36 -08001846void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001848 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850}
1851
Glenn Kastenfff6d712012-01-12 16:38:12 -08001852float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001854 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 return mStreamTypes[stream].volume;
1856}
1857
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858// addTrack_l() must be called with ThreadBase::mLock held
1859status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1860{
1861 status_t status = ALREADY_EXISTS;
1862
1863 // set retry count for buffer fill
1864 track->mRetryCount = kMaxTrackStartupRetries;
1865 if (mActiveTracks.indexOf(track) < 0) {
1866 // the track is newly added, make sure it fills up all its
1867 // buffers before playing. This is to ensure the client will
1868 // effectively get the latency it requested.
1869 track->mFillingUpStatus = Track::FS_FILLING;
1870 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001871 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 mActiveTracks.add(track);
1873 if (track->mainBuffer() != mMixBuffer) {
1874 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1875 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001876 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001877 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 }
1879 }
1880
1881 status = NO_ERROR;
1882 }
1883
Steve Block3856b092011-10-20 11:56:00 +01001884 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 mWaitWorkCV.broadcast();
1886
1887 return status;
1888}
1889
1890// destroyTrack_l() must be called with ThreadBase::mLock held
1891void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1892{
1893 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001894 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001896 removeTrack_l(track);
1897 }
1898}
1899
1900void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1901{
Eric Laurent29864602012-05-08 18:57:51 -07001902 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001903 mTracks.remove(track);
1904 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001905 // redundant as track is about to be destroyed, for dumpsys only
1906 track->mName = -1;
1907 if (track->isFastTrack()) {
1908 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001909 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001910 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1911 mFastTrackAvailMask |= 1 << index;
1912 // redundant as track is about to be destroyed, for dumpsys only
1913 track->mFastIndex = -1;
1914 }
Eric Laurentb469b942011-05-09 12:09:06 -07001915 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1916 if (chain != 0) {
1917 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 }
1919}
1920
1921String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1922{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001923 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001924 char *s;
1925
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001926 Mutex::Autolock _l(mLock);
1927 if (initCheck() != NO_ERROR) {
1928 return out_s8;
1929 }
1930
Dima Zavin799a70e2011-04-18 16:57:27 -07001931 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001932 out_s8 = String8(s);
1933 free(s);
1934 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935}
1936
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001937// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1939 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001940 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941
Steve Block3856b092011-10-20 11:56:00 +01001942 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943
1944 switch (event) {
1945 case AudioSystem::OUTPUT_OPENED:
1946 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001947 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 desc.samplingRate = mSampleRate;
1949 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001950 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 desc.latency = latency();
1952 param2 = &desc;
1953 break;
1954
1955 case AudioSystem::STREAM_CONFIG_CHANGED:
1956 param2 = &param;
1957 case AudioSystem::OUTPUT_CLOSED:
1958 default:
1959 break;
1960 }
1961 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1962}
1963
1964void AudioFlinger::PlaybackThread::readOutputParameters()
1965{
Dima Zavin799a70e2011-04-18 16:57:27 -07001966 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001967 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1968 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001969 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001970 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001971 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001972 if (mFrameCount & 15) {
1973 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1974 mFrameCount);
1975 }
1976
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001977 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001978 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001979 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001980 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001981 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1982 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1983 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1984 maxNormalFrameCount = maxNormalFrameCount & ~15;
1985 if (maxNormalFrameCount < minNormalFrameCount) {
1986 maxNormalFrameCount = minNormalFrameCount;
1987 }
1988 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1989 if (multiplier <= 1.0) {
1990 multiplier = 1.0;
1991 } else if (multiplier <= 2.0) {
1992 if (2 * mFrameCount <= maxNormalFrameCount) {
1993 multiplier = 2.0;
1994 } else {
1995 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1996 }
1997 } else {
1998 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
1999 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2000 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2001 // FIXME this rounding up should not be done if no HAL SRC
2002 uint32_t truncMult = (uint32_t) multiplier;
2003 if ((truncMult & 1)) {
2004 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2005 ++truncMult;
2006 }
2007 }
2008 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002009 }
Glenn Kasten58912562012-04-03 10:45:00 -07002010 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002011 mNormalFrameCount = multiplier * mFrameCount;
2012 // round up to nearest 16 frames to satisfy AudioMixer
2013 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002014 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015
2016 // FIXME - Current mixer implementation only supports stereo output: Always
2017 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08002018 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07002019 mMixBuffer = new int16_t[mNormalFrameCount * 2];
2020 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021
Eric Laurentde070132010-07-13 04:45:46 -07002022 // force reconfiguration of effect chains and engines to take new buffer size and audio
2023 // parameters into account
2024 // Note that mLock is not held when readOutputParameters() is called from the constructor
2025 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2026 // matter.
2027 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2028 Vector< sp<EffectChain> > effectChains = mEffectChains;
2029 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002030 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002031 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032}
2033
Eric Laurente737cda2012-05-22 18:55:44 -07002034
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2036{
Glenn Kastena0d68332012-01-27 16:47:15 -08002037 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038 return BAD_VALUE;
2039 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002040 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002041 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 return INVALID_OPERATION;
2043 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002044 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045
Dima Zavin799a70e2011-04-18 16:57:27 -07002046 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047}
2048
Eric Laurent39e94f82010-07-28 01:32:47 -07002049uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050{
2051 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002052 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002054 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 }
2056
2057 for (size_t i = 0; i < mTracks.size(); ++i) {
2058 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002059 if (sessionId == track->sessionId() &&
2060 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002061 result |= TRACK_SESSION;
2062 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 }
2064 }
2065
Eric Laurent39e94f82010-07-28 01:32:47 -07002066 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067}
2068
Eric Laurentde070132010-07-13 04:45:46 -07002069uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2070{
Dima Zavinfce7a472011-04-19 22:30:36 -07002071 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002072 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002073 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2074 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002075 }
2076 for (size_t i = 0; i < mTracks.size(); i++) {
2077 sp<Track> track = mTracks[i];
2078 if (sessionId == track->sessionId() &&
2079 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002080 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002081 }
2082 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002083 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002084}
2085
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086
Glenn Kastenaed850d2012-01-26 09:46:34 -08002087AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002088{
2089 Mutex::Autolock _l(mLock);
2090 return mOutput;
2091}
2092
2093AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2094{
2095 Mutex::Autolock _l(mLock);
2096 AudioStreamOut *output = mOutput;
2097 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002098 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2099 // must push a NULL and wait for ack
2100 mOutputSink.clear();
2101 mPipeSink.clear();
2102 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002103 return output;
2104}
2105
2106// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002107audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002108{
2109 if (mOutput == NULL) {
2110 return NULL;
2111 }
2112 return &mOutput->stream->common;
2113}
2114
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002115uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002116{
2117 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2118 // decoding and transfer time. So sleeping for half of the latency would likely cause
2119 // underruns
2120 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002121 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002122 } else {
2123 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2124 }
2125}
2126
Eric Laurenta011e352012-03-29 15:51:43 -07002127status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2128{
2129 if (!isValidSyncEvent(event)) {
2130 return BAD_VALUE;
2131 }
2132
2133 Mutex::Autolock _l(mLock);
2134
2135 for (size_t i = 0; i < mTracks.size(); ++i) {
2136 sp<Track> track = mTracks[i];
2137 if (event->triggerSession() == track->sessionId()) {
2138 track->setSyncEvent(event);
2139 return NO_ERROR;
2140 }
2141 }
2142
2143 return NAME_NOT_FOUND;
2144}
2145
2146bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2147{
2148 switch (event->type()) {
2149 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2150 return true;
2151 default:
2152 break;
2153 }
2154 return false;
2155}
2156
Eric Laurent44a957f2012-05-15 15:26:05 -07002157void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2158{
2159 size_t count = tracksToRemove.size();
2160 if (CC_UNLIKELY(count)) {
2161 for (size_t i = 0 ; i < count ; i++) {
2162 const sp<Track>& track = tracksToRemove.itemAt(i);
2163 if ((track->sharedBuffer() != 0) &&
2164 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2165 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2166 }
2167 }
2168 }
2169
2170}
2171
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172// ----------------------------------------------------------------------------
2173
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002174AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002175 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002176 : PlaybackThread(audioFlinger, output, id, device, type),
2177 // mAudioMixer below
2178#ifdef SOAKER
2179 mSoaker(NULL),
2180#endif
2181 // mFastMixer below
2182 mFastMixerFutex(0)
2183 // mOutputSink below
2184 // mPipeSink below
2185 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186{
Glenn Kasten58912562012-04-03 10:45:00 -07002187 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2188 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2189 "mFrameCount=%d, mNormalFrameCount=%d",
2190 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2191 mNormalFrameCount);
2192 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2193
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 // FIXME - Current mixer implementation only supports stereo output
2195 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002196 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 }
Glenn Kasten58912562012-04-03 10:45:00 -07002198
2199 // create an NBAIO sink for the HAL output stream, and negotiate
2200 mOutputSink = new AudioStreamOutSink(output->stream);
2201 size_t numCounterOffers = 0;
2202 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2203 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2204 ALOG_ASSERT(index == 0);
2205
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002206 // initialize fast mixer depending on configuration
2207 bool initFastMixer;
2208 switch (kUseFastMixer) {
2209 case FastMixer_Never:
2210 initFastMixer = false;
2211 break;
2212 case FastMixer_Always:
2213 initFastMixer = true;
2214 break;
2215 case FastMixer_Static:
2216 case FastMixer_Dynamic:
2217 initFastMixer = mFrameCount < mNormalFrameCount;
2218 break;
2219 }
2220 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002221
2222 // create a MonoPipe to connect our submix to FastMixer
2223 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002224 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2225 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2226 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2227 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002228 const NBAIO_Format offers[1] = {format};
2229 size_t numCounterOffers = 0;
2230 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2231 ALOG_ASSERT(index == 0);
2232 mPipeSink = monoPipe;
2233
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002234#ifdef TEE_SINK_FRAMES
2235 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2236 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2237 numCounterOffers = 0;
2238 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2239 ALOG_ASSERT(index == 0);
2240 mTeeSink = teeSink;
2241 PipeReader *teeSource = new PipeReader(*teeSink);
2242 numCounterOffers = 0;
2243 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2244 ALOG_ASSERT(index == 0);
2245 mTeeSource = teeSource;
2246#endif
2247
Glenn Kasten58912562012-04-03 10:45:00 -07002248#ifdef SOAKER
2249 // create a soaker as workaround for governor issues
2250 mSoaker = new Soaker();
2251 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2252 mSoaker->run("Soaker", PRIORITY_LOWEST);
2253#endif
2254
2255 // create fast mixer and configure it initially with just one fast track for our submix
2256 mFastMixer = new FastMixer();
2257 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002258#ifdef STATE_QUEUE_DUMP
2259 sq->setObserverDump(&mStateQueueObserverDump);
2260 sq->setMutatorDump(&mStateQueueMutatorDump);
2261#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002262 FastMixerState *state = sq->begin();
2263 FastTrack *fastTrack = &state->mFastTracks[0];
2264 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2265 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2266 fastTrack->mVolumeProvider = NULL;
2267 fastTrack->mGeneration++;
2268 state->mFastTracksGen++;
2269 state->mTrackMask = 1;
2270 // fast mixer will use the HAL output sink
2271 state->mOutputSink = mOutputSink.get();
2272 state->mOutputSinkGen++;
2273 state->mFrameCount = mFrameCount;
2274 state->mCommand = FastMixerState::COLD_IDLE;
2275 // already done in constructor initialization list
2276 //mFastMixerFutex = 0;
2277 state->mColdFutexAddr = &mFastMixerFutex;
2278 state->mColdGen++;
2279 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002280 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002281 sq->end();
2282 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2283
2284 // start the fast mixer
2285 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2286#ifdef HAVE_REQUEST_PRIORITY
2287 pid_t tid = mFastMixer->getTid();
2288 int err = requestPriority(getpid_cached, tid, 2);
2289 if (err != 0) {
2290 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2291 2, getpid_cached, tid, err);
2292 }
2293#endif
2294
2295 } else {
2296 mFastMixer = NULL;
2297 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002298
2299 switch (kUseFastMixer) {
2300 case FastMixer_Never:
2301 case FastMixer_Dynamic:
2302 mNormalSink = mOutputSink;
2303 break;
2304 case FastMixer_Always:
2305 mNormalSink = mPipeSink;
2306 break;
2307 case FastMixer_Static:
2308 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2309 break;
2310 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311}
2312
2313AudioFlinger::MixerThread::~MixerThread()
2314{
Glenn Kasten58912562012-04-03 10:45:00 -07002315 if (mFastMixer != NULL) {
2316 FastMixerStateQueue *sq = mFastMixer->sq();
2317 FastMixerState *state = sq->begin();
2318 if (state->mCommand == FastMixerState::COLD_IDLE) {
2319 int32_t old = android_atomic_inc(&mFastMixerFutex);
2320 if (old == -1) {
2321 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2322 }
2323 }
2324 state->mCommand = FastMixerState::EXIT;
2325 sq->end();
2326 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2327 mFastMixer->join();
2328 // Though the fast mixer thread has exited, it's state queue is still valid.
2329 // We'll use that extract the final state which contains one remaining fast track
2330 // corresponding to our sub-mix.
2331 state = sq->begin();
2332 ALOG_ASSERT(state->mTrackMask == 1);
2333 FastTrack *fastTrack = &state->mFastTracks[0];
2334 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2335 delete fastTrack->mBufferProvider;
2336 sq->end(false /*didModify*/);
2337 delete mFastMixer;
2338#ifdef SOAKER
2339 if (mSoaker != NULL) {
2340 mSoaker->requestExitAndWait();
2341 }
2342 delete mSoaker;
2343#endif
2344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345 delete mAudioMixer;
2346}
2347
Glenn Kasten83efdd02012-02-24 07:21:32 -08002348class CpuStats {
2349public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002350 CpuStats();
2351 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002352#ifdef DEBUG_CPU_USAGE
2353private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002354 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2355 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2356
2357 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2358
2359 int mCpuNum; // thread's current CPU number
2360 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002361#endif
2362};
2363
Glenn Kasten190a46f2012-03-06 11:27:10 -08002364CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002365#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002366 : mCpuNum(-1), mCpukHz(-1)
2367#endif
2368{
2369}
2370
2371void CpuStats::sample(const String8 &title) {
2372#ifdef DEBUG_CPU_USAGE
2373 // get current thread's delta CPU time in wall clock ns
2374 double wcNs;
2375 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2376
2377 // record sample for wall clock statistics
2378 if (valid) {
2379 mWcStats.sample(wcNs);
2380 }
2381
2382 // get the current CPU number
2383 int cpuNum = sched_getcpu();
2384
2385 // get the current CPU frequency in kHz
2386 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2387
2388 // check if either CPU number or frequency changed
2389 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2390 mCpuNum = cpuNum;
2391 mCpukHz = cpukHz;
2392 // ignore sample for purposes of cycles
2393 valid = false;
2394 }
2395
2396 // if no change in CPU number or frequency, then record sample for cycle statistics
2397 if (valid && mCpukHz > 0) {
2398 double cycles = wcNs * cpukHz * 0.000001;
2399 mHzStats.sample(cycles);
2400 }
2401
2402 unsigned n = mWcStats.n();
2403 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002404 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002405 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002406 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2407 double perLoop = elapsed / (double) n;
2408 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002409 double perLoop1k = perLoop * 0.001;
2410 double mean = mWcStats.mean();
2411 double stddev = mWcStats.stddev();
2412 double minimum = mWcStats.minimum();
2413 double maximum = mWcStats.maximum();
2414 double meanCycles = mHzStats.mean();
2415 double stddevCycles = mHzStats.stddev();
2416 double minCycles = mHzStats.minimum();
2417 double maxCycles = mHzStats.maximum();
2418 mCpuUsage.resetElapsed();
2419 mWcStats.reset();
2420 mHzStats.reset();
2421 ALOGD("CPU usage for %s over past %.1f secs\n"
2422 " (%u mixer loops at %.1f mean ms per loop):\n"
2423 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2424 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2425 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2426 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002427 elapsed * .000000001, n, perLoop * .000001,
2428 mean * .001,
2429 stddev * .001,
2430 minimum * .001,
2431 maximum * .001,
2432 mean / perLoop100,
2433 stddev / perLoop100,
2434 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002435 maximum / perLoop100,
2436 meanCycles / perLoop1k,
2437 stddevCycles / perLoop1k,
2438 minCycles / perLoop1k,
2439 maxCycles / perLoop1k);
2440
Glenn Kasten83efdd02012-02-24 07:21:32 -08002441 }
2442 }
2443#endif
2444};
2445
Glenn Kasten37d825e2012-02-24 07:21:48 -08002446void AudioFlinger::PlaybackThread::checkSilentMode_l()
2447{
2448 if (!mMasterMute) {
2449 char value[PROPERTY_VALUE_MAX];
2450 if (property_get("ro.audio.silent", value, "0") > 0) {
2451 char *endptr;
2452 unsigned long ul = strtoul(value, &endptr, 0);
2453 if (*endptr == '\0' && ul != 0) {
2454 ALOGD("Silence is golden");
2455 // The setprop command will not allow a property to be changed after
2456 // the first time it is set, so we don't have to worry about un-muting.
2457 setMasterMute_l(true);
2458 }
2459 }
2460 }
2461}
2462
Glenn Kasten000f0e32012-03-01 17:10:56 -08002463bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464{
2465 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002466
Glenn Kasten000f0e32012-03-01 17:10:56 -08002467 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002468
2469 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002471if (mType == MIXER) {
2472 longStandbyExit = false;
2473}
Glenn Kasten688a6402012-02-29 07:57:06 -08002474
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475 // DUPLICATING
2476 // FIXME could this be made local to while loop?
2477 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002478
Glenn Kasten66fcab92012-02-24 14:59:21 -08002479 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002480 sleepTime = idleSleepTime;
2481
2482if (mType == MIXER) {
2483 sleepTimeShift = 0;
2484}
2485
Glenn Kasten83efdd02012-02-24 07:21:32 -08002486 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002487 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488
Eric Laurentfeb0db62011-07-22 09:04:31 -07002489 acquireWakeLock();
2490
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491 while (!exitPending())
2492 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002493 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002494
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002495 Vector< sp<EffectChain> > effectChains;
2496
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497 processConfigEvents();
2498
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 { // scope for mLock
2500
2501 Mutex::Autolock _l(mLock);
2502
2503 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002504 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 }
2506
Glenn Kastenfa26a852012-03-06 11:28:04 -08002507 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002510 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002511 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002513
2514 threadLoop_standby();
2515
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 mStandby = true;
2517 mBytesWritten = 0;
2518 }
2519
Glenn Kasten3e074702012-02-28 18:40:35 -08002520 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 // we're about to wait, flush the binder command buffer
2522 IPCThreadState::self()->flushCommands();
2523
Glenn Kastenfa26a852012-03-06 11:28:04 -08002524 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 if (exitPending()) break;
2527
Eric Laurentfeb0db62011-07-22 09:04:31 -07002528 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002530 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002532 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002533 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534
Eric Laurentda747442012-04-25 18:53:13 -07002535 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002536 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002537
Glenn Kasten37d825e2012-02-24 07:21:48 -08002538 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539
Glenn Kasten000f0e32012-03-01 17:10:56 -08002540 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002542 if (mType == MIXER) {
2543 sleepTimeShift = 0;
2544 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002545
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 continue;
2547 }
2548 }
2549
Glenn Kasten81028042012-04-30 18:15:12 -07002550 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002551 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552
2553 // prevent any changes in effect chain list and in each effect chain
2554 // during mixing and effect process as the audio buffers could be deleted
2555 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002556 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002557 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558
Glenn Kastenfec279f2012-03-08 07:47:15 -08002559 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002560 threadLoop_mix();
2561 } else {
2562 threadLoop_sleepTime();
2563 }
2564
2565 if (mSuspended > 0) {
2566 sleepTime = suspendSleepTimeUs();
2567 }
2568
2569 // only process effects if we're going to write
2570 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002571 for (size_t i = 0; i < effectChains.size(); i ++) {
2572 effectChains[i]->process_l();
2573 }
2574 }
2575
2576 // enable changes in effect chain
2577 unlockEffectChains(effectChains);
2578
2579 // sleepTime == 0 means we must write to audio hardware
2580 if (sleepTime == 0) {
2581
2582 threadLoop_write();
2583
2584if (mType == MIXER) {
2585 // write blocked detection
2586 nsecs_t now = systemTime();
2587 nsecs_t delta = now - mLastWriteTime;
2588 if (!mStandby && delta > maxPeriod) {
2589 mNumDelayedWrites++;
2590 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002591#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002592 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002593#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002594 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2595 ns2ms(delta), mNumDelayedWrites, this);
2596 lastWarning = now;
2597 }
2598 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2599 // a different threshold. Or completely removed for what it is worth anyway...
2600 if (mStandby) {
2601 longStandbyExit = true;
2602 }
2603 }
2604}
2605
2606 mStandby = false;
2607 } else {
2608 usleep(sleepTime);
2609 }
2610
Glenn Kasten58912562012-04-03 10:45:00 -07002611 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002612 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002613 // same lock. This will also mutate and push a new fast mixer state.
2614 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002615 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002616
Glenn Kastenfa26a852012-03-06 11:28:04 -08002617 // FIXME I don't understand the need for this here;
2618 // it was in the original code but maybe the
2619 // assignment in saveOutputTracks() makes this unnecessary?
2620 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002621
2622 // Effect chains will be actually deleted here if they were removed from
2623 // mEffectChains list during mixing or effects processing
2624 effectChains.clear();
2625
2626 // FIXME Note that the above .clear() is no longer necessary since effectChains
2627 // is now local to this block, but will keep it for now (at least until merge done).
2628 }
2629
2630if (mType == MIXER || mType == DIRECT) {
2631 // put output stream into standby mode
2632 if (!mStandby) {
2633 mOutput->stream->common.standby(&mOutput->stream->common);
2634 }
2635}
2636if (mType == DUPLICATING) {
2637 // for DuplicatingThread, standby mode is handled by the outputTracks
2638}
2639
2640 releaseWakeLock();
2641
2642 ALOGV("Thread %p type %d exiting", this, mType);
2643 return false;
2644}
2645
Glenn Kasten58912562012-04-03 10:45:00 -07002646void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2647{
Glenn Kasten58912562012-04-03 10:45:00 -07002648 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2649}
2650
2651void AudioFlinger::MixerThread::threadLoop_write()
2652{
2653 // FIXME we should only do one push per cycle; confirm this is true
2654 // Start the fast mixer if it's not already running
2655 if (mFastMixer != NULL) {
2656 FastMixerStateQueue *sq = mFastMixer->sq();
2657 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002658 if (state->mCommand != FastMixerState::MIX_WRITE &&
2659 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002660 if (state->mCommand == FastMixerState::COLD_IDLE) {
2661 int32_t old = android_atomic_inc(&mFastMixerFutex);
2662 if (old == -1) {
2663 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2664 }
2665 }
2666 state->mCommand = FastMixerState::MIX_WRITE;
2667 sq->end();
2668 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002669 if (kUseFastMixer == FastMixer_Dynamic) {
2670 mNormalSink = mPipeSink;
2671 }
Glenn Kasten58912562012-04-03 10:45:00 -07002672 } else {
2673 sq->end(false /*didModify*/);
2674 }
2675 }
2676 PlaybackThread::threadLoop_write();
2677}
2678
Glenn Kasten000f0e32012-03-01 17:10:56 -08002679// shared by MIXER and DIRECT, overridden by DUPLICATING
2680void AudioFlinger::PlaybackThread::threadLoop_write()
2681{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002682 // FIXME rewrite to reduce number of system calls
2683 mLastWriteTime = systemTime();
2684 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002685
Glenn Kasten58912562012-04-03 10:45:00 -07002686#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002687 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002688#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002689 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002690#endif
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002691 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002692#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002693 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002694#endif
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002695 if (framesWritten > 0) {
2696 size_t bytesWritten = framesWritten << mBitShift;
2697 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002698 }
2699
Glenn Kasten952eeb22012-03-06 11:30:57 -08002700 mNumWrites++;
2701 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002702}
2703
Glenn Kasten58912562012-04-03 10:45:00 -07002704void AudioFlinger::MixerThread::threadLoop_standby()
2705{
2706 // Idle the fast mixer if it's currently running
2707 if (mFastMixer != NULL) {
2708 FastMixerStateQueue *sq = mFastMixer->sq();
2709 FastMixerState *state = sq->begin();
2710 if (!(state->mCommand & FastMixerState::IDLE)) {
2711 state->mCommand = FastMixerState::COLD_IDLE;
2712 state->mColdFutexAddr = &mFastMixerFutex;
2713 state->mColdGen++;
2714 mFastMixerFutex = 0;
2715 sq->end();
2716 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2717 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002718 if (kUseFastMixer == FastMixer_Dynamic) {
2719 mNormalSink = mOutputSink;
2720 }
Glenn Kasten58912562012-04-03 10:45:00 -07002721 } else {
2722 sq->end(false /*didModify*/);
2723 }
2724 }
2725 PlaybackThread::threadLoop_standby();
2726}
2727
Glenn Kasten000f0e32012-03-01 17:10:56 -08002728// shared by MIXER and DIRECT, overridden by DUPLICATING
2729void AudioFlinger::PlaybackThread::threadLoop_standby()
2730{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002731 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2732 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002733}
2734
2735void AudioFlinger::MixerThread::threadLoop_mix()
2736{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002737 // obtain the presentation timestamp of the next output buffer
2738 int64_t pts;
2739 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002740
Glenn Kasten952eeb22012-03-06 11:30:57 -08002741 if (NULL != mOutput->stream->get_next_write_timestamp) {
2742 status = mOutput->stream->get_next_write_timestamp(
2743 mOutput->stream, &pts);
2744 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002745
Glenn Kasten952eeb22012-03-06 11:30:57 -08002746 if (status != NO_ERROR) {
2747 pts = AudioBufferProvider::kInvalidPTS;
2748 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002749
Glenn Kasten952eeb22012-03-06 11:30:57 -08002750 // mix buffers...
2751 mAudioMixer->process(pts);
2752 // increase sleep time progressively when application underrun condition clears.
2753 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2754 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2755 // such that we would underrun the audio HAL.
2756 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2757 sleepTimeShift--;
2758 }
2759 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002760 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002761 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002762}
2763
2764void AudioFlinger::MixerThread::threadLoop_sleepTime()
2765{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002766 // If no tracks are ready, sleep once for the duration of an output
2767 // buffer size, then write 0s to the output
2768 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002769 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002770 sleepTime = activeSleepTime >> sleepTimeShift;
2771 if (sleepTime < kMinThreadSleepTimeUs) {
2772 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002774 // reduce sleep time in case of consecutive application underruns to avoid
2775 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2776 // duration we would end up writing less data than needed by the audio HAL if
2777 // the condition persists.
2778 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2779 sleepTimeShift++;
2780 }
2781 } else {
2782 sleepTime = idleSleepTime;
2783 }
2784 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002785 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002786 memset (mMixBuffer, 0, mixBufferSize);
2787 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002788 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002789 }
2790 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791}
2792
2793// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002794AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002795 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796{
2797
Glenn Kasten29c23c32012-01-26 13:37:52 -08002798 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002800 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 size_t mixedTracks = 0;
2802 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002803 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002804 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002805 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806
2807 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002808 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809
Eric Laurent571d49c2010-08-11 05:20:11 -07002810 if (masterMute) {
2811 masterVolume = 0;
2812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002814 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002816 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002817 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 masterVolume = (float)((v + (1 << 23)) >> 24);
2819 chain.clear();
2820 }
2821
Glenn Kasten288ed212012-04-25 17:52:27 -07002822 // prepare a new state to push
2823 FastMixerStateQueue *sq = NULL;
2824 FastMixerState *state = NULL;
2825 bool didModify = false;
2826 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2827 if (mFastMixer != NULL) {
2828 sq = mFastMixer->sq();
2829 state = sq->begin();
2830 }
2831
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002833 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 if (t == 0) continue;
2835
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002836 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002838
Glenn Kasten288ed212012-04-25 17:52:27 -07002839 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002840 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002841
2842 // It's theoretically possible (though unlikely) for a fast track to be created
2843 // and then removed within the same normal mix cycle. This is not a problem, as
2844 // the track never becomes active so it's fast mixer slot is never touched.
2845 // The converse, of removing an (active) track and then creating a new track
2846 // at the identical fast mixer slot within the same normal mix cycle,
2847 // is impossible because the slot isn't marked available until the end of each cycle.
2848 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002849 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2850 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002851 FastTrack *fastTrack = &state->mFastTracks[j];
2852
2853 // Determine whether the track is currently in underrun condition,
2854 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002855 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2856 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002857 uint32_t recentFull = (underruns.mBitFields.mFull -
2858 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2859 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2860 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2861 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2862 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2863 uint32_t recentUnderruns = recentPartial + recentEmpty;
2864 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002865 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002866 // or stopped which can occur when flush() is called while active
2867 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002868 track->mUnderrunCount += recentUnderruns;
2869 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002870
Glenn Kastend08f48c2012-05-01 18:14:02 -07002871 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002872 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002873 bool isActive = true;
2874 switch (track->mState) {
2875 case TrackBase::STOPPING_1:
2876 // track stays active in STOPPING_1 state until first underrun
2877 if (recentUnderruns > 0) {
2878 track->mState = TrackBase::STOPPING_2;
2879 }
2880 break;
2881 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002882 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002883 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002884 break;
2885 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002886 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002887 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002888 break;
2889 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002890 if (recentFull > 0 || recentPartial > 0) {
2891 // track has provided at least some frames recently: reset retry count
2892 track->mRetryCount = kMaxTrackRetries;
2893 }
2894 if (recentUnderruns == 0) {
2895 // no recent underruns: stay active
2896 break;
2897 }
2898 // there has recently been an underrun of some kind
2899 if (track->sharedBuffer() == 0) {
2900 // were any of the recent underruns "empty" (no frames available)?
2901 if (recentEmpty == 0) {
2902 // no, then ignore the partial underruns as they are allowed indefinitely
2903 break;
2904 }
2905 // there has recently been an "empty" underrun: decrement the retry counter
2906 if (--(track->mRetryCount) > 0) {
2907 break;
2908 }
2909 // indicate to client process that the track was disabled because of underrun;
2910 // it will then automatically call start() when data is available
2911 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2912 // remove from active list, but state remains ACTIVE [confusing but true]
2913 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002914 break;
2915 }
2916 // fall through
2917 case TrackBase::STOPPING_2:
2918 case TrackBase::PAUSED:
2919 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002920 case TrackBase::STOPPED:
2921 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002922 // Check for presentation complete if track is inactive
2923 // We have consumed all the buffers of this track.
2924 // This would be incomplete if we auto-paused on underrun
2925 {
2926 size_t audioHALFrames =
2927 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2928 size_t framesWritten =
2929 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2930 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2931 // track stays in active list until presentation is complete
2932 break;
2933 }
2934 }
2935 if (track->isStopping_2()) {
2936 track->mState = TrackBase::STOPPED;
2937 }
2938 if (track->isStopped()) {
2939 // Can't reset directly, as fast mixer is still polling this track
2940 // track->reset();
2941 // So instead mark this track as needing to be reset after push with ack
2942 resetMask |= 1 << i;
2943 }
2944 isActive = false;
2945 break;
2946 case TrackBase::IDLE:
2947 default:
2948 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002949 }
2950
2951 if (isActive) {
2952 // was it previously inactive?
2953 if (!(state->mTrackMask & (1 << j))) {
2954 ExtendedAudioBufferProvider *eabp = track;
2955 VolumeProvider *vp = track;
2956 fastTrack->mBufferProvider = eabp;
2957 fastTrack->mVolumeProvider = vp;
2958 fastTrack->mSampleRate = track->mSampleRate;
2959 fastTrack->mChannelMask = track->mChannelMask;
2960 fastTrack->mGeneration++;
2961 state->mTrackMask |= 1 << j;
2962 didModify = true;
2963 // no acknowledgement required for newly active tracks
2964 }
2965 // cache the combined master volume and stream type volume for fast mixer; this
2966 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2967 track->mCachedVolume = track->isMuted() ?
2968 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2969 ++fastTracks;
2970 } else {
2971 // was it previously active?
2972 if (state->mTrackMask & (1 << j)) {
2973 fastTrack->mBufferProvider = NULL;
2974 fastTrack->mGeneration++;
2975 state->mTrackMask &= ~(1 << j);
2976 didModify = true;
2977 // If any fast tracks were removed, we must wait for acknowledgement
2978 // because we're about to decrement the last sp<> on those tracks.
2979 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002980 } else {
2981 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002982 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002983 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002984 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07002985 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002986 }
2987 continue;
2988 }
2989
2990 { // local variable scope to avoid goto warning
2991
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992 audio_track_cblk_t* cblk = track->cblk();
2993
2994 // The first time a track is added we wait
2995 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002996 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002997 // make sure that we have enough frames to mix one full buffer.
2998 // enforce this condition only once to enable draining the buffer in case the client
2999 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003000 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003001 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003002 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003003 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003004 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003005 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003006 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003007 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003008 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003009 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003010 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003011 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003012 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3013 // the minimum track buffer size is normally twice the number of frames necessary
3014 // to fill one buffer and the resampler should not leave more than one buffer worth
3015 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003016 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003017 }
3018 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003019 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020 !track->isPaused() && !track->isTerminated())
3021 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003022 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023
3024 mixedTracks++;
3025
3026 // track->mainBuffer() != mMixBuffer means there is an effect chain
3027 // connected to the track
3028 chain.clear();
3029 if (track->mainBuffer() != mMixBuffer) {
3030 chain = getEffectChain_l(track->sessionId());
3031 // Delegate volume control to effect in track effect chain if needed
3032 if (chain != 0) {
3033 tracksWithEffect++;
3034 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003035 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003036 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 }
3038 }
3039
3040
3041 int param = AudioMixer::VOLUME;
3042 if (track->mFillingUpStatus == Track::FS_FILLED) {
3043 // no ramp for the first volume setting
3044 track->mFillingUpStatus = Track::FS_ACTIVE;
3045 if (track->mState == TrackBase::RESUMING) {
3046 track->mState = TrackBase::ACTIVE;
3047 param = AudioMixer::RAMP_VOLUME;
3048 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003049 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 } else if (cblk->server != 0) {
3051 // If the track is stopped before the first frame was mixed,
3052 // do not apply ramp
3053 param = AudioMixer::RAMP_VOLUME;
3054 }
3055
3056 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003057 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003058 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003059 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003060 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 if (track->isPausing()) {
3062 track->setPaused();
3063 }
3064 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003065
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003067 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003068 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003069 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003070 vl = vlr & 0xFFFF;
3071 vr = vlr >> 16;
3072 // track volumes come from shared memory, so can't be trusted and must be clamped
3073 if (vl > MAX_GAIN_INT) {
3074 ALOGV("Track left volume out of range: %04X", vl);
3075 vl = MAX_GAIN_INT;
3076 }
3077 if (vr > MAX_GAIN_INT) {
3078 ALOGV("Track right volume out of range: %04X", vr);
3079 vr = MAX_GAIN_INT;
3080 }
3081 // now apply the master volume and stream type volume
3082 vl = (uint32_t)(v * vl) << 12;
3083 vr = (uint32_t)(v * vr) << 12;
3084 // assuming master volume and stream type volume each go up to 1.0,
3085 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086
Glenn Kasten05632a52012-01-03 14:22:33 -08003087 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3088 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003089 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003090 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003091 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003092 }
3093 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003095 // Delegate volume control to effect in track effect chain if needed
3096 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3097 // Do not ramp volume if volume is controlled by effect
3098 param = AudioMixer::VOLUME;
3099 track->mHasVolumeController = true;
3100 } else {
3101 // force no volume ramp when volume controller was just disabled or removed
3102 // from effect chain to avoid volume spike
3103 if (track->mHasVolumeController) {
3104 param = AudioMixer::VOLUME;
3105 }
3106 track->mHasVolumeController = false;
3107 }
3108
3109 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003110 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003111 vl = (vl + (1 << 11)) >> 12;
3112 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3113 vr = (vr + (1 << 11)) >> 12;
3114 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003115
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003116 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 -07003117
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003119 mAudioMixer->setBufferProvider(name, track);
3120 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003122 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3123 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3124 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
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::TRACK,
3128 AudioMixer::FORMAT, (void *)track->format());
3129 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003130 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003131 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003132 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003134 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 AudioMixer::RESAMPLE,
3136 AudioMixer::SAMPLE_RATE,
3137 (void *)(cblk->sampleRate));
3138 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003139 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 AudioMixer::TRACK,
3141 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3142 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003143 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 AudioMixer::TRACK,
3145 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3146
3147 // reset retry count
3148 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003149
Eric Laurent27741442012-01-17 19:20:12 -08003150 // If one track is ready, set the mixer ready if:
3151 // - the mixer was not ready during previous round OR
3152 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003153 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003154 mixerStatus != MIXER_TRACKS_ENABLED) {
3155 mixerStatus = MIXER_TRACKS_READY;
3156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003158 // clear effect chain input buffer if an active track underruns to avoid sending
3159 // previous audio buffer again to effects
3160 chain = getEffectChain_l(track->sessionId());
3161 if (chain != 0) {
3162 chain->clearInputBuffer();
3163 }
3164
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003165 //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 -07003166 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3167 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 // We have consumed all the buffers of this track.
3169 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003170 // TODO: use actual buffer filling status instead of latency when available from
3171 // audio HAL
3172 size_t audioHALFrames =
3173 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3174 size_t framesWritten =
3175 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3176 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003177 if (track->isStopped()) {
3178 track->reset();
3179 }
Eric Laurenta011e352012-03-29 15:51:43 -07003180 tracksToRemove->add(track);
3181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003183 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 // No buffers for this track. Give it a few chances to
3185 // fill a buffer, then remove it from active list.
3186 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003187 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003189 // indicate to client process that the track was disabled because of underrun;
3190 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003191 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003192 // If one track is not ready, mark the mixer also not ready if:
3193 // - the mixer was ready during previous round OR
3194 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003195 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003196 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 mixerStatus = MIXER_TRACKS_ENABLED;
3198 }
3199 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003200 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 }
Glenn Kasten58912562012-04-03 10:45:00 -07003202
3203 } // local variable scope to avoid goto warning
3204track_is_ready: ;
3205
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 }
3207
Glenn Kasten288ed212012-04-25 17:52:27 -07003208 // Push the new FastMixer state if necessary
3209 if (didModify) {
3210 state->mFastTracksGen++;
3211 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3212 if (kUseFastMixer == FastMixer_Dynamic &&
3213 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3214 state->mCommand = FastMixerState::COLD_IDLE;
3215 state->mColdFutexAddr = &mFastMixerFutex;
3216 state->mColdGen++;
3217 mFastMixerFutex = 0;
3218 if (kUseFastMixer == FastMixer_Dynamic) {
3219 mNormalSink = mOutputSink;
3220 }
3221 // If we go into cold idle, need to wait for acknowledgement
3222 // so that fast mixer stops doing I/O.
3223 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3224 }
3225 sq->end();
3226 }
3227 if (sq != NULL) {
3228 sq->end(didModify);
3229 sq->push(block);
3230 }
3231
3232 // Now perform the deferred reset on fast tracks that have stopped
3233 while (resetMask != 0) {
3234 size_t i = __builtin_ctz(resetMask);
3235 ALOG_ASSERT(i < count);
3236 resetMask &= ~(1 << i);
3237 sp<Track> t = mActiveTracks[i].promote();
3238 if (t == 0) continue;
3239 Track* track = t.get();
3240 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3241 track->reset();
3242 }
Glenn Kasten58912562012-04-03 10:45:00 -07003243
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 // remove all the tracks that need to be...
3245 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003246 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 for (size_t i=0 ; i<count ; i++) {
3248 const sp<Track>& track = tracksToRemove->itemAt(i);
3249 mActiveTracks.remove(track);
3250 if (track->mainBuffer() != mMixBuffer) {
3251 chain = getEffectChain_l(track->sessionId());
3252 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003253 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003254 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 }
3256 }
3257 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003258 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 }
3260 }
3261 }
3262
3263 // mix buffer must be cleared if all tracks are connected to an
3264 // effect chain as in this case the mixer will not write to
3265 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003266 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3267 // FIXME as a performance optimization, should remember previous zero status
3268 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 }
3270
Glenn Kasten58912562012-04-03 10:45:00 -07003271 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003272 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003273 if (fastTracks > 0) {
3274 mixerStatus = MIXER_TRACKS_READY;
3275 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 return mixerStatus;
3277}
3278
Glenn Kasten66fcab92012-02-24 14:59:21 -08003279/*
3280The derived values that are cached:
3281 - mixBufferSize from frame count * frame size
3282 - activeSleepTime from activeSleepTimeUs()
3283 - idleSleepTime from idleSleepTimeUs()
3284 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3285 - maxPeriod from frame count and sample rate (MIXER only)
3286
3287The parameters that affect these derived values are:
3288 - frame count
3289 - frame size
3290 - sample rate
3291 - device type: A2DP or not
3292 - device latency
3293 - format: PCM or not
3294 - active sleep time
3295 - idle sleep time
3296*/
3297
3298void AudioFlinger::PlaybackThread::cacheParameters_l()
3299{
Glenn Kasten58912562012-04-03 10:45:00 -07003300 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003301 activeSleepTime = activeSleepTimeUs();
3302 idleSleepTime = idleSleepTimeUs();
3303}
3304
Glenn Kastenfff6d712012-01-12 16:38:12 -08003305void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306{
Steve Block3856b092011-10-20 11:56:00 +01003307 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003308 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003310
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 size_t size = mTracks.size();
3312 for (size_t i = 0; i < size; i++) {
3313 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003314 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003315 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 }
3318 }
3319}
3320
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003322int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003324 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325}
3326
3327// deleteTrackName_l() must be called with ThreadBase::mLock held
3328void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3329{
Steve Block3856b092011-10-20 11:56:00 +01003330 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 mAudioMixer->deleteTrackName(name);
3332}
3333
3334// checkForNewParameters_l() must be called with ThreadBase::mLock held
3335bool AudioFlinger::MixerThread::checkForNewParameters_l()
3336{
Glenn Kasten58912562012-04-03 10:45:00 -07003337 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3338 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 bool reconfig = false;
3340
3341 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003342
3343 if (mFastMixer != NULL) {
3344 FastMixerStateQueue *sq = mFastMixer->sq();
3345 FastMixerState *state = sq->begin();
3346 if (!(state->mCommand & FastMixerState::IDLE)) {
3347 previousCommand = state->mCommand;
3348 state->mCommand = FastMixerState::HOT_IDLE;
3349 sq->end();
3350 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3351 } else {
3352 sq->end(false /*didModify*/);
3353 }
3354 }
3355
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 status_t status = NO_ERROR;
3357 String8 keyValuePair = mNewParameters[0];
3358 AudioParameter param = AudioParameter(keyValuePair);
3359 int value;
3360
3361 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3362 reconfig = true;
3363 }
3364 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003365 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 status = BAD_VALUE;
3367 } else {
3368 reconfig = true;
3369 }
3370 }
3371 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003372 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 status = BAD_VALUE;
3374 } else {
3375 reconfig = true;
3376 }
3377 }
3378 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3379 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003380 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 // if frame count is changed after track creation
3382 if (!mTracks.isEmpty()) {
3383 status = INVALID_OPERATION;
3384 } else {
3385 reconfig = true;
3386 }
3387 }
3388 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003389#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003390 // when changing the audio output device, call addBatteryData to notify
3391 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003392 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003393 uint32_t params = 0;
3394 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003395 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003396 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3397 }
3398
3399 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003400 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003401 // check if any other device (except speaker) is on
3402 if (value & deviceWithoutSpeaker ) {
3403 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3404 }
3405
3406 if (params != 0) {
3407 addBatteryData(params);
3408 }
3409 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003410#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003411
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412 // forward device change to effects that have requested to be
3413 // aware of attached audio device.
3414 mDevice = (uint32_t)value;
3415 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003416 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 }
3418 }
3419
3420 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003421 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003422 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003424 mOutput->stream->common.standby(&mOutput->stream->common);
3425 mStandby = true;
3426 mBytesWritten = 0;
3427 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003428 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 }
3430 if (status == NO_ERROR && reconfig) {
3431 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003432 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3433 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003435 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003437 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 if (name < 0) break;
3439 mTracks[i]->mName = name;
3440 // limit track sample rate to 2 x new output sample rate
3441 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3442 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3443 }
3444 }
3445 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3446 }
3447 }
3448
3449 mNewParameters.removeAt(0);
3450
3451 mParamStatus = status;
3452 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003453 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3454 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003455 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 }
Glenn Kasten58912562012-04-03 10:45:00 -07003457
3458 if (!(previousCommand & FastMixerState::IDLE)) {
3459 ALOG_ASSERT(mFastMixer != NULL);
3460 FastMixerStateQueue *sq = mFastMixer->sq();
3461 FastMixerState *state = sq->begin();
3462 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3463 state->mCommand = previousCommand;
3464 sq->end();
3465 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3466 }
3467
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 return reconfig;
3469}
3470
3471status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3472{
3473 const size_t SIZE = 256;
3474 char buffer[SIZE];
3475 String8 result;
3476
3477 PlaybackThread::dumpInternals(fd, args);
3478
3479 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3480 result.append(buffer);
3481 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003482
3483 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3484 FastMixerDumpState copy = mFastMixerDumpState;
3485 copy.dump(fd);
3486
Glenn Kasten39993082012-05-31 13:40:27 -07003487#ifdef STATE_QUEUE_DUMP
3488 // Similar for state queue
3489 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3490 observerCopy.dump(fd);
3491 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3492 mutatorCopy.dump(fd);
3493#endif
3494
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003495 // Write the tee output to a .wav file
3496 NBAIO_Source *teeSource = mTeeSource.get();
3497 if (teeSource != NULL) {
3498 char teePath[64];
3499 struct timeval tv;
3500 gettimeofday(&tv, NULL);
3501 struct tm tm;
3502 localtime_r(&tv.tv_sec, &tm);
3503 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3504 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3505 if (teeFd >= 0) {
3506 char wavHeader[44];
3507 memcpy(wavHeader,
3508 "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",
3509 sizeof(wavHeader));
3510 NBAIO_Format format = teeSource->format();
3511 unsigned channelCount = Format_channelCount(format);
3512 ALOG_ASSERT(channelCount <= FCC_2);
3513 unsigned sampleRate = Format_sampleRate(format);
3514 wavHeader[22] = channelCount; // number of channels
3515 wavHeader[24] = sampleRate; // sample rate
3516 wavHeader[25] = sampleRate >> 8;
3517 wavHeader[32] = channelCount * 2; // block alignment
3518 write(teeFd, wavHeader, sizeof(wavHeader));
3519 size_t total = 0;
3520 bool firstRead = true;
3521 for (;;) {
3522#define TEE_SINK_READ 1024
3523 short buffer[TEE_SINK_READ * FCC_2];
3524 size_t count = TEE_SINK_READ;
3525 ssize_t actual = teeSource->read(buffer, count);
3526 bool wasFirstRead = firstRead;
3527 firstRead = false;
3528 if (actual <= 0) {
3529 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3530 continue;
3531 }
3532 break;
3533 }
3534 ALOG_ASSERT(actual <= count);
3535 write(teeFd, buffer, actual * channelCount * sizeof(short));
3536 total += actual;
3537 }
3538 lseek(teeFd, (off_t) 4, SEEK_SET);
3539 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3540 write(teeFd, &temp, sizeof(temp));
3541 lseek(teeFd, (off_t) 40, SEEK_SET);
3542 temp = total * channelCount * sizeof(short);
3543 write(teeFd, &temp, sizeof(temp));
3544 close(teeFd);
3545 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3546 } else {
3547 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3548 }
3549 }
3550
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 return NO_ERROR;
3552}
3553
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003554uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555{
Glenn Kasten58912562012-04-03 10:45:00 -07003556 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003557}
3558
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003559uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003560{
Glenn Kasten58912562012-04-03 10:45:00 -07003561 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003562}
3563
Glenn Kasten66fcab92012-02-24 14:59:21 -08003564void AudioFlinger::MixerThread::cacheParameters_l()
3565{
3566 PlaybackThread::cacheParameters_l();
3567
3568 // FIXME: Relaxed timing because of a certain device that can't meet latency
3569 // Should be reduced to 2x after the vendor fixes the driver issue
3570 // increase threshold again due to low power audio mode. The way this warning
3571 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003572 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003573}
3574
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003576AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3577 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003578 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003579 // mLeftVolFloat, mRightVolFloat
3580 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582}
3583
3584AudioFlinger::DirectOutputThread::~DirectOutputThread()
3585{
3586}
3587
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003588AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3589 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003590)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003592 sp<Track> trackToRemove;
3593
Glenn Kastenfec279f2012-03-08 07:47:15 -08003594 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595
Glenn Kasten952eeb22012-03-06 11:30:57 -08003596 // find out which tracks need to be processed
3597 if (mActiveTracks.size() != 0) {
3598 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003599 // The track died recently
3600 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601
Glenn Kasten952eeb22012-03-06 11:30:57 -08003602 Track* const track = t.get();
3603 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604
Glenn Kasten952eeb22012-03-06 11:30:57 -08003605 // The first time a track is added we wait
3606 // for all its buffers to be filled before processing it
3607 if (cblk->framesReady() && track->isReady() &&
3608 !track->isPaused() && !track->isTerminated())
3609 {
3610 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611
Glenn Kasten952eeb22012-03-06 11:30:57 -08003612 if (track->mFillingUpStatus == Track::FS_FILLED) {
3613 track->mFillingUpStatus = Track::FS_ACTIVE;
3614 mLeftVolFloat = mRightVolFloat = 0;
3615 mLeftVolShort = mRightVolShort = 0;
3616 if (track->mState == TrackBase::RESUMING) {
3617 track->mState = TrackBase::ACTIVE;
3618 rampVolume = true;
3619 }
3620 } else if (cblk->server != 0) {
3621 // If the track is stopped before the first frame was mixed,
3622 // do not apply ramp
3623 rampVolume = true;
3624 }
3625 // compute volume for this track
3626 float left, right;
3627 if (track->isMuted() || mMasterMute || track->isPausing() ||
3628 mStreamTypes[track->streamType()].mute) {
3629 left = right = 0;
3630 if (track->isPausing()) {
3631 track->setPaused();
3632 }
3633 } else {
3634 float typeVolume = mStreamTypes[track->streamType()].volume;
3635 float v = mMasterVolume * typeVolume;
3636 uint32_t vlr = cblk->getVolumeLR();
3637 float v_clamped = v * (vlr & 0xFFFF);
3638 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3639 left = v_clamped/MAX_GAIN;
3640 v_clamped = v * (vlr >> 16);
3641 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3642 right = v_clamped/MAX_GAIN;
3643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644
Glenn Kasten952eeb22012-03-06 11:30:57 -08003645 if (left != mLeftVolFloat || right != mRightVolFloat) {
3646 mLeftVolFloat = left;
3647 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648
Glenn Kasten952eeb22012-03-06 11:30:57 -08003649 // If audio HAL implements volume control,
3650 // force software volume to nominal value
3651 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3652 left = 1.0f;
3653 right = 1.0f;
3654 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003655
Glenn Kasten952eeb22012-03-06 11:30:57 -08003656 // Convert volumes from float to 8.24
3657 uint32_t vl = (uint32_t)(left * (1 << 24));
3658 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659
Glenn Kasten952eeb22012-03-06 11:30:57 -08003660 // Delegate volume control to effect in track effect chain if needed
3661 // only one effect chain can be present on DirectOutputThread, so if
3662 // there is one, the track is connected to it
3663 if (!mEffectChains.isEmpty()) {
3664 // Do not ramp volume if volume is controlled by effect
3665 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666 rampVolume = false;
3667 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669
Glenn Kasten952eeb22012-03-06 11:30:57 -08003670 // Convert volumes from 8.24 to 4.12 format
3671 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3672 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3673 leftVol = (uint16_t)v_clamped;
3674 v_clamped = (vr + (1 << 11)) >> 12;
3675 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3676 rightVol = (uint16_t)v_clamped;
3677 } else {
3678 leftVol = mLeftVolShort;
3679 rightVol = mRightVolShort;
3680 rampVolume = false;
3681 }
3682
3683 // reset retry count
3684 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003685 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003686 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003687 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003688 // clear effect chain input buffer if an active track underruns to avoid sending
3689 // previous audio buffer again to effects
3690 if (!mEffectChains.isEmpty()) {
3691 mEffectChains[0]->clearInputBuffer();
3692 }
3693
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003695 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3696 // We have consumed all the buffers of this track.
3697 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003698 // TODO: implement behavior for compressed audio
3699 size_t audioHALFrames =
3700 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3701 size_t framesWritten =
3702 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3703 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003704 if (track->isStopped()) {
3705 track->reset();
3706 }
Eric Laurenta011e352012-03-29 15:51:43 -07003707 trackToRemove = track;
3708 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003709 } else {
3710 // No buffers for this track. Give it a few chances to
3711 // fill a buffer, then remove it from active list.
3712 if (--(track->mRetryCount) <= 0) {
3713 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3714 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003716 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717 }
3718 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003719 }
3720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003722 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003723 // remove all the tracks that need to be...
3724 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003725 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003726 mActiveTracks.remove(trackToRemove);
3727 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003728 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003729 trackToRemove->sessionId());
3730 mEffectChains[0]->decActiveTrackCnt();
3731 }
3732 if (trackToRemove->isTerminated()) {
3733 removeTrack_l(trackToRemove);
3734 }
3735 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736
Glenn Kastenfec279f2012-03-08 07:47:15 -08003737 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003738}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003739
Glenn Kasten000f0e32012-03-01 17:10:56 -08003740void AudioFlinger::DirectOutputThread::threadLoop_mix()
3741{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 AudioBufferProvider::Buffer buffer;
3743 size_t frameCount = mFrameCount;
3744 int8_t *curBuf = (int8_t *)mMixBuffer;
3745 // output audio to hardware
3746 while (frameCount) {
3747 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003748 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 if (CC_UNLIKELY(buffer.raw == NULL)) {
3750 memset(curBuf, 0, frameCount * mFrameSize);
3751 break;
3752 }
3753 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3754 frameCount -= buffer.frameCount;
3755 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003756 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003757 }
3758 sleepTime = 0;
3759 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003760 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003761
3762 // apply volume
3763
3764 // Do not apply volume on compressed audio
3765 if (!audio_is_linear_pcm(mFormat)) {
3766 return;
3767 }
3768
3769 // convert to signed 16 bit before volume calculation
3770 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3771 size_t count = mFrameCount * mChannelCount;
3772 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3773 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003774 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003775 *dst-- = (int16_t)(*src--^0x80) << 8;
3776 }
3777 }
3778
3779 frameCount = mFrameCount;
3780 int16_t *out = mMixBuffer;
3781 if (rampVolume) {
3782 if (mChannelCount == 1) {
3783 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3784 int32_t vlInc = d / (int32_t)frameCount;
3785 int32_t vl = ((int32_t)mLeftVolShort << 16);
3786 do {
3787 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3788 out++;
3789 vl += vlInc;
3790 } while (--frameCount);
3791
3792 } else {
3793 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3794 int32_t vlInc = d / (int32_t)frameCount;
3795 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3796 int32_t vrInc = d / (int32_t)frameCount;
3797 int32_t vl = ((int32_t)mLeftVolShort << 16);
3798 int32_t vr = ((int32_t)mRightVolShort << 16);
3799 do {
3800 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3801 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3802 out += 2;
3803 vl += vlInc;
3804 vr += vrInc;
3805 } while (--frameCount);
3806 }
3807 } else {
3808 if (mChannelCount == 1) {
3809 do {
3810 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3811 out++;
3812 } while (--frameCount);
3813 } else {
3814 do {
3815 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3816 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3817 out += 2;
3818 } while (--frameCount);
3819 }
3820 }
3821
3822 // convert back to unsigned 8 bit after volume calculation
3823 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3824 size_t count = mFrameCount * mChannelCount;
3825 int16_t *src = mMixBuffer;
3826 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003827 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003828 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3829 }
3830 }
3831
3832 mLeftVolShort = leftVol;
3833 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003834}
3835
3836void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3837{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003838 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003839 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003840 sleepTime = activeSleepTime;
3841 } else {
3842 sleepTime = idleSleepTime;
3843 }
3844 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003845 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003846 sleepTime = 0;
3847 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003848}
3849
3850// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003851int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852{
3853 return 0;
3854}
3855
3856// deleteTrackName_l() must be called with ThreadBase::mLock held
3857void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3858{
3859}
3860
3861// checkForNewParameters_l() must be called with ThreadBase::mLock held
3862bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3863{
3864 bool reconfig = false;
3865
3866 while (!mNewParameters.isEmpty()) {
3867 status_t status = NO_ERROR;
3868 String8 keyValuePair = mNewParameters[0];
3869 AudioParameter param = AudioParameter(keyValuePair);
3870 int value;
3871
3872 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3873 // do not accept frame count changes if tracks are open as the track buffer
3874 // size depends on frame count and correct behavior would not be garantied
3875 // if frame count is changed after track creation
3876 if (!mTracks.isEmpty()) {
3877 status = INVALID_OPERATION;
3878 } else {
3879 reconfig = true;
3880 }
3881 }
3882 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003883 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003884 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003886 mOutput->stream->common.standby(&mOutput->stream->common);
3887 mStandby = true;
3888 mBytesWritten = 0;
3889 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003890 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891 }
3892 if (status == NO_ERROR && reconfig) {
3893 readOutputParameters();
3894 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3895 }
3896 }
3897
3898 mNewParameters.removeAt(0);
3899
3900 mParamStatus = status;
3901 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003902 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3903 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003904 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 }
3906 return reconfig;
3907}
3908
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003909uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910{
3911 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003912 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003913 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 } else {
3915 time = 10000;
3916 }
3917 return time;
3918}
3919
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003920uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921{
3922 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003923 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003924 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 } else {
3926 time = 10000;
3927 }
3928 return time;
3929}
3930
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003931uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003932{
3933 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003934 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003935 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3936 } else {
3937 time = 10000;
3938 }
3939 return time;
3940}
3941
Glenn Kasten66fcab92012-02-24 14:59:21 -08003942void AudioFlinger::DirectOutputThread::cacheParameters_l()
3943{
3944 PlaybackThread::cacheParameters_l();
3945
3946 // use shorter standby delay as on normal output to release
3947 // hardware resources as soon as possible
3948 standbyDelay = microseconds(activeSleepTime*2);
3949}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003950
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951// ----------------------------------------------------------------------------
3952
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003953AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003954 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003955 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3956 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958 addOutputTrack(mainThread);
3959}
3960
3961AudioFlinger::DuplicatingThread::~DuplicatingThread()
3962{
3963 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3964 mOutputTracks[i]->destroy();
3965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966}
3967
Glenn Kasten000f0e32012-03-01 17:10:56 -08003968void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003970 // mix buffers...
3971 if (outputsReady(outputTracks)) {
3972 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3973 } else {
3974 memset(mMixBuffer, 0, mixBufferSize);
3975 }
3976 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003977 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003978}
3979
3980void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3981{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003982 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003983 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003984 sleepTime = activeSleepTime;
3985 } else {
3986 sleepTime = idleSleepTime;
3987 }
3988 } else if (mBytesWritten != 0) {
3989 // flush remaining overflow buffers in output tracks
3990 for (size_t i = 0; i < outputTracks.size(); i++) {
3991 if (outputTracks[i]->isActive()) {
3992 sleepTime = 0;
3993 writeFrames = 0;
3994 memset(mMixBuffer, 0, mixBufferSize);
3995 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003997 }
3998 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003999}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000
Glenn Kasten000f0e32012-03-01 17:10:56 -08004001void AudioFlinger::DuplicatingThread::threadLoop_write()
4002{
Glenn Kasten66fcab92012-02-24 14:59:21 -08004003 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004004 for (size_t i = 0; i < outputTracks.size(); i++) {
4005 outputTracks[i]->write(mMixBuffer, writeFrames);
4006 }
4007 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004008}
Glenn Kasten688a6402012-02-29 07:57:06 -08004009
Glenn Kasten000f0e32012-03-01 17:10:56 -08004010void AudioFlinger::DuplicatingThread::threadLoop_standby()
4011{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004012 // DuplicatingThread implements standby by stopping all tracks
4013 for (size_t i = 0; i < outputTracks.size(); i++) {
4014 outputTracks[i]->stop();
4015 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004016}
4017
Glenn Kastenfa26a852012-03-06 11:28:04 -08004018void AudioFlinger::DuplicatingThread::saveOutputTracks()
4019{
4020 outputTracks = mOutputTracks;
4021}
4022
4023void AudioFlinger::DuplicatingThread::clearOutputTracks()
4024{
4025 outputTracks.clear();
4026}
4027
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4029{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004030 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004031 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004032 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004033 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 this,
4035 mSampleRate,
4036 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004037 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038 frameCount);
4039 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004040 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004042 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004043 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044 }
4045}
4046
4047void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4048{
4049 Mutex::Autolock _l(mLock);
4050 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004051 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052 mOutputTracks[i]->destroy();
4053 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004054 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 return;
4056 }
4057 }
Steve Block3856b092011-10-20 11:56:00 +01004058 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059}
4060
Glenn Kasten438b0362012-03-06 11:24:48 -08004061// caller must hold mLock
4062void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063{
4064 mWaitTimeMs = UINT_MAX;
4065 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4066 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004067 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4069 if (waitTimeMs < mWaitTimeMs) {
4070 mWaitTimeMs = waitTimeMs;
4071 }
4072 }
4073 }
4074}
4075
4076
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004077bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078{
4079 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004080 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004081 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004082 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 return false;
4084 }
4085 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4086 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004087 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088 return false;
4089 }
4090 }
4091 return true;
4092}
4093
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004094uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095{
4096 return (mWaitTimeMs * 1000) / 2;
4097}
4098
Glenn Kasten66fcab92012-02-24 14:59:21 -08004099void AudioFlinger::DuplicatingThread::cacheParameters_l()
4100{
4101 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4102 updateWaitTime_l();
4103
4104 MixerThread::cacheParameters_l();
4105}
4106
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107// ----------------------------------------------------------------------------
4108
4109// TrackBase constructor must be called with AudioFlinger::mLock held
4110AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004111 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 const sp<Client>& client,
4113 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004114 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004115 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117 const sp<IMemory>& sharedBuffer,
4118 int sessionId)
4119 : RefBase(),
4120 mThread(thread),
4121 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004122 mCblk(NULL),
4123 // mBuffer
4124 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125 mFrameCount(0),
4126 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004127 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004129 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004131 // mChannelCount
4132 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133{
Steve Block3856b092011-10-20 11:56:00 +01004134 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135
Steve Blockb8a80522011-12-20 16:23:08 +00004136 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004137 size_t size = sizeof(audio_track_cblk_t);
4138 uint8_t channelCount = popcount(channelMask);
4139 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4140 if (sharedBuffer == 0) {
4141 size += bufferSize;
4142 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004144 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 mCblkMemory = client->heap()->allocate(size);
4146 if (mCblkMemory != 0) {
4147 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004148 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 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;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004158 mChannelCount = channelCount;
4159 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 if (sharedBuffer == 0) {
4161 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4162 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4163 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004164 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 mCblk->flags = CBLK_UNDERRUN_ON;
4166 } else {
4167 mBuffer = sharedBuffer->pointer();
4168 }
4169 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4170 }
4171 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004172 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 client->heap()->dump("AudioTrack");
4174 return;
4175 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004176 } else {
4177 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004178 // construct the shared structure in-place.
4179 new(mCblk) audio_track_cblk_t();
4180 // clear all buffers
4181 mCblk->frameCount = frameCount;
4182 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004183// uncomment the following lines to quickly test 32-bit wraparound
4184// mCblk->user = 0xffff0000;
4185// mCblk->server = 0xffff0000;
4186// mCblk->userBase = 0xffff0000;
4187// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004188 mChannelCount = channelCount;
4189 mChannelMask = channelMask;
4190 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4191 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4192 // Force underrun condition to avoid false underrun callback until first data is
4193 // written to buffer (other flags are cleared)
4194 mCblk->flags = CBLK_UNDERRUN_ON;
4195 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197}
4198
4199AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4200{
Glenn Kastena0d68332012-01-27 16:47:15 -08004201 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004202 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004204 } else {
4205 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 }
4207 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004208 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004209 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004210 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004212 // If the client's reference count drops to zero, the associated destructor
4213 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4214 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 mClient.clear();
4216 }
4217}
4218
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004219// AudioBufferProvider interface
4220// getNextBuffer() = 0;
4221// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4223{
Glenn Kastene0feee32011-12-13 11:53:26 -08004224 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004226 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004227 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 buffer->frameCount = 0;
4229}
4230
4231bool AudioFlinger::ThreadBase::TrackBase::step() {
4232 bool result;
4233 audio_track_cblk_t* cblk = this->cblk();
4234
4235 result = cblk->stepServer(mFrameCount);
4236 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004237 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004238 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 }
4240 return result;
4241}
4242
4243void AudioFlinger::ThreadBase::TrackBase::reset() {
4244 audio_track_cblk_t* cblk = this->cblk();
4245
4246 cblk->user = 0;
4247 cblk->server = 0;
4248 cblk->userBase = 0;
4249 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004250 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004251 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252}
4253
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4255 return (int)mCblk->sampleRate;
4256}
4257
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4259 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004260 size_t frameSize = cblk->frameSize;
4261 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4262 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263
4264 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004265 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4266 "TrackBase::getBuffer buffer out of range:\n"
4267 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4268 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004270 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271
4272 return bufferStart;
4273}
4274
Eric Laurenta011e352012-03-29 15:51:43 -07004275status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4276{
4277 mSyncEvents.add(event);
4278 return NO_ERROR;
4279}
4280
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281// ----------------------------------------------------------------------------
4282
4283// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4284AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004285 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004287 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004289 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004290 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 int frameCount,
4292 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004293 int sessionId,
4294 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004295 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004296 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004297 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004298 // mRetryCount initialized later when needed
4299 mSharedBuffer(sharedBuffer),
4300 mStreamType(streamType),
4301 mName(-1), // see note below
4302 mMainBuffer(thread->mixBuffer()),
4303 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004304 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004305 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004306 mFlags(flags),
4307 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004308 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004309 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310{
4311 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4313 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004314 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004315 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4316 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
4317 if (mName < 0) {
4318 ALOGE("no more track names available");
4319 return;
4320 }
4321 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004322 if (flags & IAudioFlinger::TRACK_FAST) {
4323 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4324 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4325 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004326 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004327 // FIXME This is too eager. We allocate a fast track index before the
4328 // fast track becomes active. Since fast tracks are a scarce resource,
4329 // this means we are potentially denying other more important fast tracks from
4330 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004331 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004332 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004333 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004334 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004335 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004337 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338}
4339
4340AudioFlinger::PlaybackThread::Track::~Track()
4341{
Steve Block3856b092011-10-20 11:56:00 +01004342 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343 sp<ThreadBase> thread = mThread.promote();
4344 if (thread != 0) {
4345 Mutex::Autolock _l(thread->mLock);
4346 mState = TERMINATED;
4347 }
4348}
4349
4350void AudioFlinger::PlaybackThread::Track::destroy()
4351{
4352 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4353 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004354 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 // we must acquire a strong reference on this Track before locking mLock
4356 // here so that the destructor is called only when exiting this function.
4357 // On the other hand, as long as Track::destroy() is only called by
4358 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4359 // this Track with its member mTrack.
4360 sp<Track> keep(this);
4361 { // scope for mLock
4362 sp<ThreadBase> thread = mThread.promote();
4363 if (thread != 0) {
4364 if (!isOutputTrack()) {
4365 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004366 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004367
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004368#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004369 // to track the speaker usage
4370 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004371#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 }
4373 AudioSystem::releaseOutput(thread->id());
4374 }
4375 Mutex::Autolock _l(thread->mLock);
4376 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4377 playbackThread->destroyTrack_l(this);
4378 }
4379 }
4380}
4381
Glenn Kasten288ed212012-04-25 17:52:27 -07004382/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4383{
Glenn Kastene213c862012-04-25 13:46:15 -07004384 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07004385 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004386}
4387
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4389{
Glenn Kasten83d86532012-01-17 14:39:34 -08004390 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004391 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004392 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004393 } else {
4394 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4395 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004396 track_state state = mState;
4397 char stateChar;
4398 switch (state) {
4399 case IDLE:
4400 stateChar = 'I';
4401 break;
4402 case TERMINATED:
4403 stateChar = 'T';
4404 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004405 case STOPPING_1:
4406 stateChar = 's';
4407 break;
4408 case STOPPING_2:
4409 stateChar = '5';
4410 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004411 case STOPPED:
4412 stateChar = 'S';
4413 break;
4414 case RESUMING:
4415 stateChar = 'R';
4416 break;
4417 case ACTIVE:
4418 stateChar = 'A';
4419 break;
4420 case PAUSING:
4421 stateChar = 'p';
4422 break;
4423 case PAUSED:
4424 stateChar = 'P';
4425 break;
Eric Laurent29864602012-05-08 18:57:51 -07004426 case FLUSHED:
4427 stateChar = 'F';
4428 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004429 default:
4430 stateChar = '?';
4431 break;
4432 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004433 char nowInUnderrun;
4434 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4435 case UNDERRUN_FULL:
4436 nowInUnderrun = ' ';
4437 break;
4438 case UNDERRUN_PARTIAL:
4439 nowInUnderrun = '<';
4440 break;
4441 case UNDERRUN_EMPTY:
4442 nowInUnderrun = '*';
4443 break;
4444 default:
4445 nowInUnderrun = '?';
4446 break;
4447 }
Glenn Kastene213c862012-04-25 13:46:15 -07004448 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4449 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004450 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451 mStreamType,
4452 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004453 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004454 mSessionId,
4455 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004456 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004457 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 mMute,
4459 mFillingUpStatus,
4460 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004461 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4462 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463 mCblk->server,
4464 mCblk->user,
4465 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004466 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004467 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004468 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004469 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470}
4471
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004472// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004473status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004474 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004476 audio_track_cblk_t* cblk = this->cblk();
4477 uint32_t framesReady;
4478 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004480 // Check if last stepServer failed, try to step now
4481 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004482 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4483 // Since the fast mixer is higher priority than client callback thread,
4484 // it does not result in priority inversion for client.
4485 // But a non-blocking solution would be preferable to avoid
4486 // fast mixer being unable to tryLock(), and
4487 // to avoid the extra context switches if the client wakes up,
4488 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004489 if (!step()) goto getNextBuffer_exit;
4490 ALOGV("stepServer recovered");
4491 mStepServerFailed = false;
4492 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493
Glenn Kasten288ed212012-04-25 17:52:27 -07004494 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004495 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004497 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 uint32_t s = cblk->server;
4499 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4500
4501 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4502 if (framesReq > framesReady) {
4503 framesReq = framesReady;
4504 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004505 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 framesReq = bufferEnd - s;
4507 }
4508
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004509 buffer->raw = getBuffer(s, framesReq);
4510 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004512 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515
4516getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004517 buffer->raw = NULL;
4518 buffer->frameCount = 0;
4519 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4520 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521}
4522
Glenn Kasten288ed212012-04-25 17:52:27 -07004523// Note that framesReady() takes a mutex on the control block using tryLock().
4524// This could result in priority inversion if framesReady() is called by the normal mixer,
4525// as the normal mixer thread runs at lower
4526// priority than the client's callback thread: there is a short window within framesReady()
4527// during which the normal mixer could be preempted, and the client callback would block.
4528// Another problem can occur if framesReady() is called by the fast mixer:
4529// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4530// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4531size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004532 return mCblk->framesReady();
4533}
4534
Glenn Kasten288ed212012-04-25 17:52:27 -07004535// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004537 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538
John Grossman4ff14ba2012-02-08 16:37:41 -08004539 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4541 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004542 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543 return true;
4544 }
4545 return false;
4546}
4547
Glenn Kasten3acbd052012-02-28 10:39:56 -08004548status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004549 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550{
4551 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004552 ALOGV("start(%d), calling pid %d session %d",
4553 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004554
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 sp<ThreadBase> thread = mThread.promote();
4556 if (thread != 0) {
4557 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004558 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 // here the track could be either new, or restarted
4560 // in both cases "unstop" the track
4561 if (mState == PAUSED) {
4562 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004563 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 } else {
4565 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004566 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 }
4568
4569 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4570 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004571 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004573
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004574#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004575 // to track the speaker usage
4576 if (status == NO_ERROR) {
4577 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4578 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004579#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 }
4581 if (status == NO_ERROR) {
4582 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4583 playbackThread->addTrack_l(this);
4584 } else {
4585 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004586 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 }
4588 } else {
4589 status = BAD_VALUE;
4590 }
4591 return status;
4592}
4593
4594void AudioFlinger::PlaybackThread::Track::stop()
4595{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004596 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 sp<ThreadBase> thread = mThread.promote();
4598 if (thread != 0) {
4599 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004600 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004601 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 // If the track is not active (PAUSED and buffers full), flush buffers
4603 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4604 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4605 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004606 mState = STOPPED;
4607 } else if (!isFastTrack()) {
4608 mState = STOPPED;
4609 } else {
4610 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4611 // and then to STOPPED and reset() when presentation is complete
4612 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004614 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 }
4616 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4617 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004618 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004620
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004621#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004622 // to track the speaker usage
4623 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004624#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625 }
4626 }
4627}
4628
4629void AudioFlinger::PlaybackThread::Track::pause()
4630{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004631 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004632 sp<ThreadBase> thread = mThread.promote();
4633 if (thread != 0) {
4634 Mutex::Autolock _l(thread->mLock);
4635 if (mState == ACTIVE || mState == RESUMING) {
4636 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004637 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 if (!isOutputTrack()) {
4639 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004640 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004642
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004643#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004644 // to track the speaker usage
4645 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004646#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004647 }
4648 }
4649 }
4650}
4651
4652void AudioFlinger::PlaybackThread::Track::flush()
4653{
Steve Block3856b092011-10-20 11:56:00 +01004654 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655 sp<ThreadBase> thread = mThread.promote();
4656 if (thread != 0) {
4657 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004658 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4659 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660 return;
4661 }
4662 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004663 // FLUSHED state
4664 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004665 // do not reset the track if it is still in the process of being stopped or paused.
4666 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004667 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004668 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004669 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4670 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4671 reset();
4672 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 }
4674}
4675
4676void AudioFlinger::PlaybackThread::Track::reset()
4677{
4678 // Do not reset twice to avoid discarding data written just after a flush and before
4679 // the audioflinger thread detects the track is stopped.
4680 if (!mResetDone) {
4681 TrackBase::reset();
4682 // Force underrun condition to avoid false underrun callback until first data is
4683 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004684 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4685 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686 mFillingUpStatus = FS_FILLING;
4687 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004688 if (mState == FLUSHED) {
4689 mState = IDLE;
4690 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 }
4692}
4693
4694void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4695{
4696 mMute = muted;
4697}
4698
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4700{
4701 status_t status = DEAD_OBJECT;
4702 sp<ThreadBase> thread = mThread.promote();
4703 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004704 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4705 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004706 }
4707 return status;
4708}
4709
4710void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4711{
4712 mAuxEffectId = EffectId;
4713 mAuxBuffer = buffer;
4714}
4715
Eric Laurenta011e352012-03-29 15:51:43 -07004716bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4717 size_t audioHalFrames)
4718{
4719 // a track is considered presented when the total number of frames written to audio HAL
4720 // corresponds to the number of frames written when presentationComplete() is called for the
4721 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4722 if (mPresentationCompleteFrames == 0) {
4723 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4724 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4725 mPresentationCompleteFrames, audioHalFrames);
4726 }
4727 if (framesWritten >= mPresentationCompleteFrames) {
4728 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4729 mSessionId, framesWritten);
4730 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004731 return true;
4732 }
4733 return false;
4734}
4735
4736void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4737{
4738 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4739 if (mSyncEvents[i]->type() == type) {
4740 mSyncEvents[i]->trigger();
4741 mSyncEvents.removeAt(i);
4742 i--;
4743 }
4744 }
4745}
4746
Glenn Kasten58912562012-04-03 10:45:00 -07004747// implement VolumeBufferProvider interface
4748
4749uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4750{
4751 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4752 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4753 uint32_t vlr = mCblk->getVolumeLR();
4754 uint32_t vl = vlr & 0xFFFF;
4755 uint32_t vr = vlr >> 16;
4756 // track volumes come from shared memory, so can't be trusted and must be clamped
4757 if (vl > MAX_GAIN_INT) {
4758 vl = MAX_GAIN_INT;
4759 }
4760 if (vr > MAX_GAIN_INT) {
4761 vr = MAX_GAIN_INT;
4762 }
4763 // now apply the cached master volume and stream type volume;
4764 // this is trusted but lacks any synchronization or barrier so may be stale
4765 float v = mCachedVolume;
4766 vl *= v;
4767 vr *= v;
4768 // re-combine into U4.16
4769 vlr = (vr << 16) | (vl & 0xFFFF);
4770 // FIXME look at mute, pause, and stop flags
4771 return vlr;
4772}
Eric Laurenta011e352012-03-29 15:51:43 -07004773
Eric Laurent29864602012-05-08 18:57:51 -07004774status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4775{
4776 if (mState == TERMINATED || mState == PAUSED ||
4777 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4778 (mState == STOPPED)))) {
4779 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4780 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4781 event->cancel();
4782 return INVALID_OPERATION;
4783 }
4784 TrackBase::setSyncEvent(event);
4785 return NO_ERROR;
4786}
4787
John Grossman4ff14ba2012-02-08 16:37:41 -08004788// timed audio tracks
4789
4790sp<AudioFlinger::PlaybackThread::TimedTrack>
4791AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004792 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004793 const sp<Client>& client,
4794 audio_stream_type_t streamType,
4795 uint32_t sampleRate,
4796 audio_format_t format,
4797 uint32_t channelMask,
4798 int frameCount,
4799 const sp<IMemory>& sharedBuffer,
4800 int sessionId) {
4801 if (!client->reserveTimedTrack())
4802 return NULL;
4803
Glenn Kastena0356762012-03-19 10:38:51 -07004804 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004805 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4806 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004807}
4808
4809AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004810 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004811 const sp<Client>& client,
4812 audio_stream_type_t streamType,
4813 uint32_t sampleRate,
4814 audio_format_t format,
4815 uint32_t channelMask,
4816 int frameCount,
4817 const sp<IMemory>& sharedBuffer,
4818 int sessionId)
4819 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004820 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004821 mQueueHeadInFlight(false),
4822 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004823 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004824 mTimedSilenceBuffer(NULL),
4825 mTimedSilenceBufferSize(0),
4826 mTimedAudioOutputOnTime(false),
4827 mMediaTimeTransformValid(false)
4828{
4829 LocalClock lc;
4830 mLocalTimeFreq = lc.getLocalFreq();
4831
4832 mLocalTimeToSampleTransform.a_zero = 0;
4833 mLocalTimeToSampleTransform.b_zero = 0;
4834 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4835 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4836 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4837 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004838
4839 mMediaTimeToSampleTransform.a_zero = 0;
4840 mMediaTimeToSampleTransform.b_zero = 0;
4841 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4842 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4843 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4844 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004845}
4846
4847AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4848 mClient->releaseTimedTrack();
4849 delete [] mTimedSilenceBuffer;
4850}
4851
4852status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4853 size_t size, sp<IMemory>* buffer) {
4854
4855 Mutex::Autolock _l(mTimedBufferQueueLock);
4856
4857 trimTimedBufferQueue_l();
4858
4859 // lazily initialize the shared memory heap for timed buffers
4860 if (mTimedMemoryDealer == NULL) {
4861 const int kTimedBufferHeapSize = 512 << 10;
4862
4863 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4864 "AudioFlingerTimed");
4865 if (mTimedMemoryDealer == NULL)
4866 return NO_MEMORY;
4867 }
4868
4869 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4870 if (newBuffer == NULL) {
4871 newBuffer = mTimedMemoryDealer->allocate(size);
4872 if (newBuffer == NULL)
4873 return NO_MEMORY;
4874 }
4875
4876 *buffer = newBuffer;
4877 return NO_ERROR;
4878}
4879
4880// caller must hold mTimedBufferQueueLock
4881void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4882 int64_t mediaTimeNow;
4883 {
4884 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4885 if (!mMediaTimeTransformValid)
4886 return;
4887
4888 int64_t targetTimeNow;
4889 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4890 ? mCCHelper.getCommonTime(&targetTimeNow)
4891 : mCCHelper.getLocalTime(&targetTimeNow);
4892
4893 if (OK != res)
4894 return;
4895
4896 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4897 &mediaTimeNow)) {
4898 return;
4899 }
4900 }
4901
John Grossman1c345192012-03-27 14:00:17 -07004902 size_t trimEnd;
4903 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004904 int64_t bufEnd;
4905
John Grossmanc95cfbb2012-04-12 11:53:11 -07004906 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4907 // We have a next buffer. Just use its PTS as the PTS of the frame
4908 // following the last frame in this buffer. If the stream is sparse
4909 // (ie, there are deliberate gaps left in the stream which should be
4910 // filled with silence by the TimedAudioTrack), then this can result
4911 // in one extra buffer being left un-trimmed when it could have
4912 // been. In general, this is not typical, and we would rather
4913 // optimized away the TS calculation below for the more common case
4914 // where PTSes are contiguous.
4915 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4916 } else {
4917 // We have no next buffer. Compute the PTS of the frame following
4918 // the last frame in this buffer by computing the duration of of
4919 // this frame in media time units and adding it to the PTS of the
4920 // buffer.
4921 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4922 / mCblk->frameSize;
4923
4924 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4925 &bufEnd)) {
4926 ALOGE("Failed to convert frame count of %lld to media time"
4927 " duration" " (scale factor %d/%u) in %s",
4928 frameCount,
4929 mMediaTimeToSampleTransform.a_to_b_numer,
4930 mMediaTimeToSampleTransform.a_to_b_denom,
4931 __PRETTY_FUNCTION__);
4932 break;
4933 }
4934 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004935 }
John Grossman9fbdee12012-03-26 17:51:46 -07004936
4937 if (bufEnd > mediaTimeNow)
4938 break;
4939
4940 // Is the buffer we want to use in the middle of a mix operation right
4941 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4942 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004943 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004944 mTrimQueueHeadOnRelease = true;
4945 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004946 }
4947
John Grossman9fbdee12012-03-26 17:51:46 -07004948 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004949 if (trimStart < trimEnd) {
4950 // Update the bookkeeping for framesReady()
4951 for (size_t i = trimStart; i < trimEnd; ++i) {
4952 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4953 }
4954
4955 // Now actually remove the buffers from the queue.
4956 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004957 }
4958}
4959
John Grossman1c345192012-03-27 14:00:17 -07004960void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4961 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004962 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4963 "%s called (reason \"%s\"), but timed buffer queue has no"
4964 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004965
4966 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4967 mTimedBufferQueue.removeAt(0);
4968}
4969
4970void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4971 const TimedBuffer& buf,
4972 const char* logTag) {
4973 uint32_t bufBytes = buf.buffer()->size();
4974 uint32_t consumedAlready = buf.position();
4975
Eric Laurentb388e532012-04-14 13:32:48 -07004976 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004977 "Bad bookkeeping while updating frames pending. Timed buffer is"
4978 " only %u bytes long, but claims to have consumed %u"
4979 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004980 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004981
4982 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004983 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4984 "Bad bookkeeping while updating frames pending. Should have at"
4985 " least %u queued frames, but we think we have only %u. (update"
4986 " reason: \"%s\")",
4987 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004988
4989 mFramesPendingInQueue -= bufFrames;
4990}
4991
John Grossman4ff14ba2012-02-08 16:37:41 -08004992status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4993 const sp<IMemory>& buffer, int64_t pts) {
4994
4995 {
4996 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4997 if (!mMediaTimeTransformValid)
4998 return INVALID_OPERATION;
4999 }
5000
5001 Mutex::Autolock _l(mTimedBufferQueueLock);
5002
John Grossman1c345192012-03-27 14:00:17 -07005003 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5004 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005005 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5006
5007 return NO_ERROR;
5008}
5009
5010status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5011 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5012
John Grossman1c345192012-03-27 14:00:17 -07005013 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5014 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5015 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005016
5017 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5018 target == TimedAudioTrack::COMMON_TIME)) {
5019 return BAD_VALUE;
5020 }
5021
5022 Mutex::Autolock lock(mMediaTimeTransformLock);
5023 mMediaTimeTransform = xform;
5024 mMediaTimeTransformTarget = target;
5025 mMediaTimeTransformValid = true;
5026
5027 return NO_ERROR;
5028}
5029
5030#define min(a, b) ((a) < (b) ? (a) : (b))
5031
5032// implementation of getNextBuffer for tracks whose buffers have timestamps
5033status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5034 AudioBufferProvider::Buffer* buffer, int64_t pts)
5035{
5036 if (pts == AudioBufferProvider::kInvalidPTS) {
5037 buffer->raw = 0;
5038 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005039 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005040 return INVALID_OPERATION;
5041 }
5042
John Grossman4ff14ba2012-02-08 16:37:41 -08005043 Mutex::Autolock _l(mTimedBufferQueueLock);
5044
John Grossman9fbdee12012-03-26 17:51:46 -07005045 ALOG_ASSERT(!mQueueHeadInFlight,
5046 "getNextBuffer called without releaseBuffer!");
5047
John Grossman4ff14ba2012-02-08 16:37:41 -08005048 while (true) {
5049
5050 // if we have no timed buffers, then fail
5051 if (mTimedBufferQueue.isEmpty()) {
5052 buffer->raw = 0;
5053 buffer->frameCount = 0;
5054 return NOT_ENOUGH_DATA;
5055 }
5056
5057 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5058
5059 // calculate the PTS of the head of the timed buffer queue expressed in
5060 // local time
5061 int64_t headLocalPTS;
5062 {
5063 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5064
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005065 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005066
5067 if (mMediaTimeTransform.a_to_b_denom == 0) {
5068 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005069 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005070 return NO_ERROR;
5071 }
5072
5073 int64_t transformedPTS;
5074 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5075 &transformedPTS)) {
5076 // the transform failed. this shouldn't happen, but if it does
5077 // then just drop this buffer
5078 ALOGW("timedGetNextBuffer transform failed");
5079 buffer->raw = 0;
5080 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005081 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005082 return NO_ERROR;
5083 }
5084
5085 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5086 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5087 &headLocalPTS)) {
5088 buffer->raw = 0;
5089 buffer->frameCount = 0;
5090 return INVALID_OPERATION;
5091 }
5092 } else {
5093 headLocalPTS = transformedPTS;
5094 }
5095 }
5096
5097 // adjust the head buffer's PTS to reflect the portion of the head buffer
5098 // that has already been consumed
5099 int64_t effectivePTS = headLocalPTS +
5100 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5101
5102 // Calculate the delta in samples between the head of the input buffer
5103 // queue and the start of the next output buffer that will be written.
5104 // If the transformation fails because of over or underflow, it means
5105 // that the sample's position in the output stream is so far out of
5106 // whack that it should just be dropped.
5107 int64_t sampleDelta;
5108 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5109 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005110 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5111 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005112 continue;
5113 }
5114 if (!mLocalTimeToSampleTransform.doForwardTransform(
5115 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005116 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005117 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005118 continue;
5119 }
5120
John Grossman1c345192012-03-27 14:00:17 -07005121 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5122 " sampleDelta=[%d.%08x]",
5123 head.pts(), head.position(), pts,
5124 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5125 + (sampleDelta >> 32)),
5126 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005127
5128 // if the delta between the ideal placement for the next input sample and
5129 // the current output position is within this threshold, then we will
5130 // concatenate the next input samples to the previous output
5131 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005132 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005133
5134 // if this is the first buffer of audio that we're emitting from this track
5135 // then it should be almost exactly on time.
5136 const int64_t kSampleStartupThreshold = 1LL << 32;
5137
5138 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005139 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005140 // the next input is close enough to being on time, so concatenate it
5141 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005142 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005143
John Grossman1c345192012-03-27 14:00:17 -07005144 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5145 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005146 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005147 }
5148
5149 // Looks like our output is not on time. Reset our on timed status.
5150 // Next time we mix samples from our input queue, then should be within
5151 // the StartupThreshold.
5152 mTimedAudioOutputOnTime = false;
5153 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005154 // the gap between the current output position and the proper start of
5155 // the next input sample is too big, so fill it with silence
5156 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5157
John Grossman9fbdee12012-03-26 17:51:46 -07005158 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005159 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5160 return NO_ERROR;
5161 } else {
5162 // the next input sample is late
5163 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5164 size_t onTimeSamplePosition =
5165 head.position() + lateFrames * mCblk->frameSize;
5166
5167 if (onTimeSamplePosition > head.buffer()->size()) {
5168 // all the remaining samples in the head are too late, so
5169 // drop it and move on
5170 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005171 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005172 continue;
5173 } else {
5174 // skip over the late samples
5175 head.setPosition(onTimeSamplePosition);
5176
5177 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005178 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005179
5180 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5181 return NO_ERROR;
5182 }
5183 }
5184 }
5185}
5186
5187// Yield samples from the timed buffer queue head up to the given output
5188// buffer's capacity.
5189//
5190// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005191void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005192 AudioBufferProvider::Buffer* buffer) {
5193
5194 const TimedBuffer& head = mTimedBufferQueue[0];
5195
5196 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5197 head.position());
5198
5199 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5200 mCblk->frameSize);
5201 size_t framesRequested = buffer->frameCount;
5202 buffer->frameCount = min(framesLeftInHead, framesRequested);
5203
John Grossman9fbdee12012-03-26 17:51:46 -07005204 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005205 mTimedAudioOutputOnTime = true;
5206}
5207
5208// Yield samples of silence up to the given output buffer's capacity
5209//
5210// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005211void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005212 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5213
5214 // lazily allocate a buffer filled with silence
5215 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5216 delete [] mTimedSilenceBuffer;
5217 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5218 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5219 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5220 }
5221
5222 buffer->raw = mTimedSilenceBuffer;
5223 size_t framesRequested = buffer->frameCount;
5224 buffer->frameCount = min(numFrames, framesRequested);
5225
5226 mTimedAudioOutputOnTime = false;
5227}
5228
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005229// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005230void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5231 AudioBufferProvider::Buffer* buffer) {
5232
5233 Mutex::Autolock _l(mTimedBufferQueueLock);
5234
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005235 // If the buffer which was just released is part of the buffer at the head
5236 // of the queue, be sure to update the amt of the buffer which has been
5237 // consumed. If the buffer being returned is not part of the head of the
5238 // queue, its either because the buffer is part of the silence buffer, or
5239 // because the head of the timed queue was trimmed after the mixer called
5240 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005241 if (buffer->raw == mTimedSilenceBuffer) {
5242 ALOG_ASSERT(!mQueueHeadInFlight,
5243 "Queue head in flight during release of silence buffer!");
5244 goto done;
5245 }
5246
5247 ALOG_ASSERT(mQueueHeadInFlight,
5248 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5249 " head in flight.");
5250
5251 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005252 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005253
5254 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005255 void* end = reinterpret_cast<void*>(
5256 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5257 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005258
John Grossman9fbdee12012-03-26 17:51:46 -07005259 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5260 "released buffer not within the head of the timed buffer"
5261 " queue; qHead = [%p, %p], released buffer = %p",
5262 start, end, buffer->raw);
5263
5264 head.setPosition(head.position() +
5265 (buffer->frameCount * mCblk->frameSize));
5266 mQueueHeadInFlight = false;
5267
John Grossman1c345192012-03-27 14:00:17 -07005268 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5269 "Bad bookkeeping during releaseBuffer! Should have at"
5270 " least %u queued frames, but we think we have only %u",
5271 buffer->frameCount, mFramesPendingInQueue);
5272
5273 mFramesPendingInQueue -= buffer->frameCount;
5274
John Grossman9fbdee12012-03-26 17:51:46 -07005275 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5276 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005277 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005278 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005279 }
John Grossman9fbdee12012-03-26 17:51:46 -07005280 } else {
5281 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5282 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005283 }
5284
John Grossman9fbdee12012-03-26 17:51:46 -07005285done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005286 buffer->raw = 0;
5287 buffer->frameCount = 0;
5288}
5289
Glenn Kasten288ed212012-04-25 17:52:27 -07005290size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005291 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005292 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005293}
5294
5295AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5296 : mPTS(0), mPosition(0) {}
5297
5298AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5299 const sp<IMemory>& buffer, int64_t pts)
5300 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5301
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302// ----------------------------------------------------------------------------
5303
5304// RecordTrack constructor must be called with AudioFlinger::mLock held
5305AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005306 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307 const sp<Client>& client,
5308 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005309 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005310 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312 int sessionId)
5313 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005314 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315 mOverflow(false)
5316{
5317 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005318 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5319 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5320 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5321 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5322 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5323 } else {
5324 mCblk->frameSize = sizeof(int8_t);
5325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 }
5327}
5328
5329AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5330{
5331 sp<ThreadBase> thread = mThread.promote();
5332 if (thread != 0) {
5333 AudioSystem::releaseInput(thread->id());
5334 }
5335}
5336
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005337// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005338status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339{
5340 audio_track_cblk_t* cblk = this->cblk();
5341 uint32_t framesAvail;
5342 uint32_t framesReq = buffer->frameCount;
5343
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005344 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005345 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005347 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005348 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005349 }
5350
5351 framesAvail = cblk->framesAvailable_l();
5352
Glenn Kastenf6b16782011-12-15 09:51:17 -08005353 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 uint32_t s = cblk->server;
5355 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5356
5357 if (framesReq > framesAvail) {
5358 framesReq = framesAvail;
5359 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005360 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361 framesReq = bufferEnd - s;
5362 }
5363
5364 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005365 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366
5367 buffer->frameCount = framesReq;
5368 return NO_ERROR;
5369 }
5370
5371getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005372 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373 buffer->frameCount = 0;
5374 return NOT_ENOUGH_DATA;
5375}
5376
Glenn Kasten3acbd052012-02-28 10:39:56 -08005377status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005378 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379{
5380 sp<ThreadBase> thread = mThread.promote();
5381 if (thread != 0) {
5382 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005383 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 } else {
5385 return BAD_VALUE;
5386 }
5387}
5388
5389void AudioFlinger::RecordThread::RecordTrack::stop()
5390{
5391 sp<ThreadBase> thread = mThread.promote();
5392 if (thread != 0) {
5393 RecordThread *recordThread = (RecordThread *)thread.get();
5394 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005395 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005396 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005397 // read from buffer
5398 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 }
5400}
5401
5402void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5403{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005404 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005405 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005407 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 mSessionId,
5409 mFrameCount,
5410 mState,
5411 mCblk->sampleRate,
5412 mCblk->server,
5413 mCblk->user);
5414}
5415
5416
5417// ----------------------------------------------------------------------------
5418
5419AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005420 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 DuplicatingThread *sourceThread,
5422 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005423 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005424 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005426 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5427 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005428 mActive(false), mSourceThread(sourceThread)
5429{
5430
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 if (mCblk != NULL) {
5432 mCblk->flags |= CBLK_DIRECTION_OUT;
5433 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 mOutBuffer.frameCount = 0;
5435 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005436 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005437 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5438 mCblk, mBuffer, mCblk->buffers,
5439 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005441 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 }
5443}
5444
5445AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5446{
5447 clearBufferQueue();
5448}
5449
Glenn Kasten3acbd052012-02-28 10:39:56 -08005450status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005451 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005453 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 if (status != NO_ERROR) {
5455 return status;
5456 }
5457
5458 mActive = true;
5459 mRetryCount = 127;
5460 return status;
5461}
5462
5463void AudioFlinger::PlaybackThread::OutputTrack::stop()
5464{
5465 Track::stop();
5466 clearBufferQueue();
5467 mOutBuffer.frameCount = 0;
5468 mActive = false;
5469}
5470
5471bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5472{
5473 Buffer *pInBuffer;
5474 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005475 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 bool outputBufferFull = false;
5477 inBuffer.frameCount = frames;
5478 inBuffer.i16 = data;
5479
5480 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5481
5482 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005483 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 sp<ThreadBase> thread = mThread.promote();
5485 if (thread != 0) {
5486 MixerThread *mixerThread = (MixerThread *)thread.get();
5487 if (mCblk->frameCount > frames){
5488 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5489 uint32_t startFrames = (mCblk->frameCount - frames);
5490 pInBuffer = new Buffer;
5491 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5492 pInBuffer->frameCount = startFrames;
5493 pInBuffer->i16 = pInBuffer->mBuffer;
5494 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5495 mBufferQueue.add(pInBuffer);
5496 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005497 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498 }
5499 }
5500 }
5501 }
5502
5503 while (waitTimeLeftMs) {
5504 // First write pending buffers, then new data
5505 if (mBufferQueue.size()) {
5506 pInBuffer = mBufferQueue.itemAt(0);
5507 } else {
5508 pInBuffer = &inBuffer;
5509 }
5510
5511 if (pInBuffer->frameCount == 0) {
5512 break;
5513 }
5514
5515 if (mOutBuffer.frameCount == 0) {
5516 mOutBuffer.frameCount = pInBuffer->frameCount;
5517 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005518 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005519 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 outputBufferFull = true;
5521 break;
5522 }
5523 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5524 if (waitTimeLeftMs >= waitTimeMs) {
5525 waitTimeLeftMs -= waitTimeMs;
5526 } else {
5527 waitTimeLeftMs = 0;
5528 }
5529 }
5530
5531 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5532 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5533 mCblk->stepUser(outFrames);
5534 pInBuffer->frameCount -= outFrames;
5535 pInBuffer->i16 += outFrames * channelCount;
5536 mOutBuffer.frameCount -= outFrames;
5537 mOutBuffer.i16 += outFrames * channelCount;
5538
5539 if (pInBuffer->frameCount == 0) {
5540 if (mBufferQueue.size()) {
5541 mBufferQueue.removeAt(0);
5542 delete [] pInBuffer->mBuffer;
5543 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005544 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 } else {
5546 break;
5547 }
5548 }
5549 }
5550
5551 // If we could not write all frames, allocate a buffer and queue it for next time.
5552 if (inBuffer.frameCount) {
5553 sp<ThreadBase> thread = mThread.promote();
5554 if (thread != 0 && !thread->standby()) {
5555 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5556 pInBuffer = new Buffer;
5557 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5558 pInBuffer->frameCount = inBuffer.frameCount;
5559 pInBuffer->i16 = pInBuffer->mBuffer;
5560 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5561 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005562 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005564 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565 }
5566 }
5567 }
5568
5569 // Calling write() with a 0 length buffer, means that no more data will be written:
5570 // If no more buffers are pending, fill output track buffer to make sure it is started
5571 // by output mixer.
5572 if (frames == 0 && mBufferQueue.size() == 0) {
5573 if (mCblk->user < mCblk->frameCount) {
5574 frames = mCblk->frameCount - mCblk->user;
5575 pInBuffer = new Buffer;
5576 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5577 pInBuffer->frameCount = frames;
5578 pInBuffer->i16 = pInBuffer->mBuffer;
5579 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5580 mBufferQueue.add(pInBuffer);
5581 } else if (mActive) {
5582 stop();
5583 }
5584 }
5585
5586 return outputBufferFull;
5587}
5588
5589status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5590{
5591 int active;
5592 status_t result;
5593 audio_track_cblk_t* cblk = mCblk;
5594 uint32_t framesReq = buffer->frameCount;
5595
Steve Block3856b092011-10-20 11:56:00 +01005596// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 buffer->frameCount = 0;
5598
5599 uint32_t framesAvail = cblk->framesAvailable();
5600
5601
5602 if (framesAvail == 0) {
5603 Mutex::Autolock _l(cblk->lock);
5604 goto start_loop_here;
5605 while (framesAvail == 0) {
5606 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005607 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005608 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005609 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610 }
5611 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5612 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005613 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614 }
5615 // read the server count again
5616 start_loop_here:
5617 framesAvail = cblk->framesAvailable_l();
5618 }
5619 }
5620
5621// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005622// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623// }
5624
5625 if (framesReq > framesAvail) {
5626 framesReq = framesAvail;
5627 }
5628
5629 uint32_t u = cblk->user;
5630 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5631
Marco Nelissena1472d92012-03-30 14:36:54 -07005632 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 framesReq = bufferEnd - u;
5634 }
5635
5636 buffer->frameCount = framesReq;
5637 buffer->raw = (void *)cblk->buffer(u);
5638 return NO_ERROR;
5639}
5640
5641
5642void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5643{
5644 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645
5646 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005647 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005648 delete [] pBuffer->mBuffer;
5649 delete pBuffer;
5650 }
5651 mBufferQueue.clear();
5652}
5653
5654// ----------------------------------------------------------------------------
5655
5656AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5657 : RefBase(),
5658 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005659 // 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 -07005660 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005661 mPid(pid),
5662 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663{
5664 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5665}
5666
5667// Client destructor must be called with AudioFlinger::mLock held
5668AudioFlinger::Client::~Client()
5669{
5670 mAudioFlinger->removeClient_l(mPid);
5671}
5672
Glenn Kasten435dbe62012-01-30 10:15:48 -08005673sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674{
5675 return mMemoryDealer;
5676}
5677
John Grossman4ff14ba2012-02-08 16:37:41 -08005678// Reserve one of the limited slots for a timed audio track associated
5679// with this client
5680bool AudioFlinger::Client::reserveTimedTrack()
5681{
5682 const int kMaxTimedTracksPerClient = 4;
5683
5684 Mutex::Autolock _l(mTimedTrackLock);
5685
5686 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5687 ALOGW("can not create timed track - pid %d has exceeded the limit",
5688 mPid);
5689 return false;
5690 }
5691
5692 mTimedTrackCount++;
5693 return true;
5694}
5695
5696// Release a slot for a timed audio track
5697void AudioFlinger::Client::releaseTimedTrack()
5698{
5699 Mutex::Autolock _l(mTimedTrackLock);
5700 mTimedTrackCount--;
5701}
5702
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703// ----------------------------------------------------------------------------
5704
5705AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5706 const sp<IAudioFlingerClient>& client,
5707 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005708 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709{
5710}
5711
5712AudioFlinger::NotificationClient::~NotificationClient()
5713{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714}
5715
5716void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5717{
5718 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005719 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005720}
5721
5722// ----------------------------------------------------------------------------
5723
5724AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5725 : BnAudioTrack(),
5726 mTrack(track)
5727{
5728}
5729
5730AudioFlinger::TrackHandle::~TrackHandle() {
5731 // just stop the track on deletion, associated resources
5732 // will be freed from the main thread once all pending buffers have
5733 // been played. Unless it's not in the active track list, in which
5734 // case we free everything now...
5735 mTrack->destroy();
5736}
5737
Glenn Kasten90716c52012-01-26 13:40:12 -08005738sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5739 return mTrack->getCblk();
5740}
5741
Glenn Kasten3acbd052012-02-28 10:39:56 -08005742status_t AudioFlinger::TrackHandle::start() {
5743 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744}
5745
5746void AudioFlinger::TrackHandle::stop() {
5747 mTrack->stop();
5748}
5749
5750void AudioFlinger::TrackHandle::flush() {
5751 mTrack->flush();
5752}
5753
5754void AudioFlinger::TrackHandle::mute(bool e) {
5755 mTrack->mute(e);
5756}
5757
5758void AudioFlinger::TrackHandle::pause() {
5759 mTrack->pause();
5760}
5761
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5763{
5764 return mTrack->attachAuxEffect(EffectId);
5765}
5766
John Grossman4ff14ba2012-02-08 16:37:41 -08005767status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5768 sp<IMemory>* buffer) {
5769 if (!mTrack->isTimedTrack())
5770 return INVALID_OPERATION;
5771
5772 PlaybackThread::TimedTrack* tt =
5773 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5774 return tt->allocateTimedBuffer(size, buffer);
5775}
5776
5777status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5778 int64_t pts) {
5779 if (!mTrack->isTimedTrack())
5780 return INVALID_OPERATION;
5781
5782 PlaybackThread::TimedTrack* tt =
5783 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5784 return tt->queueTimedBuffer(buffer, pts);
5785}
5786
5787status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5788 const LinearTransform& xform, int target) {
5789
5790 if (!mTrack->isTimedTrack())
5791 return INVALID_OPERATION;
5792
5793 PlaybackThread::TimedTrack* tt =
5794 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5795 return tt->setMediaTimeTransform(
5796 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5797}
5798
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799status_t AudioFlinger::TrackHandle::onTransact(
5800 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5801{
5802 return BnAudioTrack::onTransact(code, data, reply, flags);
5803}
5804
5805// ----------------------------------------------------------------------------
5806
5807sp<IAudioRecord> AudioFlinger::openRecord(
5808 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005809 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005811 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005812 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005814 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815 int *sessionId,
5816 status_t *status)
5817{
5818 sp<RecordThread::RecordTrack> recordTrack;
5819 sp<RecordHandle> recordHandle;
5820 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 status_t lStatus;
5822 RecordThread *thread;
5823 size_t inFrameCount;
5824 int lSessionId;
5825
5826 // check calling permissions
5827 if (!recordingAllowed()) {
5828 lStatus = PERMISSION_DENIED;
5829 goto Exit;
5830 }
5831
5832 // add client to list
5833 { // scope for mLock
5834 Mutex::Autolock _l(mLock);
5835 thread = checkRecordThread_l(input);
5836 if (thread == NULL) {
5837 lStatus = BAD_VALUE;
5838 goto Exit;
5839 }
5840
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005841 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842
5843 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005844 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845 lSessionId = *sessionId;
5846 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005847 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848 if (sessionId != NULL) {
5849 *sessionId = lSessionId;
5850 }
5851 }
5852 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005853 recordTrack = thread->createRecordTrack_l(client,
5854 sampleRate,
5855 format,
5856 channelMask,
5857 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005858 lSessionId,
5859 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005861 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5863 // destructor is called by the TrackBase destructor with mLock held
5864 client.clear();
5865 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866 goto Exit;
5867 }
5868
5869 // return to handle to client
5870 recordHandle = new RecordHandle(recordTrack);
5871 lStatus = NO_ERROR;
5872
5873Exit:
5874 if (status) {
5875 *status = lStatus;
5876 }
5877 return recordHandle;
5878}
5879
5880// ----------------------------------------------------------------------------
5881
5882AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5883 : BnAudioRecord(),
5884 mRecordTrack(recordTrack)
5885{
5886}
5887
5888AudioFlinger::RecordHandle::~RecordHandle() {
5889 stop();
5890}
5891
Glenn Kasten90716c52012-01-26 13:40:12 -08005892sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5893 return mRecordTrack->getCblk();
5894}
5895
Glenn Kasten3acbd052012-02-28 10:39:56 -08005896status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005897 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005898 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899}
5900
5901void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005902 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 mRecordTrack->stop();
5904}
5905
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906status_t AudioFlinger::RecordHandle::onTransact(
5907 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5908{
5909 return BnAudioRecord::onTransact(code, data, reply, flags);
5910}
5911
5912// ----------------------------------------------------------------------------
5913
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005914AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5915 AudioStreamIn *input,
5916 uint32_t sampleRate,
5917 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005918 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005919 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005920 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005921 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5922 // mRsmpInIndex and mInputBytes set by readInputParameters()
5923 mReqChannelCount(popcount(channels)),
5924 mReqSampleRate(sampleRate)
5925 // mBytesRead is only meaningful while active, and so is cleared in start()
5926 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927{
Glenn Kasten480b4682012-02-28 12:30:08 -08005928 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005929
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 readInputParameters();
5931}
5932
5933
5934AudioFlinger::RecordThread::~RecordThread()
5935{
5936 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005937 delete mResampler;
5938 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939}
5940
5941void AudioFlinger::RecordThread::onFirstRef()
5942{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005943 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944}
5945
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005946status_t AudioFlinger::RecordThread::readyToRun()
5947{
5948 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005949 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005950 return status;
5951}
5952
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953bool AudioFlinger::RecordThread::threadLoop()
5954{
5955 AudioBufferProvider::Buffer buffer;
5956 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005957 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958
Eric Laurent44d98482010-09-30 16:12:31 -07005959 nsecs_t lastWarning = 0;
5960
Eric Laurentfeb0db62011-07-22 09:04:31 -07005961 acquireWakeLock();
5962
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 // start recording
5964 while (!exitPending()) {
5965
5966 processConfigEvents();
5967
5968 { // scope for mLock
5969 Mutex::Autolock _l(mLock);
5970 checkForNewParameters_l();
5971 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5972 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005973 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 mStandby = true;
5975 }
5976
5977 if (exitPending()) break;
5978
Eric Laurentfeb0db62011-07-22 09:04:31 -07005979 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005980 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 // go to sleep
5982 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005983 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005984 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 continue;
5986 }
5987 if (mActiveTrack != 0) {
5988 if (mActiveTrack->mState == TrackBase::PAUSING) {
5989 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005990 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 mStandby = true;
5992 }
5993 mActiveTrack.clear();
5994 mStartStopCond.broadcast();
5995 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5996 if (mReqChannelCount != mActiveTrack->channelCount()) {
5997 mActiveTrack.clear();
5998 mStartStopCond.broadcast();
5999 } else if (mBytesRead != 0) {
6000 // record start succeeds only if first read from audio input
6001 // succeeds
6002 if (mBytesRead > 0) {
6003 mActiveTrack->mState = TrackBase::ACTIVE;
6004 } else {
6005 mActiveTrack.clear();
6006 }
6007 mStartStopCond.broadcast();
6008 }
6009 mStandby = false;
6010 }
6011 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006012 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 }
6014
6015 if (mActiveTrack != 0) {
6016 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6017 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006018 unlockEffectChains(effectChains);
6019 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020 continue;
6021 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006022 for (size_t i = 0; i < effectChains.size(); i ++) {
6023 effectChains[i]->process_l();
6024 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006025
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006027 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006029 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 // no resampling
6031 while (framesOut) {
6032 size_t framesIn = mFrameCount - mRsmpInIndex;
6033 if (framesIn) {
6034 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6035 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6036 if (framesIn > framesOut)
6037 framesIn = framesOut;
6038 mRsmpInIndex += framesIn;
6039 framesOut -= framesIn;
6040 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006041 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 memcpy(dst, src, framesIn * mFrameSize);
6043 } else {
6044 int16_t *src16 = (int16_t *)src;
6045 int16_t *dst16 = (int16_t *)dst;
6046 if (mChannelCount == 1) {
6047 while (framesIn--) {
6048 *dst16++ = *src16;
6049 *dst16++ = *src16++;
6050 }
6051 } else {
6052 while (framesIn--) {
6053 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6054 src16 += 2;
6055 }
6056 }
6057 }
6058 }
6059 if (framesOut && mFrameCount == mRsmpInIndex) {
6060 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006061 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006062 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 framesOut = 0;
6064 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006065 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066 mRsmpInIndex = 0;
6067 }
6068 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006069 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6071 // Force input into standby so that it tries to
6072 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006073 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006074 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 }
6076 mRsmpInIndex = mFrameCount;
6077 framesOut = 0;
6078 buffer.frameCount = 0;
6079 }
6080 }
6081 }
6082 } else {
6083 // resampling
6084
6085 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6086 // alter output frame count as if we were expecting stereo samples
6087 if (mChannelCount == 1 && mReqChannelCount == 1) {
6088 framesOut >>= 1;
6089 }
6090 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6091 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6092 // are 32 bit aligned which should be always true.
6093 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006094 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095 // the resampler always outputs stereo samples: do post stereo to mono conversion
6096 int16_t *src = (int16_t *)mRsmpOutBuffer;
6097 int16_t *dst = buffer.i16;
6098 while (framesOut--) {
6099 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6100 src += 2;
6101 }
6102 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006103 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104 }
6105
6106 }
Eric Laurenta011e352012-03-29 15:51:43 -07006107 if (mFramestoDrop == 0) {
6108 mActiveTrack->releaseBuffer(&buffer);
6109 } else {
6110 if (mFramestoDrop > 0) {
6111 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006112 if (mFramestoDrop <= 0) {
6113 clearSyncStartEvent();
6114 }
6115 } else {
6116 mFramestoDrop += buffer.frameCount;
6117 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6118 mSyncStartEvent->isCancelled()) {
6119 ALOGW("Synced record %s, session %d, trigger session %d",
6120 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6121 mActiveTrack->sessionId(),
6122 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6123 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006124 }
6125 }
6126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 mActiveTrack->overflow();
6128 }
6129 // client isn't retrieving buffers fast enough
6130 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006131 if (!mActiveTrack->setOverflow()) {
6132 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006133 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006134 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006135 lastWarning = now;
6136 }
6137 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138 // Release the processor for a while before asking for a new buffer.
6139 // This will give the application more chance to read from the buffer and
6140 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006141 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142 }
6143 }
Eric Laurentec437d82011-07-26 20:54:46 -07006144 // enable changes in effect chain
6145 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006146 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147 }
6148
6149 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006150 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151 }
6152 mActiveTrack.clear();
6153
6154 mStartStopCond.broadcast();
6155
Eric Laurentfeb0db62011-07-22 09:04:31 -07006156 releaseWakeLock();
6157
Steve Block3856b092011-10-20 11:56:00 +01006158 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159 return false;
6160}
6161
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006162
6163sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6164 const sp<AudioFlinger::Client>& client,
6165 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006166 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006167 int channelMask,
6168 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006169 int sessionId,
6170 status_t *status)
6171{
6172 sp<RecordTrack> track;
6173 status_t lStatus;
6174
6175 lStatus = initCheck();
6176 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006177 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006178 goto Exit;
6179 }
6180
6181 { // scope for mLock
6182 Mutex::Autolock _l(mLock);
6183
6184 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006185 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186
Glenn Kasten7378ca52012-01-20 13:44:40 -08006187 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006188 lStatus = NO_MEMORY;
6189 goto Exit;
6190 }
6191
6192 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006193 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6194 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006195 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006196 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6197 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006198 }
6199 lStatus = NO_ERROR;
6200
6201Exit:
6202 if (status) {
6203 *status = lStatus;
6204 }
6205 return track;
6206}
6207
Eric Laurenta011e352012-03-29 15:51:43 -07006208status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006209 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006210 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211{
Glenn Kasten58912562012-04-03 10:45:00 -07006212 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006213 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006215
6216 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006217 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006218 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6219 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6220 triggerSession,
6221 recordTrack->sessionId(),
6222 syncStartEventCallback,
6223 this);
Eric Laurent29864602012-05-08 18:57:51 -07006224 // Sync event can be cancelled by the trigger session if the track is not in a
6225 // compatible state in which case we start record immediately
6226 if (mSyncStartEvent->isCancelled()) {
6227 clearSyncStartEvent();
6228 } else {
6229 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6230 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6231 }
Eric Laurenta011e352012-03-29 15:51:43 -07006232 }
6233
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006235 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236 if (mActiveTrack != 0) {
6237 if (recordTrack != mActiveTrack.get()) {
6238 status = -EBUSY;
6239 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6240 mActiveTrack->mState = TrackBase::ACTIVE;
6241 }
6242 return status;
6243 }
6244
6245 recordTrack->mState = TrackBase::IDLE;
6246 mActiveTrack = recordTrack;
6247 mLock.unlock();
6248 status_t status = AudioSystem::startInput(mId);
6249 mLock.lock();
6250 if (status != NO_ERROR) {
6251 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006252 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 return status;
6254 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 mRsmpInIndex = mFrameCount;
6256 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006257 if (mResampler != NULL) {
6258 mResampler->reset();
6259 }
6260 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006262 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263 mWaitWorkCV.signal();
6264 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006265 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 mActiveTrack.clear();
6267 status = INVALID_OPERATION;
6268 goto startError;
6269 }
6270 mStartStopCond.wait(mLock);
6271 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006272 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 status = BAD_VALUE;
6274 goto startError;
6275 }
Steve Block3856b092011-10-20 11:56:00 +01006276 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 return status;
6278 }
6279startError:
6280 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006281 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 return status;
6283}
6284
Eric Laurenta011e352012-03-29 15:51:43 -07006285void AudioFlinger::RecordThread::clearSyncStartEvent()
6286{
6287 if (mSyncStartEvent != 0) {
6288 mSyncStartEvent->cancel();
6289 }
6290 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006291 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006292}
6293
6294void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6295{
6296 sp<SyncEvent> strongEvent = event.promote();
6297
6298 if (strongEvent != 0) {
6299 RecordThread *me = (RecordThread *)strongEvent->cookie();
6300 me->handleSyncStartEvent(strongEvent);
6301 }
6302}
6303
6304void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6305{
Eric Laurent29864602012-05-08 18:57:51 -07006306 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006307 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6308 // from audio HAL
6309 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006310 }
6311}
6312
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006314 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006315 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006317 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6319 mActiveTrack->mState = TrackBase::PAUSING;
6320 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006321 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006322 return;
6323 }
6324 mStartStopCond.wait(mLock);
6325 // if we have been restarted, recordTrack == mActiveTrack.get() here
6326 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6327 mLock.unlock();
6328 AudioSystem::stopInput(mId);
6329 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006330 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331 }
6332 }
6333 }
6334}
6335
Eric Laurenta011e352012-03-29 15:51:43 -07006336bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6337{
6338 return false;
6339}
6340
6341status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6342{
6343 if (!isValidSyncEvent(event)) {
6344 return BAD_VALUE;
6345 }
6346
6347 Mutex::Autolock _l(mLock);
6348
6349 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6350 mTrack->setSyncEvent(event);
6351 return NO_ERROR;
6352 }
6353 return NAME_NOT_FOUND;
6354}
6355
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6357{
6358 const size_t SIZE = 256;
6359 char buffer[SIZE];
6360 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361
6362 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6363 result.append(buffer);
6364
6365 if (mActiveTrack != 0) {
6366 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006367 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 mActiveTrack->dump(buffer, SIZE);
6369 result.append(buffer);
6370
6371 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6372 result.append(buffer);
6373 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6374 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006375 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 result.append(buffer);
6377 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6378 result.append(buffer);
6379 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6380 result.append(buffer);
6381
6382
6383 } else {
6384 result.append("No record client\n");
6385 }
6386 write(fd, result.string(), result.size());
6387
6388 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006389 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390
6391 return NO_ERROR;
6392}
6393
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006394// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006395status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396{
6397 size_t framesReq = buffer->frameCount;
6398 size_t framesReady = mFrameCount - mRsmpInIndex;
6399 int channelCount;
6400
6401 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006402 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006404 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6406 // Force input into standby so that it tries to
6407 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006408 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006409 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006411 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006412 buffer->frameCount = 0;
6413 return NOT_ENOUGH_DATA;
6414 }
6415 mRsmpInIndex = 0;
6416 framesReady = mFrameCount;
6417 }
6418
6419 if (framesReq > framesReady) {
6420 framesReq = framesReady;
6421 }
6422
6423 if (mChannelCount == 1 && mReqChannelCount == 2) {
6424 channelCount = 1;
6425 } else {
6426 channelCount = 2;
6427 }
6428 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6429 buffer->frameCount = framesReq;
6430 return NO_ERROR;
6431}
6432
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006433// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006434void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6435{
6436 mRsmpInIndex += buffer->frameCount;
6437 buffer->frameCount = 0;
6438}
6439
6440bool AudioFlinger::RecordThread::checkForNewParameters_l()
6441{
6442 bool reconfig = false;
6443
6444 while (!mNewParameters.isEmpty()) {
6445 status_t status = NO_ERROR;
6446 String8 keyValuePair = mNewParameters[0];
6447 AudioParameter param = AudioParameter(keyValuePair);
6448 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006449 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450 int reqSamplingRate = mReqSampleRate;
6451 int reqChannelCount = mReqChannelCount;
6452
6453 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6454 reqSamplingRate = value;
6455 reconfig = true;
6456 }
6457 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006458 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459 reconfig = true;
6460 }
6461 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006462 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463 reconfig = true;
6464 }
6465 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6466 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006467 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 // if frame count is changed after track creation
6469 if (mActiveTrack != 0) {
6470 status = INVALID_OPERATION;
6471 } else {
6472 reconfig = true;
6473 }
6474 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006475 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6476 // forward device change to effects that have requested to be
6477 // aware of attached audio device.
6478 for (size_t i = 0; i < mEffectChains.size(); i++) {
6479 mEffectChains[i]->setDevice_l(value);
6480 }
6481 // store input device and output device but do not forward output device to audio HAL.
6482 // Note that status is ignored by the caller for output device
6483 // (see AudioFlinger::setParameters()
6484 if (value & AUDIO_DEVICE_OUT_ALL) {
6485 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6486 status = BAD_VALUE;
6487 } else {
6488 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006489 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6490 if (mTrack != NULL) {
6491 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006492 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006493 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6494 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6495 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006496 }
6497 mDevice |= (uint32_t)value;
6498 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006500 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006502 mInput->stream->common.standby(&mInput->stream->common);
6503 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6504 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 }
6506 if (reconfig) {
6507 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006508 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006509 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006510 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006511 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6512 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513 status = NO_ERROR;
6514 }
6515 if (status == NO_ERROR) {
6516 readInputParameters();
6517 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6518 }
6519 }
6520 }
6521
6522 mNewParameters.removeAt(0);
6523
6524 mParamStatus = status;
6525 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006526 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6527 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006528 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006529 }
6530 return reconfig;
6531}
6532
6533String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6534{
Dima Zavinfce7a472011-04-19 22:30:36 -07006535 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006536 String8 out_s8 = String8();
6537
6538 Mutex::Autolock _l(mLock);
6539 if (initCheck() != NO_ERROR) {
6540 return out_s8;
6541 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006542
Dima Zavin799a70e2011-04-18 16:57:27 -07006543 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006544 out_s8 = String8(s);
6545 free(s);
6546 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547}
6548
6549void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6550 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006551 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552
6553 switch (event) {
6554 case AudioSystem::INPUT_OPENED:
6555 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006556 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 desc.samplingRate = mSampleRate;
6558 desc.format = mFormat;
6559 desc.frameCount = mFrameCount;
6560 desc.latency = 0;
6561 param2 = &desc;
6562 break;
6563
6564 case AudioSystem::INPUT_CLOSED:
6565 default:
6566 break;
6567 }
6568 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6569}
6570
6571void AudioFlinger::RecordThread::readInputParameters()
6572{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006573 delete mRsmpInBuffer;
6574 // mRsmpInBuffer is always assigned a new[] below
6575 delete mRsmpOutBuffer;
6576 mRsmpOutBuffer = NULL;
6577 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006578 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579
Dima Zavin799a70e2011-04-18 16:57:27 -07006580 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006581 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6582 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006583 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006584 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006585 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006587 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6589
Glenn Kasten53d76db2012-03-08 12:32:47 -08006590 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 {
6592 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006593 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6594 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595 if (mChannelCount == 1 && mReqChannelCount == 2) {
6596 channelCount = 1;
6597 } else {
6598 channelCount = 2;
6599 }
6600 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6601 mResampler->setSampleRate(mSampleRate);
6602 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6603 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6604
6605 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6606 if (mChannelCount == 1 && mReqChannelCount == 1) {
6607 mFrameCount >>= 1;
6608 }
6609
6610 }
6611 mRsmpInIndex = mFrameCount;
6612}
6613
6614unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6615{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006616 Mutex::Autolock _l(mLock);
6617 if (initCheck() != NO_ERROR) {
6618 return 0;
6619 }
6620
Dima Zavin799a70e2011-04-18 16:57:27 -07006621 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622}
6623
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006624uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6625{
6626 Mutex::Autolock _l(mLock);
6627 uint32_t result = 0;
6628 if (getEffectChain_l(sessionId) != 0) {
6629 result = EFFECT_SESSION;
6630 }
6631
6632 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6633 result |= TRACK_SESSION;
6634 }
6635
6636 return result;
6637}
6638
Eric Laurent59bd0da2011-08-01 09:52:20 -07006639AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6640{
6641 Mutex::Autolock _l(mLock);
6642 return mTrack;
6643}
6644
Glenn Kastenaed850d2012-01-26 09:46:34 -08006645AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006646{
6647 Mutex::Autolock _l(mLock);
6648 return mInput;
6649}
6650
6651AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6652{
6653 Mutex::Autolock _l(mLock);
6654 AudioStreamIn *input = mInput;
6655 mInput = NULL;
6656 return input;
6657}
6658
6659// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006660audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006661{
6662 if (mInput == NULL) {
6663 return NULL;
6664 }
6665 return &mInput->stream->common;
6666}
6667
6668
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669// ----------------------------------------------------------------------------
6670
Eric Laurenta4c5a552012-03-29 10:12:40 -07006671audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6672{
6673 if (!settingsAllowed()) {
6674 return 0;
6675 }
6676 Mutex::Autolock _l(mLock);
6677 return loadHwModule_l(name);
6678}
6679
6680// loadHwModule_l() must be called with AudioFlinger::mLock held
6681audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6682{
6683 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6684 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6685 ALOGW("loadHwModule() module %s already loaded", name);
6686 return mAudioHwDevs.keyAt(i);
6687 }
6688 }
6689
Eric Laurenta4c5a552012-03-29 10:12:40 -07006690 audio_hw_device_t *dev;
6691
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006692 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006693 if (rc) {
6694 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6695 return 0;
6696 }
6697
6698 mHardwareStatus = AUDIO_HW_INIT;
6699 rc = dev->init_check(dev);
6700 mHardwareStatus = AUDIO_HW_IDLE;
6701 if (rc) {
6702 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6703 return 0;
6704 }
6705
6706 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6707 (NULL != dev->set_master_volume)) {
6708 AutoMutex lock(mHardwareLock);
6709 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6710 dev->set_master_volume(dev, mMasterVolume);
6711 mHardwareStatus = AUDIO_HW_IDLE;
6712 }
6713
6714 audio_module_handle_t handle = nextUniqueId();
6715 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6716
6717 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006718 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006719
6720 return handle;
6721
6722}
6723
6724audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6725 audio_devices_t *pDevices,
6726 uint32_t *pSamplingRate,
6727 audio_format_t *pFormat,
6728 audio_channel_mask_t *pChannelMask,
6729 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006730 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731{
6732 status_t status;
6733 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006734 struct audio_config config = {
6735 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6736 channel_mask: pChannelMask ? *pChannelMask : 0,
6737 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6738 };
6739 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006740 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741
Eric Laurenta4c5a552012-03-29 10:12:40 -07006742 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6743 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006744 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006745 config.sample_rate,
6746 config.format,
6747 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006748 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749
6750 if (pDevices == NULL || *pDevices == 0) {
6751 return 0;
6752 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006753
Mathias Agopian65ab4712010-07-14 17:59:35 -07006754 Mutex::Autolock _l(mLock);
6755
Eric Laurenta4c5a552012-03-29 10:12:40 -07006756 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006757 if (outHwDev == NULL)
6758 return 0;
6759
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006760 audio_io_handle_t id = nextUniqueId();
6761
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006762 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006763
6764 status = outHwDev->open_output_stream(outHwDev,
6765 id,
6766 *pDevices,
6767 (audio_output_flags_t)flags,
6768 &config,
6769 &outStream);
6770
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006771 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006772 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006773 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006774 config.sample_rate,
6775 config.format,
6776 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777 status);
6778
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006779 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006780 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006781
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006782 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006783 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6784 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006786 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787 } else {
6788 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006789 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 }
6791 mPlaybackThreads.add(id, thread);
6792
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006793 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6794 if (pFormat != NULL) *pFormat = config.format;
6795 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006796 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797
6798 // notify client processes of the new output creation
6799 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006800
6801 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006802 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006803 ALOGI("Using module %d has the primary audio interface", module);
6804 mPrimaryHardwareDev = outHwDev;
6805
6806 AutoMutex lock(mHardwareLock);
6807 mHardwareStatus = AUDIO_HW_SET_MODE;
6808 outHwDev->set_mode(outHwDev, mMode);
6809
6810 // Determine the level of master volume support the primary audio HAL has,
6811 // and set the initial master volume at the same time.
6812 float initialVolume = 1.0;
6813 mMasterVolumeSupportLvl = MVS_NONE;
6814
6815 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6816 if ((NULL != outHwDev->get_master_volume) &&
6817 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6818 mMasterVolumeSupportLvl = MVS_FULL;
6819 } else {
6820 mMasterVolumeSupportLvl = MVS_SETONLY;
6821 initialVolume = 1.0;
6822 }
6823
6824 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6825 if ((NULL == outHwDev->set_master_volume) ||
6826 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6827 mMasterVolumeSupportLvl = MVS_NONE;
6828 }
6829 // now that we have a primary device, initialize master volume on other devices
6830 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6831 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6832
6833 if ((dev != mPrimaryHardwareDev) &&
6834 (NULL != dev->set_master_volume)) {
6835 dev->set_master_volume(dev, initialVolume);
6836 }
6837 }
6838 mHardwareStatus = AUDIO_HW_IDLE;
6839 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6840 ? initialVolume
6841 : 1.0;
6842 mMasterVolume = initialVolume;
6843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844 return id;
6845 }
6846
6847 return 0;
6848}
6849
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006850audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6851 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852{
6853 Mutex::Autolock _l(mLock);
6854 MixerThread *thread1 = checkMixerThread_l(output1);
6855 MixerThread *thread2 = checkMixerThread_l(output2);
6856
6857 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006858 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859 return 0;
6860 }
6861
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006862 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6864 thread->addOutputTrack(thread2);
6865 mPlaybackThreads.add(id, thread);
6866 // notify client processes of the new output creation
6867 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6868 return id;
6869}
6870
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006871status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872{
6873 // keep strong reference on the playback thread so that
6874 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006875 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876 {
6877 Mutex::Autolock _l(mLock);
6878 thread = checkPlaybackThread_l(output);
6879 if (thread == NULL) {
6880 return BAD_VALUE;
6881 }
6882
Steve Block3856b092011-10-20 11:56:00 +01006883 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006885 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006887 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6889 dupThread->removeOutputTrack((MixerThread *)thread.get());
6890 }
6891 }
6892 }
Glenn Kastena1117922012-01-26 10:53:32 -08006893 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 mPlaybackThreads.removeItem(output);
6895 }
6896 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006897 // The thread entity (active unit of execution) is no longer running here,
6898 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006900 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006901 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006902 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006903 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006904 out->hwDev->close_output_stream(out->hwDev, out->stream);
6905 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 }
6907 return NO_ERROR;
6908}
6909
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006910status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911{
6912 Mutex::Autolock _l(mLock);
6913 PlaybackThread *thread = checkPlaybackThread_l(output);
6914
6915 if (thread == NULL) {
6916 return BAD_VALUE;
6917 }
6918
Steve Block3856b092011-10-20 11:56:00 +01006919 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920 thread->suspend();
6921
6922 return NO_ERROR;
6923}
6924
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006925status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926{
6927 Mutex::Autolock _l(mLock);
6928 PlaybackThread *thread = checkPlaybackThread_l(output);
6929
6930 if (thread == NULL) {
6931 return BAD_VALUE;
6932 }
6933
Steve Block3856b092011-10-20 11:56:00 +01006934 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935
6936 thread->restore();
6937
6938 return NO_ERROR;
6939}
6940
Eric Laurenta4c5a552012-03-29 10:12:40 -07006941audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6942 audio_devices_t *pDevices,
6943 uint32_t *pSamplingRate,
6944 audio_format_t *pFormat,
6945 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946{
6947 status_t status;
6948 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006949 struct audio_config config = {
6950 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6951 channel_mask: pChannelMask ? *pChannelMask : 0,
6952 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6953 };
6954 uint32_t reqSamplingRate = config.sample_rate;
6955 audio_format_t reqFormat = config.format;
6956 audio_channel_mask_t reqChannels = config.channel_mask;
6957 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006958 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959
6960 if (pDevices == NULL || *pDevices == 0) {
6961 return 0;
6962 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006963
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 Mutex::Autolock _l(mLock);
6965
Eric Laurenta4c5a552012-03-29 10:12:40 -07006966 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006967 if (inHwDev == NULL)
6968 return 0;
6969
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006970 audio_io_handle_t id = nextUniqueId();
6971
6972 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006973 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006974 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006975 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006976 config.sample_rate,
6977 config.format,
6978 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 status);
6980
6981 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6982 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6983 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006984 if (status == BAD_VALUE &&
6985 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6986 (config.sample_rate <= 2 * reqSamplingRate) &&
6987 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006988 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006989 inStream = NULL;
6990 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991 }
6992
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006993 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006994 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6995
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006996 // Start record thread
6997 // RecorThread require both input and output device indication to forward to audio
6998 // pre processing modules
6999 uint32_t device = (*pDevices) | primaryOutputDevice_l();
7000 thread = new RecordThread(this,
7001 input,
7002 reqSamplingRate,
7003 reqChannels,
7004 id,
7005 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007007 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007008 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007009 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007010 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011
Dima Zavin799a70e2011-04-18 16:57:27 -07007012 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013
7014 // notify client processes of the new input creation
7015 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7016 return id;
7017 }
7018
7019 return 0;
7020}
7021
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007022status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023{
7024 // keep strong reference on the record thread so that
7025 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007026 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 {
7028 Mutex::Autolock _l(mLock);
7029 thread = checkRecordThread_l(input);
7030 if (thread == NULL) {
7031 return BAD_VALUE;
7032 }
7033
Steve Block3856b092011-10-20 11:56:00 +01007034 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007035 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036 mRecordThreads.removeItem(input);
7037 }
7038 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007039 // The thread entity (active unit of execution) is no longer running here,
7040 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007042 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007043 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007044 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007045 in->hwDev->close_input_stream(in->hwDev, in->stream);
7046 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047
7048 return NO_ERROR;
7049}
7050
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007051status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052{
7053 Mutex::Autolock _l(mLock);
7054 MixerThread *dstThread = checkMixerThread_l(output);
7055 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007056 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 return BAD_VALUE;
7058 }
7059
Steve Block3856b092011-10-20 11:56:00 +01007060 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
7062
7063 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7064 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08007065 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066 MixerThread *srcThread = (MixerThread *)thread;
7067 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 }
Eric Laurentde070132010-07-13 04:45:46 -07007069 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070
7071 return NO_ERROR;
7072}
7073
7074
7075int AudioFlinger::newAudioSessionId()
7076{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007077 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078}
7079
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007080void AudioFlinger::acquireAudioSessionId(int audioSession)
7081{
7082 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007083 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007084 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007085 size_t num = mAudioSessionRefs.size();
7086 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007087 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007088 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7089 ref->mCnt++;
7090 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007091 return;
7092 }
7093 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007094 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7095 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007096}
7097
7098void AudioFlinger::releaseAudioSessionId(int audioSession)
7099{
7100 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007101 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007102 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007103 size_t num = mAudioSessionRefs.size();
7104 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007105 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007106 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7107 ref->mCnt--;
7108 ALOGV(" decremented refcount to %d", ref->mCnt);
7109 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007110 mAudioSessionRefs.removeAt(i);
7111 delete ref;
7112 purgeStaleEffects_l();
7113 }
7114 return;
7115 }
7116 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007117 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007118}
7119
7120void AudioFlinger::purgeStaleEffects_l() {
7121
Steve Block3856b092011-10-20 11:56:00 +01007122 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007123
7124 Vector< sp<EffectChain> > chains;
7125
7126 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7127 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7128 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7129 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007130 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7131 chains.push(ec);
7132 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007133 }
7134 }
7135 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7136 sp<RecordThread> t = mRecordThreads.valueAt(i);
7137 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7138 sp<EffectChain> ec = t->mEffectChains[j];
7139 chains.push(ec);
7140 }
7141 }
7142
7143 for (size_t i = 0; i < chains.size(); i++) {
7144 sp<EffectChain> ec = chains[i];
7145 int sessionid = ec->sessionId();
7146 sp<ThreadBase> t = ec->mThread.promote();
7147 if (t == 0) {
7148 continue;
7149 }
7150 size_t numsessionrefs = mAudioSessionRefs.size();
7151 bool found = false;
7152 for (size_t k = 0; k < numsessionrefs; k++) {
7153 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007154 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007155 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007156 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007157 found = true;
7158 break;
7159 }
7160 }
7161 if (!found) {
7162 // remove all effects from the chain
7163 while (ec->mEffects.size()) {
7164 sp<EffectModule> effect = ec->mEffects[0];
7165 effect->unPin();
7166 Mutex::Autolock _l (t->mLock);
7167 t->removeEffect_l(effect);
7168 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7169 sp<EffectHandle> handle = effect->mHandles[j].promote();
7170 if (handle != 0) {
7171 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007172 if (handle->mHasControl && handle->mEnabled) {
7173 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7174 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007175 }
7176 }
7177 AudioSystem::unregisterEffect(effect->id());
7178 }
7179 }
7180 }
7181 return;
7182}
7183
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007185AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007186{
Glenn Kastena1117922012-01-26 10:53:32 -08007187 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188}
7189
7190// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007191AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007192{
7193 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007194 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195}
7196
7197// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007198AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199{
Glenn Kastena1117922012-01-26 10:53:32 -08007200 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201}
7202
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007203uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007205 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206}
7207
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007208AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007209{
7210 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7211 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007212 AudioStreamOut *output = thread->getOutput();
7213 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007214 return thread;
7215 }
7216 }
7217 return NULL;
7218}
7219
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007220uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007221{
7222 PlaybackThread *thread = primaryPlaybackThread_l();
7223
7224 if (thread == NULL) {
7225 return 0;
7226 }
7227
7228 return thread->device();
7229}
7230
Eric Laurenta011e352012-03-29 15:51:43 -07007231sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7232 int triggerSession,
7233 int listenerSession,
7234 sync_event_callback_t callBack,
7235 void *cookie)
7236{
7237 Mutex::Autolock _l(mLock);
7238
7239 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7240 status_t playStatus = NAME_NOT_FOUND;
7241 status_t recStatus = NAME_NOT_FOUND;
7242 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7243 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7244 if (playStatus == NO_ERROR) {
7245 return event;
7246 }
7247 }
7248 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7249 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7250 if (recStatus == NO_ERROR) {
7251 return event;
7252 }
7253 }
7254 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7255 mPendingSyncEvents.add(event);
7256 } else {
7257 ALOGV("createSyncEvent() invalid event %d", event->type());
7258 event.clear();
7259 }
7260 return event;
7261}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007262
Mathias Agopian65ab4712010-07-14 17:59:35 -07007263// ----------------------------------------------------------------------------
7264// Effect management
7265// ----------------------------------------------------------------------------
7266
7267
Glenn Kastenf587ba52012-01-26 16:25:10 -08007268status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007269{
7270 Mutex::Autolock _l(mLock);
7271 return EffectQueryNumberEffects(numEffects);
7272}
7273
Glenn Kastenf587ba52012-01-26 16:25:10 -08007274status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275{
7276 Mutex::Autolock _l(mLock);
7277 return EffectQueryEffect(index, descriptor);
7278}
7279
Glenn Kasten5e92a782012-01-30 07:40:52 -08007280status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007281 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282{
7283 Mutex::Autolock _l(mLock);
7284 return EffectGetDescriptor(pUuid, descriptor);
7285}
7286
7287
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7289 effect_descriptor_t *pDesc,
7290 const sp<IEffectClient>& effectClient,
7291 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007292 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293 int sessionId,
7294 status_t *status,
7295 int *id,
7296 int *enabled)
7297{
7298 status_t lStatus = NO_ERROR;
7299 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007302 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007303 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304
7305 if (pDesc == NULL) {
7306 lStatus = BAD_VALUE;
7307 goto Exit;
7308 }
7309
Eric Laurent84e9a102010-09-23 16:10:16 -07007310 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007311 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007312 lStatus = PERMISSION_DENIED;
7313 goto Exit;
7314 }
7315
Dima Zavinfce7a472011-04-19 22:30:36 -07007316 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007317 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007318 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007319 lStatus = PERMISSION_DENIED;
7320 goto Exit;
7321 }
7322
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007323 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007324 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007325 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007326 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007327 lStatus = BAD_VALUE;
7328 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007329 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007330 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007331 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007332 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007333 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007334 }
7335 }
7336
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 {
7338 Mutex::Autolock _l(mLock);
7339
Mathias Agopian65ab4712010-07-14 17:59:35 -07007340
7341 if (!EffectIsNullUuid(&pDesc->uuid)) {
7342 // if uuid is specified, request effect descriptor
7343 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7344 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007345 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 goto Exit;
7347 }
7348 } else {
7349 // if uuid is not specified, look for an available implementation
7350 // of the required type in effect factory
7351 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007352 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353 lStatus = BAD_VALUE;
7354 goto Exit;
7355 }
7356 uint32_t numEffects = 0;
7357 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007358 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359 bool found = false;
7360
7361 lStatus = EffectQueryNumberEffects(&numEffects);
7362 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007363 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 goto Exit;
7365 }
7366 for (uint32_t i = 0; i < numEffects; i++) {
7367 lStatus = EffectQueryEffect(i, &desc);
7368 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007369 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 continue;
7371 }
7372 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7373 // If matching type found save effect descriptor. If the session is
7374 // 0 and the effect is not auxiliary, continue enumeration in case
7375 // an auxiliary version of this effect type is available
7376 found = true;
7377 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007378 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7380 break;
7381 }
7382 }
7383 }
7384 if (!found) {
7385 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007386 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 goto Exit;
7388 }
7389 // For same effect type, chose auxiliary version over insert version if
7390 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007391 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7393 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7394 }
7395 }
7396
7397 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007398 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7400 lStatus = INVALID_OPERATION;
7401 goto Exit;
7402 }
7403
Eric Laurent59255e42011-07-27 19:49:51 -07007404 // check recording permission for visualizer
7405 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7406 !recordingAllowed()) {
7407 lStatus = PERMISSION_DENIED;
7408 goto Exit;
7409 }
7410
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 // return effect descriptor
7412 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7413
7414 // If output is not specified try to find a matching audio session ID in one of the
7415 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007416 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7417 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007418 // Note: io is never 0 when creating an effect on an input
7419 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007420 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007421 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7422 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007423 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007424 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007427 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007428 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7429 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7430 io = mRecordThreads.keyAt(i);
7431 break;
7432 }
7433 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007434 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007435 // If no output thread contains the requested session ID, default to
7436 // first output. The effect chain will be moved to the correct output
7437 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007438 if (io == 0 && mPlaybackThreads.size()) {
7439 io = mPlaybackThreads.keyAt(0);
7440 }
Steve Block3856b092011-10-20 11:56:00 +01007441 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007442 }
7443 ThreadBase *thread = checkRecordThread_l(io);
7444 if (thread == NULL) {
7445 thread = checkPlaybackThread_l(io);
7446 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007447 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007448 lStatus = BAD_VALUE;
7449 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007450 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007452
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007453 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007454
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007455 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007456 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7457 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007458 if (handle != 0 && id != NULL) {
7459 *id = handle->id();
7460 }
7461 }
7462
7463Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007464 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465 *status = lStatus;
7466 }
7467 return handle;
7468}
7469
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007470status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7471 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007472{
Steve Block3856b092011-10-20 11:56:00 +01007473 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007474 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007475 Mutex::Autolock _l(mLock);
7476 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007477 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007478 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479 }
Eric Laurentde070132010-07-13 04:45:46 -07007480 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7481 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007482 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007483 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484 }
Eric Laurentde070132010-07-13 04:45:46 -07007485 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7486 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007487 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007488 return BAD_VALUE;
7489 }
7490
7491 Mutex::Autolock _dl(dstThread->mLock);
7492 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007493 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007494
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 return NO_ERROR;
7496}
7497
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007498// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007499status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007500 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007501 AudioFlinger::PlaybackThread *dstThread,
7502 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007503{
Steve Block3856b092011-10-20 11:56:00 +01007504 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007505 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007506
Eric Laurent59255e42011-07-27 19:49:51 -07007507 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007508 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007509 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007510 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007511 return INVALID_OPERATION;
7512 }
7513
Eric Laurent39e94f82010-07-28 01:32:47 -07007514 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007515 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007516 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007517 // removed.
7518 srcThread->removeEffectChain_l(chain);
7519
7520 // transfer all effects one by one so that new effect chain is created on new thread with
7521 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007522 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007523 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007524 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007525 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7526 while (effect != 0) {
7527 srcThread->removeEffect_l(effect);
7528 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007529 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7530 if (effect->state() == EffectModule::ACTIVE ||
7531 effect->state() == EffectModule::STOPPING) {
7532 effect->start();
7533 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007534 // if the move request is not received from audio policy manager, the effect must be
7535 // re-registered with the new strategy and output
7536 if (dstChain == 0) {
7537 dstChain = effect->chain().promote();
7538 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007539 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007540 srcThread->addEffect_l(effect);
7541 return NO_INIT;
7542 }
7543 strategy = dstChain->strategy();
7544 }
7545 if (reRegister) {
7546 AudioSystem::unregisterEffect(effect->id());
7547 AudioSystem::registerEffect(&effect->desc(),
7548 dstOutput,
7549 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007550 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007551 effect->id());
7552 }
Eric Laurentde070132010-07-13 04:45:46 -07007553 effect = chain->getEffectFromId_l(0);
7554 }
7555
7556 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007557}
7558
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007559
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007561sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007562 const sp<AudioFlinger::Client>& client,
7563 const sp<IEffectClient>& effectClient,
7564 int32_t priority,
7565 int sessionId,
7566 effect_descriptor_t *desc,
7567 int *enabled,
7568 status_t *status
7569 )
7570{
7571 sp<EffectModule> effect;
7572 sp<EffectHandle> handle;
7573 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007575 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007576 bool effectCreated = false;
7577 bool effectRegistered = false;
7578
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007579 lStatus = initCheck();
7580 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007581 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582 goto Exit;
7583 }
7584
7585 // Do not allow effects with session ID 0 on direct output or duplicating threads
7586 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007587 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007588 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007589 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 lStatus = BAD_VALUE;
7591 goto Exit;
7592 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007593 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007594 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007595 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007596 desc->name, desc->flags, mType);
7597 lStatus = BAD_VALUE;
7598 goto Exit;
7599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600
Steve Block3856b092011-10-20 11:56:00 +01007601 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602
7603 { // scope for mLock
7604 Mutex::Autolock _l(mLock);
7605
7606 // check for existing effect chain with the requested audio session
7607 chain = getEffectChain_l(sessionId);
7608 if (chain == 0) {
7609 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007610 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611 chain = new EffectChain(this, sessionId);
7612 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007613 chain->setStrategy(getStrategyForSession_l(sessionId));
7614 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007616 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007617 }
7618
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007619 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620
7621 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007622 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007624 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625 if (lStatus != NO_ERROR) {
7626 goto Exit;
7627 }
7628 effectRegistered = true;
7629 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007630 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631 lStatus = effect->status();
7632 if (lStatus != NO_ERROR) {
7633 goto Exit;
7634 }
Eric Laurentcab11242010-07-15 12:50:15 -07007635 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007636 if (lStatus != NO_ERROR) {
7637 goto Exit;
7638 }
7639 effectCreated = true;
7640
7641 effect->setDevice(mDevice);
7642 effect->setMode(mAudioFlinger->getMode());
7643 }
7644 // create effect handle and connect it to effect module
7645 handle = new EffectHandle(effect, client, effectClient, priority);
7646 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007647 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007648 *enabled = (int)effect->isEnabled();
7649 }
7650 }
7651
7652Exit:
7653 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007654 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007655 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007656 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007657 }
7658 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007659 AudioSystem::unregisterEffect(effect->id());
7660 }
7661 if (chainCreated) {
7662 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 }
7664 handle.clear();
7665 }
7666
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007667 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007668 *status = lStatus;
7669 }
7670 return handle;
7671}
7672
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007673sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7674{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007675 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007676 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007677}
7678
Eric Laurentde070132010-07-13 04:45:46 -07007679// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7680// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007681status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007682{
7683 // check for existing effect chain with the requested audio session
7684 int sessionId = effect->sessionId();
7685 sp<EffectChain> chain = getEffectChain_l(sessionId);
7686 bool chainCreated = false;
7687
7688 if (chain == 0) {
7689 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007690 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007691 chain = new EffectChain(this, sessionId);
7692 addEffectChain_l(chain);
7693 chain->setStrategy(getStrategyForSession_l(sessionId));
7694 chainCreated = true;
7695 }
Steve Block3856b092011-10-20 11:56:00 +01007696 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007697
7698 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007699 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007700 this, effect->desc().name, chain.get());
7701 return BAD_VALUE;
7702 }
7703
7704 status_t status = chain->addEffect_l(effect);
7705 if (status != NO_ERROR) {
7706 if (chainCreated) {
7707 removeEffectChain_l(chain);
7708 }
7709 return status;
7710 }
7711
7712 effect->setDevice(mDevice);
7713 effect->setMode(mAudioFlinger->getMode());
7714 return NO_ERROR;
7715}
7716
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007717void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007718
Steve Block3856b092011-10-20 11:56:00 +01007719 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007720 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007721 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7722 detachAuxEffect_l(effect->id());
7723 }
7724
7725 sp<EffectChain> chain = effect->chain().promote();
7726 if (chain != 0) {
7727 // remove effect chain if removing last effect
7728 if (chain->removeEffect_l(effect) == 0) {
7729 removeEffectChain_l(chain);
7730 }
7731 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007732 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007733 }
7734}
7735
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007736void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007737 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007738{
7739 effectChains = mEffectChains;
7740 for (size_t i = 0; i < mEffectChains.size(); i++) {
7741 mEffectChains[i]->lock();
7742 }
7743}
7744
7745void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007746 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007747{
7748 for (size_t i = 0; i < effectChains.size(); i++) {
7749 effectChains[i]->unlock();
7750 }
7751}
7752
7753sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7754{
7755 Mutex::Autolock _l(mLock);
7756 return getEffectChain_l(sessionId);
7757}
7758
7759sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7760{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007761 size_t size = mEffectChains.size();
7762 for (size_t i = 0; i < size; i++) {
7763 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007764 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007765 }
7766 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007767 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007768}
7769
Glenn Kastenf78aee72012-01-04 11:00:47 -08007770void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007771{
7772 Mutex::Autolock _l(mLock);
7773 size_t size = mEffectChains.size();
7774 for (size_t i = 0; i < size; i++) {
7775 mEffectChains[i]->setMode_l(mode);
7776 }
7777}
7778
7779void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007780 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007781 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007782
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007784 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785 // delete the effect module if removing last handle on it
7786 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007787 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007788 removeEffect_l(effect);
7789 AudioSystem::unregisterEffect(effect->id());
7790 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 }
7792}
7793
7794status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7795{
7796 int session = chain->sessionId();
7797 int16_t *buffer = mMixBuffer;
7798 bool ownsBuffer = false;
7799
Steve Block3856b092011-10-20 11:56:00 +01007800 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007801 if (session > 0) {
7802 // Only one effect chain can be present in direct output thread and it uses
7803 // the mix buffer as input
7804 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007805 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 buffer = new int16_t[numSamples];
7807 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007808 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809 ownsBuffer = true;
7810 }
7811
7812 // Attach all tracks with same session ID to this chain.
7813 for (size_t i = 0; i < mTracks.size(); ++i) {
7814 sp<Track> track = mTracks[i];
7815 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007816 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007817 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007818 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819 }
7820 }
7821
7822 // indicate all active tracks in the chain
7823 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7824 sp<Track> track = mActiveTracks[i].promote();
7825 if (track == 0) continue;
7826 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007827 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007828 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829 }
7830 }
7831 }
7832
7833 chain->setInBuffer(buffer, ownsBuffer);
7834 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007835 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007836 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007837 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7838 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007840 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7841 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007842 // Effect chain for other sessions are inserted at beginning of effect
7843 // chains list to be processed before output mix effects. Relative order between other
7844 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845 size_t size = mEffectChains.size();
7846 size_t i = 0;
7847 for (i = 0; i < size; i++) {
7848 if (mEffectChains[i]->sessionId() < session) break;
7849 }
7850 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007851 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852
7853 return NO_ERROR;
7854}
7855
7856size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7857{
7858 int session = chain->sessionId();
7859
Steve Block3856b092011-10-20 11:56:00 +01007860 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861
7862 for (size_t i = 0; i < mEffectChains.size(); i++) {
7863 if (chain == mEffectChains[i]) {
7864 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007865 // detach all active tracks from the chain
7866 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7867 sp<Track> track = mActiveTracks[i].promote();
7868 if (track == 0) continue;
7869 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007870 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007871 chain.get(), session);
7872 chain->decActiveTrackCnt();
7873 }
7874 }
7875
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 // detach all tracks with same session ID from this chain
7877 for (size_t i = 0; i < mTracks.size(); ++i) {
7878 sp<Track> track = mTracks[i];
7879 if (session == track->sessionId()) {
7880 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007881 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882 }
7883 }
Eric Laurentde070132010-07-13 04:45:46 -07007884 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 }
7886 }
7887 return mEffectChains.size();
7888}
7889
Eric Laurentde070132010-07-13 04:45:46 -07007890status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7891 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892{
7893 Mutex::Autolock _l(mLock);
7894 return attachAuxEffect_l(track, EffectId);
7895}
7896
Eric Laurentde070132010-07-13 04:45:46 -07007897status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7898 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899{
7900 status_t status = NO_ERROR;
7901
7902 if (EffectId == 0) {
7903 track->setAuxBuffer(0, NULL);
7904 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007905 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7906 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907 if (effect != 0) {
7908 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7909 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7910 } else {
7911 status = INVALID_OPERATION;
7912 }
7913 } else {
7914 status = BAD_VALUE;
7915 }
7916 }
7917 return status;
7918}
7919
7920void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7921{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007922 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007923 sp<Track> track = mTracks[i];
7924 if (track->auxEffectId() == effectId) {
7925 attachAuxEffect_l(track, 0);
7926 }
7927 }
7928}
7929
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007930status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7931{
7932 // only one chain per input thread
7933 if (mEffectChains.size() != 0) {
7934 return INVALID_OPERATION;
7935 }
Steve Block3856b092011-10-20 11:56:00 +01007936 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007937
7938 chain->setInBuffer(NULL);
7939 chain->setOutBuffer(NULL);
7940
Eric Laurent59255e42011-07-27 19:49:51 -07007941 checkSuspendOnAddEffectChain_l(chain);
7942
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007943 mEffectChains.add(chain);
7944
7945 return NO_ERROR;
7946}
7947
7948size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7949{
Steve Block3856b092011-10-20 11:56:00 +01007950 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007951 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007952 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7953 chain.get(), mEffectChains.size(), this);
7954 if (mEffectChains.size() == 1) {
7955 mEffectChains.removeAt(0);
7956 }
7957 return 0;
7958}
7959
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960// ----------------------------------------------------------------------------
7961// EffectModule implementation
7962// ----------------------------------------------------------------------------
7963
7964#undef LOG_TAG
7965#define LOG_TAG "AudioFlinger::EffectModule"
7966
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007967AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968 const wp<AudioFlinger::EffectChain>& chain,
7969 effect_descriptor_t *desc,
7970 int id,
7971 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007972 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007973 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007974{
Steve Block3856b092011-10-20 11:56:00 +01007975 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007977 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007978 return;
7979 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980
7981 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7982
7983 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007984 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007985
7986 if (mStatus != NO_ERROR) {
7987 return;
7988 }
7989 lStatus = init();
7990 if (lStatus < 0) {
7991 mStatus = lStatus;
7992 goto Error;
7993 }
7994
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007995 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7996 mPinned = true;
7997 }
Steve Block3856b092011-10-20 11:56:00 +01007998 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007999 return;
8000Error:
8001 EffectRelease(mEffectInterface);
8002 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008003 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008004}
8005
8006AudioFlinger::EffectModule::~EffectModule()
8007{
Steve Block3856b092011-10-20 11:56:00 +01008008 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008010 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8011 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8012 sp<ThreadBase> thread = mThread.promote();
8013 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008014 audio_stream_t *stream = thread->stream();
8015 if (stream != NULL) {
8016 stream->remove_audio_effect(stream, mEffectInterface);
8017 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008018 }
8019 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008020 // release effect engine
8021 EffectRelease(mEffectInterface);
8022 }
8023}
8024
Glenn Kasten435dbe62012-01-30 10:15:48 -08008025status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026{
8027 status_t status;
8028
8029 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008030 int priority = handle->priority();
8031 size_t size = mHandles.size();
8032 sp<EffectHandle> h;
8033 size_t i;
8034 for (i = 0; i < size; i++) {
8035 h = mHandles[i].promote();
8036 if (h == 0) continue;
8037 if (h->priority() <= priority) break;
8038 }
8039 // if inserted in first place, move effect control from previous owner to this handle
8040 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008041 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008043 enabled = h->enabled();
8044 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045 }
Eric Laurent59255e42011-07-27 19:49:51 -07008046 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008047 status = NO_ERROR;
8048 } else {
8049 status = ALREADY_EXISTS;
8050 }
Steve Block3856b092011-10-20 11:56:00 +01008051 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008052 mHandles.insertAt(handle, i);
8053 return status;
8054}
8055
8056size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
8057{
8058 Mutex::Autolock _l(mLock);
8059 size_t size = mHandles.size();
8060 size_t i;
8061 for (i = 0; i < size; i++) {
8062 if (mHandles[i] == handle) break;
8063 }
8064 if (i == size) {
8065 return size;
8066 }
Steve Block3856b092011-10-20 11:56:00 +01008067 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07008068
8069 bool enabled = false;
8070 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08008071 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01008072 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07008073 enabled = hdl->enabled();
8074 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075 mHandles.removeAt(i);
8076 size = mHandles.size();
8077 // if removed from first place, move effect control from this handle to next in line
8078 if (i == 0 && size != 0) {
8079 sp<EffectHandle> h = mHandles[0].promote();
8080 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008081 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082 }
8083 }
8084
Eric Laurentec437d82011-07-26 20:54:46 -07008085 // Prevent calls to process() and other functions on effect interface from now on.
8086 // The effect engine will be released by the destructor when the last strong reference on
8087 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008088 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008089 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008090 }
8091
Mathias Agopian65ab4712010-07-14 17:59:35 -07008092 return size;
8093}
8094
Eric Laurent59255e42011-07-27 19:49:51 -07008095sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8096{
8097 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08008098 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008099}
8100
Glenn Kasten58123c32012-02-03 10:32:24 -08008101void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102{
Glenn Kasten90bebef2012-01-27 15:24:38 -08008103 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104 // keep a strong reference on this EffectModule to avoid calling the
8105 // destructor before we exit
8106 sp<EffectModule> keep(this);
8107 {
8108 sp<ThreadBase> thread = mThread.promote();
8109 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008110 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008111 }
8112 }
8113}
8114
8115void AudioFlinger::EffectModule::updateState() {
8116 Mutex::Autolock _l(mLock);
8117
8118 switch (mState) {
8119 case RESTART:
8120 reset_l();
8121 // FALL THROUGH
8122
8123 case STARTING:
8124 // clear auxiliary effect input buffer for next accumulation
8125 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8126 memset(mConfig.inputCfg.buffer.raw,
8127 0,
8128 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8129 }
8130 start_l();
8131 mState = ACTIVE;
8132 break;
8133 case STOPPING:
8134 stop_l();
8135 mDisableWaitCnt = mMaxDisableWaitCnt;
8136 mState = STOPPED;
8137 break;
8138 case STOPPED:
8139 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8140 // turn off sequence.
8141 if (--mDisableWaitCnt == 0) {
8142 reset_l();
8143 mState = IDLE;
8144 }
8145 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008146 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008147 break;
8148 }
8149}
8150
8151void AudioFlinger::EffectModule::process()
8152{
8153 Mutex::Autolock _l(mLock);
8154
Eric Laurentec437d82011-07-26 20:54:46 -07008155 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 mConfig.inputCfg.buffer.raw == NULL ||
8157 mConfig.outputCfg.buffer.raw == NULL) {
8158 return;
8159 }
8160
Eric Laurent8f45bd72010-08-31 13:50:07 -07008161 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8163 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008164 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008165 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008166 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167 }
8168
8169 // do the actual processing in the effect engine
8170 int ret = (*mEffectInterface)->process(mEffectInterface,
8171 &mConfig.inputCfg.buffer,
8172 &mConfig.outputCfg.buffer);
8173
8174 // force transition to IDLE state when engine is ready
8175 if (mState == STOPPED && ret == -ENODATA) {
8176 mDisableWaitCnt = 1;
8177 }
8178
8179 // clear auxiliary effect input buffer for next accumulation
8180 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008181 memset(mConfig.inputCfg.buffer.raw, 0,
8182 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008183 }
8184 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008185 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8186 // If an insert effect is idle and input buffer is different from output buffer,
8187 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008189 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008190 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8191 int16_t *in = mConfig.inputCfg.buffer.s16;
8192 int16_t *out = mConfig.outputCfg.buffer.s16;
8193 for (size_t i = 0; i < frameCnt; i++) {
8194 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196 }
8197 }
8198}
8199
8200void AudioFlinger::EffectModule::reset_l()
8201{
8202 if (mEffectInterface == NULL) {
8203 return;
8204 }
8205 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8206}
8207
8208status_t AudioFlinger::EffectModule::configure()
8209{
8210 uint32_t channels;
8211 if (mEffectInterface == NULL) {
8212 return NO_INIT;
8213 }
8214
8215 sp<ThreadBase> thread = mThread.promote();
8216 if (thread == 0) {
8217 return DEAD_OBJECT;
8218 }
8219
8220 // TODO: handle configuration of effects replacing track process
8221 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008222 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008223 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008224 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008225 }
8226
8227 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008228 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008229 } else {
8230 mConfig.inputCfg.channels = channels;
8231 }
8232 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008233 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8234 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235 mConfig.inputCfg.samplingRate = thread->sampleRate();
8236 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8237 mConfig.inputCfg.bufferProvider.cookie = NULL;
8238 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8239 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8240 mConfig.outputCfg.bufferProvider.cookie = NULL;
8241 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8242 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8243 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8244 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008245 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008246 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008247 // - in other sessions:
8248 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8249 // other effect: overwrites output buffer: input buffer == output buffer
8250 // Auxiliary effect:
8251 // accumulates in output buffer: input buffer != output buffer
8252 // Therefore: accumulate <=> input buffer != output buffer
8253 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8254 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8255 } else {
8256 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8257 }
8258 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8259 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8260 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8261 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8262
Steve Block3856b092011-10-20 11:56:00 +01008263 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008264 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8265
Mathias Agopian65ab4712010-07-14 17:59:35 -07008266 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008267 uint32_t size = sizeof(int);
8268 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008269 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008270 sizeof(effect_config_t),
8271 &mConfig,
8272 &size,
8273 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008274 if (status == 0) {
8275 status = cmdStatus;
8276 }
8277
8278 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8279 (1000 * mConfig.outputCfg.buffer.frameCount);
8280
8281 return status;
8282}
8283
8284status_t AudioFlinger::EffectModule::init()
8285{
8286 Mutex::Autolock _l(mLock);
8287 if (mEffectInterface == NULL) {
8288 return NO_INIT;
8289 }
8290 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008291 uint32_t size = sizeof(status_t);
8292 status_t status = (*mEffectInterface)->command(mEffectInterface,
8293 EFFECT_CMD_INIT,
8294 0,
8295 NULL,
8296 &size,
8297 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008298 if (status == 0) {
8299 status = cmdStatus;
8300 }
8301 return status;
8302}
8303
Eric Laurentec35a142011-10-05 17:42:25 -07008304status_t AudioFlinger::EffectModule::start()
8305{
8306 Mutex::Autolock _l(mLock);
8307 return start_l();
8308}
8309
Mathias Agopian65ab4712010-07-14 17:59:35 -07008310status_t AudioFlinger::EffectModule::start_l()
8311{
8312 if (mEffectInterface == NULL) {
8313 return NO_INIT;
8314 }
8315 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008316 uint32_t size = sizeof(status_t);
8317 status_t status = (*mEffectInterface)->command(mEffectInterface,
8318 EFFECT_CMD_ENABLE,
8319 0,
8320 NULL,
8321 &size,
8322 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008323 if (status == 0) {
8324 status = cmdStatus;
8325 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008326 if (status == 0 &&
8327 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8328 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8329 sp<ThreadBase> thread = mThread.promote();
8330 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008331 audio_stream_t *stream = thread->stream();
8332 if (stream != NULL) {
8333 stream->add_audio_effect(stream, mEffectInterface);
8334 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008335 }
8336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008337 return status;
8338}
8339
Eric Laurentec437d82011-07-26 20:54:46 -07008340status_t AudioFlinger::EffectModule::stop()
8341{
8342 Mutex::Autolock _l(mLock);
8343 return stop_l();
8344}
8345
Mathias Agopian65ab4712010-07-14 17:59:35 -07008346status_t AudioFlinger::EffectModule::stop_l()
8347{
8348 if (mEffectInterface == NULL) {
8349 return NO_INIT;
8350 }
8351 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008352 uint32_t size = sizeof(status_t);
8353 status_t status = (*mEffectInterface)->command(mEffectInterface,
8354 EFFECT_CMD_DISABLE,
8355 0,
8356 NULL,
8357 &size,
8358 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 if (status == 0) {
8360 status = cmdStatus;
8361 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008362 if (status == 0 &&
8363 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8364 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8365 sp<ThreadBase> thread = mThread.promote();
8366 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008367 audio_stream_t *stream = thread->stream();
8368 if (stream != NULL) {
8369 stream->remove_audio_effect(stream, mEffectInterface);
8370 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008371 }
8372 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008373 return status;
8374}
8375
Eric Laurent25f43952010-07-28 05:40:18 -07008376status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8377 uint32_t cmdSize,
8378 void *pCmdData,
8379 uint32_t *replySize,
8380 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008381{
8382 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008383// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008384
Eric Laurentec437d82011-07-26 20:54:46 -07008385 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008386 return NO_INIT;
8387 }
Eric Laurent25f43952010-07-28 05:40:18 -07008388 status_t status = (*mEffectInterface)->command(mEffectInterface,
8389 cmdCode,
8390 cmdSize,
8391 pCmdData,
8392 replySize,
8393 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008395 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396 for (size_t i = 1; i < mHandles.size(); i++) {
8397 sp<EffectHandle> h = mHandles[i].promote();
8398 if (h != 0) {
8399 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8400 }
8401 }
8402 }
8403 return status;
8404}
8405
8406status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8407{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008408
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008410 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008411
8412 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008413 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8414 if (enabled && status != NO_ERROR) {
8415 return status;
8416 }
8417
Mathias Agopian65ab4712010-07-14 17:59:35 -07008418 switch (mState) {
8419 // going from disabled to enabled
8420 case IDLE:
8421 mState = STARTING;
8422 break;
8423 case STOPPED:
8424 mState = RESTART;
8425 break;
8426 case STOPPING:
8427 mState = ACTIVE;
8428 break;
8429
8430 // going from enabled to disabled
8431 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008432 mState = STOPPED;
8433 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008434 case STARTING:
8435 mState = IDLE;
8436 break;
8437 case ACTIVE:
8438 mState = STOPPING;
8439 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008440 case DESTROYED:
8441 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008442 }
8443 for (size_t i = 1; i < mHandles.size(); i++) {
8444 sp<EffectHandle> h = mHandles[i].promote();
8445 if (h != 0) {
8446 h->setEnabled(enabled);
8447 }
8448 }
8449 }
8450 return NO_ERROR;
8451}
8452
Glenn Kastenc59c0042012-02-02 14:06:11 -08008453bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454{
8455 switch (mState) {
8456 case RESTART:
8457 case STARTING:
8458 case ACTIVE:
8459 return true;
8460 case IDLE:
8461 case STOPPING:
8462 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008463 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008464 default:
8465 return false;
8466 }
8467}
8468
Glenn Kastenc59c0042012-02-02 14:06:11 -08008469bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008470{
8471 switch (mState) {
8472 case RESTART:
8473 case ACTIVE:
8474 case STOPPING:
8475 case STOPPED:
8476 return true;
8477 case IDLE:
8478 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008479 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008480 default:
8481 return false;
8482 }
8483}
8484
Mathias Agopian65ab4712010-07-14 17:59:35 -07008485status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8486{
8487 Mutex::Autolock _l(mLock);
8488 status_t status = NO_ERROR;
8489
8490 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8491 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008492 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008493 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8494 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495 status_t cmdStatus;
8496 uint32_t volume[2];
8497 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008498 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008499 volume[0] = *left;
8500 volume[1] = *right;
8501 if (controller) {
8502 pVolume = volume;
8503 }
Eric Laurent25f43952010-07-28 05:40:18 -07008504 status = (*mEffectInterface)->command(mEffectInterface,
8505 EFFECT_CMD_SET_VOLUME,
8506 size,
8507 volume,
8508 &size,
8509 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008510 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8511 *left = volume[0];
8512 *right = volume[1];
8513 }
8514 }
8515 return status;
8516}
8517
8518status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8519{
8520 Mutex::Autolock _l(mLock);
8521 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008522 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8523 // audio pre processing modules on RecordThread can receive both output and
8524 // input device indication in the same call
8525 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8526 if (dev) {
8527 status_t cmdStatus;
8528 uint32_t size = sizeof(status_t);
8529
8530 status = (*mEffectInterface)->command(mEffectInterface,
8531 EFFECT_CMD_SET_DEVICE,
8532 sizeof(uint32_t),
8533 &dev,
8534 &size,
8535 &cmdStatus);
8536 if (status == NO_ERROR) {
8537 status = cmdStatus;
8538 }
8539 }
8540 dev = device & AUDIO_DEVICE_IN_ALL;
8541 if (dev) {
8542 status_t cmdStatus;
8543 uint32_t size = sizeof(status_t);
8544
8545 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8546 EFFECT_CMD_SET_INPUT_DEVICE,
8547 sizeof(uint32_t),
8548 &dev,
8549 &size,
8550 &cmdStatus);
8551 if (status2 == NO_ERROR) {
8552 status2 = cmdStatus;
8553 }
8554 if (status == NO_ERROR) {
8555 status = status2;
8556 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557 }
8558 }
8559 return status;
8560}
8561
Glenn Kastenf78aee72012-01-04 11:00:47 -08008562status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008563{
8564 Mutex::Autolock _l(mLock);
8565 status_t status = NO_ERROR;
8566 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008567 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008568 uint32_t size = sizeof(status_t);
8569 status = (*mEffectInterface)->command(mEffectInterface,
8570 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008571 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008572 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008573 &size,
8574 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575 if (status == NO_ERROR) {
8576 status = cmdStatus;
8577 }
8578 }
8579 return status;
8580}
8581
Eric Laurent59255e42011-07-27 19:49:51 -07008582void AudioFlinger::EffectModule::setSuspended(bool suspended)
8583{
8584 Mutex::Autolock _l(mLock);
8585 mSuspended = suspended;
8586}
Glenn Kastena3a85482012-01-04 11:01:11 -08008587
8588bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008589{
8590 Mutex::Autolock _l(mLock);
8591 return mSuspended;
8592}
8593
Mathias Agopian65ab4712010-07-14 17:59:35 -07008594status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8595{
8596 const size_t SIZE = 256;
8597 char buffer[SIZE];
8598 String8 result;
8599
8600 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8601 result.append(buffer);
8602
8603 bool locked = tryLock(mLock);
8604 // failed to lock - AudioFlinger is probably deadlocked
8605 if (!locked) {
8606 result.append("\t\tCould not lock Fx mutex:\n");
8607 }
8608
8609 result.append("\t\tSession Status State Engine:\n");
8610 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8611 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8612 result.append(buffer);
8613
8614 result.append("\t\tDescriptor:\n");
8615 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8616 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8617 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8618 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8619 result.append(buffer);
8620 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8621 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8622 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8623 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8624 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008625 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008626 mDescriptor.apiVersion,
8627 mDescriptor.flags);
8628 result.append(buffer);
8629 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8630 mDescriptor.name);
8631 result.append(buffer);
8632 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8633 mDescriptor.implementor);
8634 result.append(buffer);
8635
8636 result.append("\t\t- Input configuration:\n");
8637 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8638 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8639 (uint32_t)mConfig.inputCfg.buffer.raw,
8640 mConfig.inputCfg.buffer.frameCount,
8641 mConfig.inputCfg.samplingRate,
8642 mConfig.inputCfg.channels,
8643 mConfig.inputCfg.format);
8644 result.append(buffer);
8645
8646 result.append("\t\t- Output configuration:\n");
8647 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8648 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8649 (uint32_t)mConfig.outputCfg.buffer.raw,
8650 mConfig.outputCfg.buffer.frameCount,
8651 mConfig.outputCfg.samplingRate,
8652 mConfig.outputCfg.channels,
8653 mConfig.outputCfg.format);
8654 result.append(buffer);
8655
8656 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8657 result.append(buffer);
8658 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8659 for (size_t i = 0; i < mHandles.size(); ++i) {
8660 sp<EffectHandle> handle = mHandles[i].promote();
8661 if (handle != 0) {
8662 handle->dump(buffer, SIZE);
8663 result.append(buffer);
8664 }
8665 }
8666
8667 result.append("\n");
8668
8669 write(fd, result.string(), result.length());
8670
8671 if (locked) {
8672 mLock.unlock();
8673 }
8674
8675 return NO_ERROR;
8676}
8677
8678// ----------------------------------------------------------------------------
8679// EffectHandle implementation
8680// ----------------------------------------------------------------------------
8681
8682#undef LOG_TAG
8683#define LOG_TAG "AudioFlinger::EffectHandle"
8684
8685AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8686 const sp<AudioFlinger::Client>& client,
8687 const sp<IEffectClient>& effectClient,
8688 int32_t priority)
8689 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008690 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008691 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008692{
Steve Block3856b092011-10-20 11:56:00 +01008693 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008694
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008695 if (client == 0) {
8696 return;
8697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008698 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8699 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8700 if (mCblkMemory != 0) {
8701 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8702
Glenn Kastena0d68332012-01-27 16:47:15 -08008703 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008704 new(mCblk) effect_param_cblk_t();
8705 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008708 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008709 return;
8710 }
8711}
8712
8713AudioFlinger::EffectHandle::~EffectHandle()
8714{
Steve Block3856b092011-10-20 11:56:00 +01008715 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008716 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008717 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008718}
8719
8720status_t AudioFlinger::EffectHandle::enable()
8721{
Steve Block3856b092011-10-20 11:56:00 +01008722 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008723 if (!mHasControl) return INVALID_OPERATION;
8724 if (mEffect == 0) return DEAD_OBJECT;
8725
Eric Laurentdb7c0792011-08-10 10:37:50 -07008726 if (mEnabled) {
8727 return NO_ERROR;
8728 }
8729
Eric Laurent59255e42011-07-27 19:49:51 -07008730 mEnabled = true;
8731
8732 sp<ThreadBase> thread = mEffect->thread().promote();
8733 if (thread != 0) {
8734 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8735 }
8736
8737 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8738 if (mEffect->suspended()) {
8739 return NO_ERROR;
8740 }
8741
Eric Laurentdb7c0792011-08-10 10:37:50 -07008742 status_t status = mEffect->setEnabled(true);
8743 if (status != NO_ERROR) {
8744 if (thread != 0) {
8745 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8746 }
8747 mEnabled = false;
8748 }
8749 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008750}
8751
8752status_t AudioFlinger::EffectHandle::disable()
8753{
Steve Block3856b092011-10-20 11:56:00 +01008754 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008756 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757
Eric Laurentdb7c0792011-08-10 10:37:50 -07008758 if (!mEnabled) {
8759 return NO_ERROR;
8760 }
Eric Laurent59255e42011-07-27 19:49:51 -07008761 mEnabled = false;
8762
8763 if (mEffect->suspended()) {
8764 return NO_ERROR;
8765 }
8766
8767 status_t status = mEffect->setEnabled(false);
8768
8769 sp<ThreadBase> thread = mEffect->thread().promote();
8770 if (thread != 0) {
8771 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8772 }
8773
8774 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008775}
8776
8777void AudioFlinger::EffectHandle::disconnect()
8778{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008779 disconnect(true);
8780}
8781
Glenn Kasten58123c32012-02-03 10:32:24 -08008782void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008783{
Glenn Kasten58123c32012-02-03 10:32:24 -08008784 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008785 if (mEffect == 0) {
8786 return;
8787 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008788 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008789
Eric Laurenta85a74a2011-10-19 11:44:54 -07008790 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008791 sp<ThreadBase> thread = mEffect->thread().promote();
8792 if (thread != 0) {
8793 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8794 }
Eric Laurent59255e42011-07-27 19:49:51 -07008795 }
8796
Mathias Agopian65ab4712010-07-14 17:59:35 -07008797 // release sp on module => module destructor can be called now
8798 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008799 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008800 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008801 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008802 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8803 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008804 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008805 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008806 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8807 mClient.clear();
8808 }
8809}
8810
Eric Laurent25f43952010-07-28 05:40:18 -07008811status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8812 uint32_t cmdSize,
8813 void *pCmdData,
8814 uint32_t *replySize,
8815 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008816{
Steve Block3856b092011-10-20 11:56:00 +01008817// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008818// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008819
8820 // only get parameter command is permitted for applications not controlling the effect
8821 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8822 return INVALID_OPERATION;
8823 }
8824 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008825 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826
8827 // handle commands that are not forwarded transparently to effect engine
8828 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8829 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8830 // no risk to block the whole media server process or mixer threads is we are stuck here
8831 Mutex::Autolock _l(mCblk->lock);
8832 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8833 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8834 mCblk->serverIndex = 0;
8835 mCblk->clientIndex = 0;
8836 return BAD_VALUE;
8837 }
8838 status_t status = NO_ERROR;
8839 while (mCblk->serverIndex < mCblk->clientIndex) {
8840 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008841 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008842 int *p = (int *)(mBuffer + mCblk->serverIndex);
8843 int size = *p++;
8844 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008845 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008846 break;
8847 }
8848 effect_param_t *param = (effect_param_t *)p;
8849 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008850 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008851 mCblk->serverIndex += size;
8852 continue;
8853 }
Eric Laurent25f43952010-07-28 05:40:18 -07008854 uint32_t psize = sizeof(effect_param_t) +
8855 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8856 param->vsize;
8857 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8858 psize,
8859 p,
8860 &rsize,
8861 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008862 // stop at first error encountered
8863 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008864 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008865 *(int *)pReplyData = reply;
8866 break;
8867 } else if (reply != NO_ERROR) {
8868 *(int *)pReplyData = reply;
8869 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008870 }
8871 mCblk->serverIndex += size;
8872 }
8873 mCblk->serverIndex = 0;
8874 mCblk->clientIndex = 0;
8875 return status;
8876 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008877 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008878 return enable();
8879 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008880 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008881 return disable();
8882 }
8883
8884 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8885}
8886
Eric Laurent59255e42011-07-27 19:49:51 -07008887void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008888{
Steve Block3856b092011-10-20 11:56:00 +01008889 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008890
8891 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008892 mEnabled = enabled;
8893
Mathias Agopian65ab4712010-07-14 17:59:35 -07008894 if (signal && mEffectClient != 0) {
8895 mEffectClient->controlStatusChanged(hasControl);
8896 }
8897}
8898
Eric Laurent25f43952010-07-28 05:40:18 -07008899void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8900 uint32_t cmdSize,
8901 void *pCmdData,
8902 uint32_t replySize,
8903 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904{
8905 if (mEffectClient != 0) {
8906 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8907 }
8908}
8909
8910
8911
8912void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8913{
8914 if (mEffectClient != 0) {
8915 mEffectClient->enableStatusChanged(enabled);
8916 }
8917}
8918
8919status_t AudioFlinger::EffectHandle::onTransact(
8920 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8921{
8922 return BnEffect::onTransact(code, data, reply, flags);
8923}
8924
8925
8926void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8927{
Glenn Kastena0d68332012-01-27 16:47:15 -08008928 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929
8930 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008931 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008932 mPriority,
8933 mHasControl,
8934 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008935 mCblk ? mCblk->clientIndex : 0,
8936 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008937 );
8938
8939 if (locked) {
8940 mCblk->lock.unlock();
8941 }
8942}
8943
8944#undef LOG_TAG
8945#define LOG_TAG "AudioFlinger::EffectChain"
8946
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008947AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008948 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008949 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008950 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8951 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008952{
Dima Zavinfce7a472011-04-19 22:30:36 -07008953 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008954 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008955 return;
8956 }
8957 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8958 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008959}
8960
8961AudioFlinger::EffectChain::~EffectChain()
8962{
8963 if (mOwnInBuffer) {
8964 delete mInBuffer;
8965 }
8966
8967}
8968
Eric Laurent59255e42011-07-27 19:49:51 -07008969// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008970sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008971{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008972 size_t size = mEffects.size();
8973
8974 for (size_t i = 0; i < size; i++) {
8975 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008976 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008977 }
8978 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008979 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008980}
8981
Eric Laurent59255e42011-07-27 19:49:51 -07008982// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008983sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008984{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008985 size_t size = mEffects.size();
8986
8987 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008988 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8989 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008990 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991 }
8992 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008993 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994}
8995
Eric Laurent59255e42011-07-27 19:49:51 -07008996// getEffectFromType_l() must be called with ThreadBase::mLock held
8997sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8998 const effect_uuid_t *type)
8999{
Eric Laurent59255e42011-07-27 19:49:51 -07009000 size_t size = mEffects.size();
9001
9002 for (size_t i = 0; i < size; i++) {
9003 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009004 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009005 }
9006 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009007 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009008}
9009
Eric Laurent91b14c42012-05-30 12:30:29 -07009010void AudioFlinger::EffectChain::clearInputBuffer()
9011{
9012 Mutex::Autolock _l(mLock);
9013 sp<ThreadBase> thread = mThread.promote();
9014 if (thread == 0) {
9015 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9016 return;
9017 }
9018 clearInputBuffer_l(thread);
9019}
9020
9021// Must be called with EffectChain::mLock locked
9022void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9023{
9024 size_t numSamples = thread->frameCount() * thread->channelCount();
9025 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9026
9027}
9028
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029// Must be called with EffectChain::mLock locked
9030void AudioFlinger::EffectChain::process_l()
9031{
Eric Laurentdac69112010-09-28 14:09:57 -07009032 sp<ThreadBase> thread = mThread.promote();
9033 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009034 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009035 return;
9036 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009037 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9038 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009039 // always process effects unless no more tracks are on the session and the effect tail
9040 // has been rendered
9041 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009042 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009043 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009044
Eric Laurent544fe9b2011-11-11 15:42:52 -08009045 if (!tracksOnSession && mTailBufferCount == 0) {
9046 doProcess = false;
9047 }
9048
9049 if (activeTrackCnt() == 0) {
9050 // if no track is active and the effect tail has not been rendered,
9051 // the input buffer must be cleared here as the mixer process will not do it
9052 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009053 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009054 if (mTailBufferCount > 0) {
9055 mTailBufferCount--;
9056 }
9057 }
9058 }
Eric Laurentdac69112010-09-28 14:09:57 -07009059 }
9060
Mathias Agopian65ab4712010-07-14 17:59:35 -07009061 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009062 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009063 for (size_t i = 0; i < size; i++) {
9064 mEffects[i]->process();
9065 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009066 }
9067 for (size_t i = 0; i < size; i++) {
9068 mEffects[i]->updateState();
9069 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009070}
9071
Eric Laurentcab11242010-07-15 12:50:15 -07009072// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009073status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009074{
9075 effect_descriptor_t desc = effect->desc();
9076 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9077
9078 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009079 effect->setChain(this);
9080 sp<ThreadBase> thread = mThread.promote();
9081 if (thread == 0) {
9082 return NO_INIT;
9083 }
9084 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009085
9086 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9087 // Auxiliary effects are inserted at the beginning of mEffects vector as
9088 // they are processed first and accumulated in chain input buffer
9089 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009090
Mathias Agopian65ab4712010-07-14 17:59:35 -07009091 // the input buffer for auxiliary effect contains mono samples in
9092 // 32 bit format. This is to avoid saturation in AudoMixer
9093 // accumulation stage. Saturation is done in EffectModule::process() before
9094 // calling the process in effect engine
9095 size_t numSamples = thread->frameCount();
9096 int32_t *buffer = new int32_t[numSamples];
9097 memset(buffer, 0, numSamples * sizeof(int32_t));
9098 effect->setInBuffer((int16_t *)buffer);
9099 // auxiliary effects output samples to chain input buffer for further processing
9100 // by insert effects
9101 effect->setOutBuffer(mInBuffer);
9102 } else {
9103 // Insert effects are inserted at the end of mEffects vector as they are processed
9104 // after track and auxiliary effects.
9105 // Insert effect order as a function of indicated preference:
9106 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9107 // another effect is present
9108 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9109 // last effect claiming first position
9110 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9111 // first effect claiming last position
9112 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9113 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9114 // already present
9115
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009116 size_t size = mEffects.size();
9117 size_t idx_insert = size;
9118 ssize_t idx_insert_first = -1;
9119 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009121 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009122 effect_descriptor_t d = mEffects[i]->desc();
9123 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9124 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9125 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9126 // check invalid effect chaining combinations
9127 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9128 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009129 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009130 return INVALID_OPERATION;
9131 }
9132 // remember position of first insert effect and by default
9133 // select this as insert position for new effect
9134 if (idx_insert == size) {
9135 idx_insert = i;
9136 }
9137 // remember position of last insert effect claiming
9138 // first position
9139 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9140 idx_insert_first = i;
9141 }
9142 // remember position of first insert effect claiming
9143 // last position
9144 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9145 idx_insert_last == -1) {
9146 idx_insert_last = i;
9147 }
9148 }
9149 }
9150
9151 // modify idx_insert from first position if needed
9152 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9153 if (idx_insert_last != -1) {
9154 idx_insert = idx_insert_last;
9155 } else {
9156 idx_insert = size;
9157 }
9158 } else {
9159 if (idx_insert_first != -1) {
9160 idx_insert = idx_insert_first + 1;
9161 }
9162 }
9163
9164 // always read samples from chain input buffer
9165 effect->setInBuffer(mInBuffer);
9166
9167 // if last effect in the chain, output samples to chain
9168 // output buffer, otherwise to chain input buffer
9169 if (idx_insert == size) {
9170 if (idx_insert != 0) {
9171 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9172 mEffects[idx_insert-1]->configure();
9173 }
9174 effect->setOutBuffer(mOutBuffer);
9175 } else {
9176 effect->setOutBuffer(mInBuffer);
9177 }
9178 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009179
Steve Block3856b092011-10-20 11:56:00 +01009180 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009181 }
9182 effect->configure();
9183 return NO_ERROR;
9184}
9185
Eric Laurentcab11242010-07-15 12:50:15 -07009186// removeEffect_l() must be called with PlaybackThread::mLock held
9187size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009188{
9189 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009190 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009191 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9192
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009193 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009194 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009195 // calling stop here will remove pre-processing effect from the audio HAL.
9196 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9197 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009198 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9199 mEffects[i]->state() == EffectModule::STOPPING) {
9200 mEffects[i]->stop();
9201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009202 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9203 delete[] effect->inBuffer();
9204 } else {
9205 if (i == size - 1 && i != 0) {
9206 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9207 mEffects[i - 1]->configure();
9208 }
9209 }
9210 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009211 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009212 break;
9213 }
9214 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009215
9216 return mEffects.size();
9217}
9218
Eric Laurentcab11242010-07-15 12:50:15 -07009219// setDevice_l() must be called with PlaybackThread::mLock held
9220void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009221{
9222 size_t size = mEffects.size();
9223 for (size_t i = 0; i < size; i++) {
9224 mEffects[i]->setDevice(device);
9225 }
9226}
9227
Eric Laurentcab11242010-07-15 12:50:15 -07009228// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009229void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009230{
9231 size_t size = mEffects.size();
9232 for (size_t i = 0; i < size; i++) {
9233 mEffects[i]->setMode(mode);
9234 }
9235}
9236
Eric Laurentcab11242010-07-15 12:50:15 -07009237// setVolume_l() must be called with PlaybackThread::mLock held
9238bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009239{
9240 uint32_t newLeft = *left;
9241 uint32_t newRight = *right;
9242 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009243 int ctrlIdx = -1;
9244 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009245
Eric Laurentcab11242010-07-15 12:50:15 -07009246 // first update volume controller
9247 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009248 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009249 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9250 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009251 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009252 break;
9253 }
9254 }
9255
9256 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009257 if (hasControl) {
9258 *left = mNewLeftVolume;
9259 *right = mNewRightVolume;
9260 }
9261 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009262 }
9263
9264 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009265 mLeftVolume = newLeft;
9266 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009267
9268 // second get volume update from volume controller
9269 if (ctrlIdx >= 0) {
9270 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009271 mNewLeftVolume = newLeft;
9272 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273 }
9274 // then indicate volume to all other effects in chain.
9275 // Pass altered volume to effects before volume controller
9276 // and requested volume to effects after controller
9277 uint32_t lVol = newLeft;
9278 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009279
Mathias Agopian65ab4712010-07-14 17:59:35 -07009280 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009281 if ((int)i == ctrlIdx) continue;
9282 // this also works for ctrlIdx == -1 when there is no volume controller
9283 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009284 lVol = *left;
9285 rVol = *right;
9286 }
9287 mEffects[i]->setVolume(&lVol, &rVol, false);
9288 }
9289 *left = newLeft;
9290 *right = newRight;
9291
9292 return hasControl;
9293}
9294
Mathias Agopian65ab4712010-07-14 17:59:35 -07009295status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9296{
9297 const size_t SIZE = 256;
9298 char buffer[SIZE];
9299 String8 result;
9300
9301 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9302 result.append(buffer);
9303
9304 bool locked = tryLock(mLock);
9305 // failed to lock - AudioFlinger is probably deadlocked
9306 if (!locked) {
9307 result.append("\tCould not lock mutex:\n");
9308 }
9309
Eric Laurentcab11242010-07-15 12:50:15 -07009310 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9311 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009312 mEffects.size(),
9313 (uint32_t)mInBuffer,
9314 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009315 mActiveTrackCnt);
9316 result.append(buffer);
9317 write(fd, result.string(), result.size());
9318
9319 for (size_t i = 0; i < mEffects.size(); ++i) {
9320 sp<EffectModule> effect = mEffects[i];
9321 if (effect != 0) {
9322 effect->dump(fd, args);
9323 }
9324 }
9325
9326 if (locked) {
9327 mLock.unlock();
9328 }
9329
9330 return NO_ERROR;
9331}
9332
Eric Laurent59255e42011-07-27 19:49:51 -07009333// must be called with ThreadBase::mLock held
9334void AudioFlinger::EffectChain::setEffectSuspended_l(
9335 const effect_uuid_t *type, bool suspend)
9336{
9337 sp<SuspendedEffectDesc> desc;
9338 // use effect type UUID timelow as key as there is no real risk of identical
9339 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009340 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009341 if (suspend) {
9342 if (index >= 0) {
9343 desc = mSuspendedEffects.valueAt(index);
9344 } else {
9345 desc = new SuspendedEffectDesc();
9346 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9347 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009348 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009349 }
9350 if (desc->mRefCount++ == 0) {
9351 sp<EffectModule> effect = getEffectIfEnabled(type);
9352 if (effect != 0) {
9353 desc->mEffect = effect;
9354 effect->setSuspended(true);
9355 effect->setEnabled(false);
9356 }
9357 }
9358 } else {
9359 if (index < 0) {
9360 return;
9361 }
9362 desc = mSuspendedEffects.valueAt(index);
9363 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009364 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009365 desc->mRefCount = 1;
9366 }
9367 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009368 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009369 if (desc->mEffect != 0) {
9370 sp<EffectModule> effect = desc->mEffect.promote();
9371 if (effect != 0) {
9372 effect->setSuspended(false);
9373 sp<EffectHandle> handle = effect->controlHandle();
9374 if (handle != 0) {
9375 effect->setEnabled(handle->enabled());
9376 }
9377 }
9378 desc->mEffect.clear();
9379 }
9380 mSuspendedEffects.removeItemsAt(index);
9381 }
9382 }
9383}
9384
9385// must be called with ThreadBase::mLock held
9386void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9387{
9388 sp<SuspendedEffectDesc> desc;
9389
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009390 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009391 if (suspend) {
9392 if (index >= 0) {
9393 desc = mSuspendedEffects.valueAt(index);
9394 } else {
9395 desc = new SuspendedEffectDesc();
9396 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009397 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009398 }
9399 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009400 Vector< sp<EffectModule> > effects;
9401 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009402 for (size_t i = 0; i < effects.size(); i++) {
9403 setEffectSuspended_l(&effects[i]->desc().type, true);
9404 }
9405 }
9406 } else {
9407 if (index < 0) {
9408 return;
9409 }
9410 desc = mSuspendedEffects.valueAt(index);
9411 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009412 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009413 desc->mRefCount = 1;
9414 }
9415 if (--desc->mRefCount == 0) {
9416 Vector<const effect_uuid_t *> types;
9417 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9418 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9419 continue;
9420 }
9421 types.add(&mSuspendedEffects.valueAt(i)->mType);
9422 }
9423 for (size_t i = 0; i < types.size(); i++) {
9424 setEffectSuspended_l(types[i], false);
9425 }
Steve Block3856b092011-10-20 11:56:00 +01009426 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009427 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9428 }
9429 }
9430}
9431
Eric Laurent6bffdb82011-09-23 08:40:41 -07009432
9433// The volume effect is used for automated tests only
9434#ifndef OPENSL_ES_H_
9435static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9436 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9437const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9438#endif //OPENSL_ES_H_
9439
Eric Laurentdb7c0792011-08-10 10:37:50 -07009440bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9441{
9442 // auxiliary effects and visualizer are never suspended on output mix
9443 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9444 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009445 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9446 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009447 return false;
9448 }
9449 return true;
9450}
9451
Glenn Kastend0539712012-01-30 12:56:03 -08009452void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009453{
Glenn Kastend0539712012-01-30 12:56:03 -08009454 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009455 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009456 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9457 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009458 }
Eric Laurent59255e42011-07-27 19:49:51 -07009459 }
Eric Laurent59255e42011-07-27 19:49:51 -07009460}
9461
9462sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9463 const effect_uuid_t *type)
9464{
Glenn Kasten090f0192012-01-30 13:00:02 -08009465 sp<EffectModule> effect = getEffectFromType_l(type);
9466 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009467}
9468
9469void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9470 bool enabled)
9471{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009472 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009473 if (enabled) {
9474 if (index < 0) {
9475 // if the effect is not suspend check if all effects are suspended
9476 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9477 if (index < 0) {
9478 return;
9479 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009480 if (!isEffectEligibleForSuspend(effect->desc())) {
9481 return;
9482 }
Eric Laurent59255e42011-07-27 19:49:51 -07009483 setEffectSuspended_l(&effect->desc().type, enabled);
9484 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009485 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009486 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009487 return;
9488 }
Eric Laurent59255e42011-07-27 19:49:51 -07009489 }
Steve Block3856b092011-10-20 11:56:00 +01009490 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009491 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009492 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9493 // if effect is requested to suspended but was not yet enabled, supend it now.
9494 if (desc->mEffect == 0) {
9495 desc->mEffect = effect;
9496 effect->setEnabled(false);
9497 effect->setSuspended(true);
9498 }
9499 } else {
9500 if (index < 0) {
9501 return;
9502 }
Steve Block3856b092011-10-20 11:56:00 +01009503 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009504 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009505 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9506 desc->mEffect.clear();
9507 effect->setSuspended(false);
9508 }
9509}
9510
Mathias Agopian65ab4712010-07-14 17:59:35 -07009511#undef LOG_TAG
9512#define LOG_TAG "AudioFlinger"
9513
9514// ----------------------------------------------------------------------------
9515
9516status_t AudioFlinger::onTransact(
9517 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9518{
9519 return BnAudioFlinger::onTransact(code, data, reply, flags);
9520}
9521
Mathias Agopian65ab4712010-07-14 17:59:35 -07009522}; // namespace android