blob: e1fae8294b1ce5e1ae9207c6062e79f937f5fefa [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
Glenn Kastend8e6fd32012-05-07 11:07:57 -070022//#define ATRACE_TAG ATRACE_TAG_AUDIO
23
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
34#include <binder/IPCThreadState.h>
35#include <utils/String16.h>
36#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070037#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Dima Zavinfce7a472011-04-19 22:30:36 -070039#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080041#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
Glenn Kastend3cee2f2012-03-13 17:55:35 -070043#undef ADD_BATTERY_DATA
44
45#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080046#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080047#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070048#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
50#include <private/media/AudioTrackShared.h>
51#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070052
Dima Zavin64760242011-05-11 14:15:23 -070053#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070054#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
56#include "AudioMixer.h"
57#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080058#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070061#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070062#include <audio_effects/effect_ns.h>
63#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Glenn Kasten3b21c502011-12-15 09:52:39 -080065#include <audio_utils/primitives.h>
66
Eric Laurentfeb0db62011-07-22 09:04:31 -070067#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080068
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070069// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070074
John Grossman4ff14ba2012-02-08 16:37:41 -080075#include <common_time/cc_helper.h>
76#include <common_time/local_clock.h>
77
Glenn Kasten58912562012-04-03 10:45:00 -070078#include "FastMixer.h"
79
80// NBAIO implementations
81#include "AudioStreamOutSink.h"
82#include "MonoPipe.h"
83#include "MonoPipeReader.h"
84#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 Laurentde070132010-07-13 04:45:46 -0700477 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
479 if (mPlaybackThreads.keyAt(i) != output) {
480 // prevent same audio session on different output threads
481 uint32_t sessions = t->hasAudioSession(*sessionId);
482 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000483 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700484 lStatus = BAD_VALUE;
485 goto Exit;
486 }
487 // check if an effect with same session ID is waiting for a track to be created
488 if (sessions & PlaybackThread::EFFECT_SESSION) {
489 effectThread = t.get();
490 }
Eric Laurentde070132010-07-13 04:45:46 -0700491 }
492 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 lSessionId = *sessionId;
494 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700495 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700496 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 if (sessionId != NULL) {
498 *sessionId = lSessionId;
499 }
500 }
Steve Block3856b092011-10-20 11:56:00 +0100501 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502
503 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800504 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700505
506 // move effect chain to this output thread if an effect on same session was waiting
507 // for a track to be created
508 if (lStatus == NO_ERROR && effectThread != NULL) {
509 Mutex::Autolock _dl(thread->mLock);
510 Mutex::Autolock _sl(effectThread->mLock);
511 moveEffectChain_l(lSessionId, effectThread, thread, true);
512 }
Eric Laurenta011e352012-03-29 15:51:43 -0700513
514 // Look for sync events awaiting for a session to be used.
515 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
516 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
517 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
518 track->setSyncEvent(mPendingSyncEvents[i]);
519 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());
1578 return NO_ERROR;
1579}
1580
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1582{
1583 const size_t SIZE = 256;
1584 char buffer[SIZE];
1585 String8 result;
1586
1587 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1588 result.append(buffer);
1589 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1590 result.append(buffer);
1591 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1592 result.append(buffer);
1593 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1596 result.append(buffer);
1597 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1598 result.append(buffer);
1599 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1600 result.append(buffer);
1601 write(fd, result.string(), result.size());
1602
1603 dumpBase(fd, args);
1604
1605 return NO_ERROR;
1606}
1607
1608// Thread virtuals
1609status_t AudioFlinger::PlaybackThread::readyToRun()
1610{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001611 status_t status = initCheck();
1612 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001613 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001614 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001615 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001617 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618}
1619
1620void AudioFlinger::PlaybackThread::onFirstRef()
1621{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001622 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623}
1624
1625// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001626sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001628 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001630 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001631 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632 int frameCount,
1633 const sp<IMemory>& sharedBuffer,
1634 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001635 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001636 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 status_t *status)
1638{
1639 sp<Track> track;
1640 status_t lStatus;
1641
Glenn Kasten73d22752012-03-19 13:38:30 -07001642 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1643
1644 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001645 if (flags & IAudioFlinger::TRACK_FAST) {
1646 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001647 // not timed
1648 (!isTimed) &&
1649 // either of these use cases:
1650 (
1651 // use case 1: shared buffer with any frame count
1652 (
1653 (sharedBuffer != 0)
1654 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001655 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001656 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001657 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001658 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001659 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001660 )
1661 ) &&
1662 // PCM data
1663 audio_is_linear_pcm(format) &&
1664 // mono or stereo
1665 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1666 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001667#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001668 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001669 (sampleRate == mSampleRate) &&
1670#endif
1671 // normal mixer has an associated fast mixer
1672 hasFastMixer() &&
1673 // there are sufficient fast track slots available
1674 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001675 // FIXME test that MixerThread for this fast track has a capable output HAL
1676 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001677 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001678 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1679 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001680 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001681 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001682 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001683 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001684 } else {
1685 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001686 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1687 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1688 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1689 audio_is_linear_pcm(format),
1690 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001691 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001692 // For compatibility with AudioTrack calculation, buffer depth is forced
1693 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1694 // This is probably too conservative, but legacy application code may depend on it.
1695 // If you change this calculation, also review the start threshold which is related.
1696 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1697 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1698 if (minBufCount < 2) {
1699 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001700 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001701 int minFrameCount = mNormalFrameCount * minBufCount;
1702 if (frameCount < minFrameCount) {
1703 frameCount = minFrameCount;
1704 }
1705 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001706 }
1707
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001709 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1710 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001711 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001712 "for output %p with format %d",
1713 sampleRate, format, channelMask, mOutput, mFormat);
1714 lStatus = BAD_VALUE;
1715 goto Exit;
1716 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717 }
1718 } else {
1719 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1720 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001721 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722 lStatus = BAD_VALUE;
1723 goto Exit;
1724 }
1725 }
1726
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001727 lStatus = initCheck();
1728 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001729 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 goto Exit;
1731 }
1732
1733 { // scope for mLock
1734 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001735
1736 // all tracks in same audio session must share the same routing strategy otherwise
1737 // conflicts will happen when tracks are moved from one output to another by audio policy
1738 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001739 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001740 for (size_t i = 0; i < mTracks.size(); ++i) {
1741 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001742 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001743 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001744 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001745 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001746 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001747 lStatus = BAD_VALUE;
1748 goto Exit;
1749 }
1750 }
1751 }
1752
John Grossman4ff14ba2012-02-08 16:37:41 -08001753 if (!isTimed) {
1754 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001755 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001756 } else {
1757 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1758 channelMask, frameCount, sharedBuffer, sessionId);
1759 }
1760 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 lStatus = NO_MEMORY;
1762 goto Exit;
1763 }
1764 mTracks.add(track);
1765
1766 sp<EffectChain> chain = getEffectChain_l(sessionId);
1767 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001768 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001770 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001771 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 }
1773 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001774
1775#ifdef HAVE_REQUEST_PRIORITY
1776 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1777 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1778 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1779 // so ask activity manager to do this on our behalf
1780 int err = requestPriority(callingPid, tid, 1);
1781 if (err != 0) {
1782 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1783 1, callingPid, tid, err);
1784 }
1785 }
1786#endif
1787
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 lStatus = NO_ERROR;
1789
1790Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001791 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 *status = lStatus;
1793 }
1794 return track;
1795}
1796
1797uint32_t AudioFlinger::PlaybackThread::latency() const
1798{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001799 Mutex::Autolock _l(mLock);
1800 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001801 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001802 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 return 0;
1804 }
1805}
1806
Glenn Kasten6637baa2012-01-09 09:40:36 -08001807void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001809 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811}
1812
Glenn Kasten6637baa2012-01-09 09:40:36 -08001813void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001815 Mutex::Autolock _l(mLock);
1816 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817}
1818
Glenn Kasten6637baa2012-01-09 09:40:36 -08001819void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001821 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823}
1824
Glenn Kasten6637baa2012-01-09 09:40:36 -08001825void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001827 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829}
1830
Glenn Kastenfff6d712012-01-12 16:38:12 -08001831float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001833 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 return mStreamTypes[stream].volume;
1835}
1836
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837// addTrack_l() must be called with ThreadBase::mLock held
1838status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1839{
1840 status_t status = ALREADY_EXISTS;
1841
1842 // set retry count for buffer fill
1843 track->mRetryCount = kMaxTrackStartupRetries;
1844 if (mActiveTracks.indexOf(track) < 0) {
1845 // the track is newly added, make sure it fills up all its
1846 // buffers before playing. This is to ensure the client will
1847 // effectively get the latency it requested.
1848 track->mFillingUpStatus = Track::FS_FILLING;
1849 track->mResetDone = false;
1850 mActiveTracks.add(track);
1851 if (track->mainBuffer() != mMixBuffer) {
1852 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1853 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001854 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001855 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 }
1857 }
1858
1859 status = NO_ERROR;
1860 }
1861
Steve Block3856b092011-10-20 11:56:00 +01001862 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 mWaitWorkCV.broadcast();
1864
1865 return status;
1866}
1867
1868// destroyTrack_l() must be called with ThreadBase::mLock held
1869void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1870{
1871 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001872 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001874 removeTrack_l(track);
1875 }
1876}
1877
1878void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1879{
1880 mTracks.remove(track);
1881 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001882 // redundant as track is about to be destroyed, for dumpsys only
1883 track->mName = -1;
1884 if (track->isFastTrack()) {
1885 int index = track->mFastIndex;
1886 ALOG_ASSERT(0 < index && index < FastMixerState::kMaxFastTracks);
1887 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1888 mFastTrackAvailMask |= 1 << index;
1889 // redundant as track is about to be destroyed, for dumpsys only
1890 track->mFastIndex = -1;
1891 }
Eric Laurentb469b942011-05-09 12:09:06 -07001892 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1893 if (chain != 0) {
1894 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 }
1896}
1897
1898String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1899{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001900 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001901 char *s;
1902
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001903 Mutex::Autolock _l(mLock);
1904 if (initCheck() != NO_ERROR) {
1905 return out_s8;
1906 }
1907
Dima Zavin799a70e2011-04-18 16:57:27 -07001908 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001909 out_s8 = String8(s);
1910 free(s);
1911 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912}
1913
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001914// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1916 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001917 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918
Steve Block3856b092011-10-20 11:56:00 +01001919 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920
1921 switch (event) {
1922 case AudioSystem::OUTPUT_OPENED:
1923 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001924 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 desc.samplingRate = mSampleRate;
1926 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001927 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 desc.latency = latency();
1929 param2 = &desc;
1930 break;
1931
1932 case AudioSystem::STREAM_CONFIG_CHANGED:
1933 param2 = &param;
1934 case AudioSystem::OUTPUT_CLOSED:
1935 default:
1936 break;
1937 }
1938 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1939}
1940
1941void AudioFlinger::PlaybackThread::readOutputParameters()
1942{
Dima Zavin799a70e2011-04-18 16:57:27 -07001943 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001944 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1945 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001946 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001947 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001948 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001949 if (mFrameCount & 15) {
1950 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1951 mFrameCount);
1952 }
1953
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001954 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001955 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001956 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001957 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001958 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1959 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1960 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1961 maxNormalFrameCount = maxNormalFrameCount & ~15;
1962 if (maxNormalFrameCount < minNormalFrameCount) {
1963 maxNormalFrameCount = minNormalFrameCount;
1964 }
1965 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1966 if (multiplier <= 1.0) {
1967 multiplier = 1.0;
1968 } else if (multiplier <= 2.0) {
1969 if (2 * mFrameCount <= maxNormalFrameCount) {
1970 multiplier = 2.0;
1971 } else {
1972 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1973 }
1974 } else {
1975 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
1976 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
1977 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
1978 // FIXME this rounding up should not be done if no HAL SRC
1979 uint32_t truncMult = (uint32_t) multiplier;
1980 if ((truncMult & 1)) {
1981 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1982 ++truncMult;
1983 }
1984 }
1985 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07001986 }
Glenn Kasten58912562012-04-03 10:45:00 -07001987 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07001988 mNormalFrameCount = multiplier * mFrameCount;
1989 // round up to nearest 16 frames to satisfy AudioMixer
1990 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07001991 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992
1993 // FIXME - Current mixer implementation only supports stereo output: Always
1994 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001995 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001996 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1997 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998
Eric Laurentde070132010-07-13 04:45:46 -07001999 // force reconfiguration of effect chains and engines to take new buffer size and audio
2000 // parameters into account
2001 // Note that mLock is not held when readOutputParameters() is called from the constructor
2002 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2003 // matter.
2004 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2005 Vector< sp<EffectChain> > effectChains = mEffectChains;
2006 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002007 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009}
2010
2011status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2012{
Glenn Kastena0d68332012-01-27 16:47:15 -08002013 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 return BAD_VALUE;
2015 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002016 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002017 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018 return INVALID_OPERATION;
2019 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002020 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021
Dima Zavin799a70e2011-04-18 16:57:27 -07002022 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023}
2024
Eric Laurent39e94f82010-07-28 01:32:47 -07002025uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026{
2027 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002028 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002030 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031 }
2032
2033 for (size_t i = 0; i < mTracks.size(); ++i) {
2034 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002035 if (sessionId == track->sessionId() &&
2036 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002037 result |= TRACK_SESSION;
2038 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 }
2040 }
2041
Eric Laurent39e94f82010-07-28 01:32:47 -07002042 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043}
2044
Eric Laurentde070132010-07-13 04:45:46 -07002045uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2046{
Dima Zavinfce7a472011-04-19 22:30:36 -07002047 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002048 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002049 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2050 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002051 }
2052 for (size_t i = 0; i < mTracks.size(); i++) {
2053 sp<Track> track = mTracks[i];
2054 if (sessionId == track->sessionId() &&
2055 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002056 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002057 }
2058 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002059 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002060}
2061
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062
Glenn Kastenaed850d2012-01-26 09:46:34 -08002063AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002064{
2065 Mutex::Autolock _l(mLock);
2066 return mOutput;
2067}
2068
2069AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2070{
2071 Mutex::Autolock _l(mLock);
2072 AudioStreamOut *output = mOutput;
2073 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002074 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2075 // must push a NULL and wait for ack
2076 mOutputSink.clear();
2077 mPipeSink.clear();
2078 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002079 return output;
2080}
2081
2082// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002083audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002084{
2085 if (mOutput == NULL) {
2086 return NULL;
2087 }
2088 return &mOutput->stream->common;
2089}
2090
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002091uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002092{
2093 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2094 // decoding and transfer time. So sleeping for half of the latency would likely cause
2095 // underruns
2096 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002097 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002098 } else {
2099 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2100 }
2101}
2102
Eric Laurenta011e352012-03-29 15:51:43 -07002103status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2104{
2105 if (!isValidSyncEvent(event)) {
2106 return BAD_VALUE;
2107 }
2108
2109 Mutex::Autolock _l(mLock);
2110
2111 for (size_t i = 0; i < mTracks.size(); ++i) {
2112 sp<Track> track = mTracks[i];
2113 if (event->triggerSession() == track->sessionId()) {
2114 track->setSyncEvent(event);
2115 return NO_ERROR;
2116 }
2117 }
2118
2119 return NAME_NOT_FOUND;
2120}
2121
2122bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2123{
2124 switch (event->type()) {
2125 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2126 return true;
2127 default:
2128 break;
2129 }
2130 return false;
2131}
2132
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133// ----------------------------------------------------------------------------
2134
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002135AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002136 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002137 : PlaybackThread(audioFlinger, output, id, device, type),
2138 // mAudioMixer below
2139#ifdef SOAKER
2140 mSoaker(NULL),
2141#endif
2142 // mFastMixer below
2143 mFastMixerFutex(0)
2144 // mOutputSink below
2145 // mPipeSink below
2146 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147{
Glenn Kasten58912562012-04-03 10:45:00 -07002148 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2149 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2150 "mFrameCount=%d, mNormalFrameCount=%d",
2151 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2152 mNormalFrameCount);
2153 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2154
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 // FIXME - Current mixer implementation only supports stereo output
2156 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002157 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 }
Glenn Kasten58912562012-04-03 10:45:00 -07002159
2160 // create an NBAIO sink for the HAL output stream, and negotiate
2161 mOutputSink = new AudioStreamOutSink(output->stream);
2162 size_t numCounterOffers = 0;
2163 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2164 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2165 ALOG_ASSERT(index == 0);
2166
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002167 // initialize fast mixer depending on configuration
2168 bool initFastMixer;
2169 switch (kUseFastMixer) {
2170 case FastMixer_Never:
2171 initFastMixer = false;
2172 break;
2173 case FastMixer_Always:
2174 initFastMixer = true;
2175 break;
2176 case FastMixer_Static:
2177 case FastMixer_Dynamic:
2178 initFastMixer = mFrameCount < mNormalFrameCount;
2179 break;
2180 }
2181 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002182
2183 // create a MonoPipe to connect our submix to FastMixer
2184 NBAIO_Format format = mOutputSink->format();
2185 // frame count will be rounded up to a power of 2, so this formula should work well
2186 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2187 true /*writeCanBlock*/);
2188 const NBAIO_Format offers[1] = {format};
2189 size_t numCounterOffers = 0;
2190 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2191 ALOG_ASSERT(index == 0);
2192 mPipeSink = monoPipe;
2193
2194#ifdef SOAKER
2195 // create a soaker as workaround for governor issues
2196 mSoaker = new Soaker();
2197 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2198 mSoaker->run("Soaker", PRIORITY_LOWEST);
2199#endif
2200
2201 // create fast mixer and configure it initially with just one fast track for our submix
2202 mFastMixer = new FastMixer();
2203 FastMixerStateQueue *sq = mFastMixer->sq();
2204 FastMixerState *state = sq->begin();
2205 FastTrack *fastTrack = &state->mFastTracks[0];
2206 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2207 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2208 fastTrack->mVolumeProvider = NULL;
2209 fastTrack->mGeneration++;
2210 state->mFastTracksGen++;
2211 state->mTrackMask = 1;
2212 // fast mixer will use the HAL output sink
2213 state->mOutputSink = mOutputSink.get();
2214 state->mOutputSinkGen++;
2215 state->mFrameCount = mFrameCount;
2216 state->mCommand = FastMixerState::COLD_IDLE;
2217 // already done in constructor initialization list
2218 //mFastMixerFutex = 0;
2219 state->mColdFutexAddr = &mFastMixerFutex;
2220 state->mColdGen++;
2221 state->mDumpState = &mFastMixerDumpState;
2222 sq->end();
2223 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2224
2225 // start the fast mixer
2226 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2227#ifdef HAVE_REQUEST_PRIORITY
2228 pid_t tid = mFastMixer->getTid();
2229 int err = requestPriority(getpid_cached, tid, 2);
2230 if (err != 0) {
2231 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2232 2, getpid_cached, tid, err);
2233 }
2234#endif
2235
2236 } else {
2237 mFastMixer = NULL;
2238 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002239
2240 switch (kUseFastMixer) {
2241 case FastMixer_Never:
2242 case FastMixer_Dynamic:
2243 mNormalSink = mOutputSink;
2244 break;
2245 case FastMixer_Always:
2246 mNormalSink = mPipeSink;
2247 break;
2248 case FastMixer_Static:
2249 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2250 break;
2251 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252}
2253
2254AudioFlinger::MixerThread::~MixerThread()
2255{
Glenn Kasten58912562012-04-03 10:45:00 -07002256 if (mFastMixer != NULL) {
2257 FastMixerStateQueue *sq = mFastMixer->sq();
2258 FastMixerState *state = sq->begin();
2259 if (state->mCommand == FastMixerState::COLD_IDLE) {
2260 int32_t old = android_atomic_inc(&mFastMixerFutex);
2261 if (old == -1) {
2262 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2263 }
2264 }
2265 state->mCommand = FastMixerState::EXIT;
2266 sq->end();
2267 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2268 mFastMixer->join();
2269 // Though the fast mixer thread has exited, it's state queue is still valid.
2270 // We'll use that extract the final state which contains one remaining fast track
2271 // corresponding to our sub-mix.
2272 state = sq->begin();
2273 ALOG_ASSERT(state->mTrackMask == 1);
2274 FastTrack *fastTrack = &state->mFastTracks[0];
2275 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2276 delete fastTrack->mBufferProvider;
2277 sq->end(false /*didModify*/);
2278 delete mFastMixer;
2279#ifdef SOAKER
2280 if (mSoaker != NULL) {
2281 mSoaker->requestExitAndWait();
2282 }
2283 delete mSoaker;
2284#endif
2285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 delete mAudioMixer;
2287}
2288
Glenn Kasten83efdd02012-02-24 07:21:32 -08002289class CpuStats {
2290public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002291 CpuStats();
2292 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002293#ifdef DEBUG_CPU_USAGE
2294private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002295 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2296 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2297
2298 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2299
2300 int mCpuNum; // thread's current CPU number
2301 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002302#endif
2303};
2304
Glenn Kasten190a46f2012-03-06 11:27:10 -08002305CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002306#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002307 : mCpuNum(-1), mCpukHz(-1)
2308#endif
2309{
2310}
2311
2312void CpuStats::sample(const String8 &title) {
2313#ifdef DEBUG_CPU_USAGE
2314 // get current thread's delta CPU time in wall clock ns
2315 double wcNs;
2316 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2317
2318 // record sample for wall clock statistics
2319 if (valid) {
2320 mWcStats.sample(wcNs);
2321 }
2322
2323 // get the current CPU number
2324 int cpuNum = sched_getcpu();
2325
2326 // get the current CPU frequency in kHz
2327 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2328
2329 // check if either CPU number or frequency changed
2330 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2331 mCpuNum = cpuNum;
2332 mCpukHz = cpukHz;
2333 // ignore sample for purposes of cycles
2334 valid = false;
2335 }
2336
2337 // if no change in CPU number or frequency, then record sample for cycle statistics
2338 if (valid && mCpukHz > 0) {
2339 double cycles = wcNs * cpukHz * 0.000001;
2340 mHzStats.sample(cycles);
2341 }
2342
2343 unsigned n = mWcStats.n();
2344 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002345 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002346 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002347 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2348 double perLoop = elapsed / (double) n;
2349 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002350 double perLoop1k = perLoop * 0.001;
2351 double mean = mWcStats.mean();
2352 double stddev = mWcStats.stddev();
2353 double minimum = mWcStats.minimum();
2354 double maximum = mWcStats.maximum();
2355 double meanCycles = mHzStats.mean();
2356 double stddevCycles = mHzStats.stddev();
2357 double minCycles = mHzStats.minimum();
2358 double maxCycles = mHzStats.maximum();
2359 mCpuUsage.resetElapsed();
2360 mWcStats.reset();
2361 mHzStats.reset();
2362 ALOGD("CPU usage for %s over past %.1f secs\n"
2363 " (%u mixer loops at %.1f mean ms per loop):\n"
2364 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2365 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2366 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2367 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002368 elapsed * .000000001, n, perLoop * .000001,
2369 mean * .001,
2370 stddev * .001,
2371 minimum * .001,
2372 maximum * .001,
2373 mean / perLoop100,
2374 stddev / perLoop100,
2375 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002376 maximum / perLoop100,
2377 meanCycles / perLoop1k,
2378 stddevCycles / perLoop1k,
2379 minCycles / perLoop1k,
2380 maxCycles / perLoop1k);
2381
Glenn Kasten83efdd02012-02-24 07:21:32 -08002382 }
2383 }
2384#endif
2385};
2386
Glenn Kasten37d825e2012-02-24 07:21:48 -08002387void AudioFlinger::PlaybackThread::checkSilentMode_l()
2388{
2389 if (!mMasterMute) {
2390 char value[PROPERTY_VALUE_MAX];
2391 if (property_get("ro.audio.silent", value, "0") > 0) {
2392 char *endptr;
2393 unsigned long ul = strtoul(value, &endptr, 0);
2394 if (*endptr == '\0' && ul != 0) {
2395 ALOGD("Silence is golden");
2396 // The setprop command will not allow a property to be changed after
2397 // the first time it is set, so we don't have to worry about un-muting.
2398 setMasterMute_l(true);
2399 }
2400 }
2401 }
2402}
2403
Glenn Kasten000f0e32012-03-01 17:10:56 -08002404bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405{
2406 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002407
Glenn Kasten000f0e32012-03-01 17:10:56 -08002408 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002409
2410 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002412if (mType == MIXER) {
2413 longStandbyExit = false;
2414}
Glenn Kasten688a6402012-02-29 07:57:06 -08002415
Glenn Kasten000f0e32012-03-01 17:10:56 -08002416 // DUPLICATING
2417 // FIXME could this be made local to while loop?
2418 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002419
Glenn Kasten66fcab92012-02-24 14:59:21 -08002420 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002421 sleepTime = idleSleepTime;
2422
2423if (mType == MIXER) {
2424 sleepTimeShift = 0;
2425}
2426
Glenn Kasten83efdd02012-02-24 07:21:32 -08002427 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002428 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429
Eric Laurentfeb0db62011-07-22 09:04:31 -07002430 acquireWakeLock();
2431
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 while (!exitPending())
2433 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002434 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002435
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002436 Vector< sp<EffectChain> > effectChains;
2437
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 processConfigEvents();
2439
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 { // scope for mLock
2441
2442 Mutex::Autolock _l(mLock);
2443
2444 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002445 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 }
2447
Glenn Kastenfa26a852012-03-06 11:28:04 -08002448 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002449
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002451 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002452 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002454
2455 threadLoop_standby();
2456
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457 mStandby = true;
2458 mBytesWritten = 0;
2459 }
2460
Glenn Kasten3e074702012-02-28 18:40:35 -08002461 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 // we're about to wait, flush the binder command buffer
2463 IPCThreadState::self()->flushCommands();
2464
Glenn Kastenfa26a852012-03-06 11:28:04 -08002465 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002466
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467 if (exitPending()) break;
2468
Eric Laurentfeb0db62011-07-22 09:04:31 -07002469 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002471 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002473 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002474 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475
Eric Laurentda747442012-04-25 18:53:13 -07002476 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002477 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002478
Glenn Kasten37d825e2012-02-24 07:21:48 -08002479 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480
Glenn Kasten000f0e32012-03-01 17:10:56 -08002481 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002483 if (mType == MIXER) {
2484 sleepTimeShift = 0;
2485 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002486
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 continue;
2488 }
2489 }
2490
Glenn Kasten81028042012-04-30 18:15:12 -07002491 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002492 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493
2494 // prevent any changes in effect chain list and in each effect chain
2495 // during mixing and effect process as the audio buffers could be deleted
2496 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002497 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002498 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499
Glenn Kastenfec279f2012-03-08 07:47:15 -08002500 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002501 threadLoop_mix();
2502 } else {
2503 threadLoop_sleepTime();
2504 }
2505
2506 if (mSuspended > 0) {
2507 sleepTime = suspendSleepTimeUs();
2508 }
2509
2510 // only process effects if we're going to write
2511 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002512 for (size_t i = 0; i < effectChains.size(); i ++) {
2513 effectChains[i]->process_l();
2514 }
2515 }
2516
2517 // enable changes in effect chain
2518 unlockEffectChains(effectChains);
2519
2520 // sleepTime == 0 means we must write to audio hardware
2521 if (sleepTime == 0) {
2522
2523 threadLoop_write();
2524
2525if (mType == MIXER) {
2526 // write blocked detection
2527 nsecs_t now = systemTime();
2528 nsecs_t delta = now - mLastWriteTime;
2529 if (!mStandby && delta > maxPeriod) {
2530 mNumDelayedWrites++;
2531 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002532 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten000f0e32012-03-01 17:10:56 -08002533 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2534 ns2ms(delta), mNumDelayedWrites, this);
2535 lastWarning = now;
2536 }
2537 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2538 // a different threshold. Or completely removed for what it is worth anyway...
2539 if (mStandby) {
2540 longStandbyExit = true;
2541 }
2542 }
2543}
2544
2545 mStandby = false;
2546 } else {
2547 usleep(sleepTime);
2548 }
2549
Glenn Kasten58912562012-04-03 10:45:00 -07002550 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002551 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002552 // same lock. This will also mutate and push a new fast mixer state.
2553 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002554 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002555
Glenn Kastenfa26a852012-03-06 11:28:04 -08002556 // FIXME I don't understand the need for this here;
2557 // it was in the original code but maybe the
2558 // assignment in saveOutputTracks() makes this unnecessary?
2559 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002560
2561 // Effect chains will be actually deleted here if they were removed from
2562 // mEffectChains list during mixing or effects processing
2563 effectChains.clear();
2564
2565 // FIXME Note that the above .clear() is no longer necessary since effectChains
2566 // is now local to this block, but will keep it for now (at least until merge done).
2567 }
2568
2569if (mType == MIXER || mType == DIRECT) {
2570 // put output stream into standby mode
2571 if (!mStandby) {
2572 mOutput->stream->common.standby(&mOutput->stream->common);
2573 }
2574}
2575if (mType == DUPLICATING) {
2576 // for DuplicatingThread, standby mode is handled by the outputTracks
2577}
2578
2579 releaseWakeLock();
2580
2581 ALOGV("Thread %p type %d exiting", this, mType);
2582 return false;
2583}
2584
Glenn Kasten288ed212012-04-25 17:52:27 -07002585// returns (via tracksToRemove) a set of tracks to remove.
Glenn Kasten58912562012-04-03 10:45:00 -07002586void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2587{
Glenn Kasten58912562012-04-03 10:45:00 -07002588 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2589}
2590
2591void AudioFlinger::MixerThread::threadLoop_write()
2592{
2593 // FIXME we should only do one push per cycle; confirm this is true
2594 // Start the fast mixer if it's not already running
2595 if (mFastMixer != NULL) {
2596 FastMixerStateQueue *sq = mFastMixer->sq();
2597 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002598 if (state->mCommand != FastMixerState::MIX_WRITE &&
2599 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002600 if (state->mCommand == FastMixerState::COLD_IDLE) {
2601 int32_t old = android_atomic_inc(&mFastMixerFutex);
2602 if (old == -1) {
2603 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2604 }
2605 }
2606 state->mCommand = FastMixerState::MIX_WRITE;
2607 sq->end();
2608 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002609 if (kUseFastMixer == FastMixer_Dynamic) {
2610 mNormalSink = mPipeSink;
2611 }
Glenn Kasten58912562012-04-03 10:45:00 -07002612 } else {
2613 sq->end(false /*didModify*/);
2614 }
2615 }
2616 PlaybackThread::threadLoop_write();
2617}
2618
Glenn Kasten000f0e32012-03-01 17:10:56 -08002619// shared by MIXER and DIRECT, overridden by DUPLICATING
2620void AudioFlinger::PlaybackThread::threadLoop_write()
2621{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002622 // FIXME rewrite to reduce number of system calls
2623 mLastWriteTime = systemTime();
2624 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002625
Glenn Kasten58912562012-04-03 10:45:00 -07002626#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002627 size_t count = mixBufferSize >> mBitShift;
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002628 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002629 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002630 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002631 if (framesWritten > 0) {
2632 size_t bytesWritten = framesWritten << mBitShift;
2633 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002634 }
2635
Glenn Kasten952eeb22012-03-06 11:30:57 -08002636 mNumWrites++;
2637 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002638}
2639
Glenn Kasten58912562012-04-03 10:45:00 -07002640void AudioFlinger::MixerThread::threadLoop_standby()
2641{
2642 // Idle the fast mixer if it's currently running
2643 if (mFastMixer != NULL) {
2644 FastMixerStateQueue *sq = mFastMixer->sq();
2645 FastMixerState *state = sq->begin();
2646 if (!(state->mCommand & FastMixerState::IDLE)) {
2647 state->mCommand = FastMixerState::COLD_IDLE;
2648 state->mColdFutexAddr = &mFastMixerFutex;
2649 state->mColdGen++;
2650 mFastMixerFutex = 0;
2651 sq->end();
2652 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2653 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002654 if (kUseFastMixer == FastMixer_Dynamic) {
2655 mNormalSink = mOutputSink;
2656 }
Glenn Kasten58912562012-04-03 10:45:00 -07002657 } else {
2658 sq->end(false /*didModify*/);
2659 }
2660 }
2661 PlaybackThread::threadLoop_standby();
2662}
2663
Glenn Kasten000f0e32012-03-01 17:10:56 -08002664// shared by MIXER and DIRECT, overridden by DUPLICATING
2665void AudioFlinger::PlaybackThread::threadLoop_standby()
2666{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002667 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2668 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002669}
2670
2671void AudioFlinger::MixerThread::threadLoop_mix()
2672{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002673 // obtain the presentation timestamp of the next output buffer
2674 int64_t pts;
2675 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002676
Glenn Kasten952eeb22012-03-06 11:30:57 -08002677 if (NULL != mOutput->stream->get_next_write_timestamp) {
2678 status = mOutput->stream->get_next_write_timestamp(
2679 mOutput->stream, &pts);
2680 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002681
Glenn Kasten952eeb22012-03-06 11:30:57 -08002682 if (status != NO_ERROR) {
2683 pts = AudioBufferProvider::kInvalidPTS;
2684 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002685
Glenn Kasten952eeb22012-03-06 11:30:57 -08002686 // mix buffers...
2687 mAudioMixer->process(pts);
2688 // increase sleep time progressively when application underrun condition clears.
2689 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2690 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2691 // such that we would underrun the audio HAL.
2692 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2693 sleepTimeShift--;
2694 }
2695 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002696 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002697 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002698}
2699
2700void AudioFlinger::MixerThread::threadLoop_sleepTime()
2701{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002702 // If no tracks are ready, sleep once for the duration of an output
2703 // buffer size, then write 0s to the output
2704 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002705 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002706 sleepTime = activeSleepTime >> sleepTimeShift;
2707 if (sleepTime < kMinThreadSleepTimeUs) {
2708 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002710 // reduce sleep time in case of consecutive application underruns to avoid
2711 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2712 // duration we would end up writing less data than needed by the audio HAL if
2713 // the condition persists.
2714 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2715 sleepTimeShift++;
2716 }
2717 } else {
2718 sleepTime = idleSleepTime;
2719 }
2720 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002721 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002722 memset (mMixBuffer, 0, mixBufferSize);
2723 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002724 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002725 }
2726 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727}
2728
2729// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002730AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002731 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732{
2733
Glenn Kasten29c23c32012-01-26 13:37:52 -08002734 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002736 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737 size_t mixedTracks = 0;
2738 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002739 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002740 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002741 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742
2743 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002744 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745
Eric Laurent571d49c2010-08-11 05:20:11 -07002746 if (masterMute) {
2747 masterVolume = 0;
2748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002750 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002752 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002753 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 masterVolume = (float)((v + (1 << 23)) >> 24);
2755 chain.clear();
2756 }
2757
Glenn Kasten288ed212012-04-25 17:52:27 -07002758 // prepare a new state to push
2759 FastMixerStateQueue *sq = NULL;
2760 FastMixerState *state = NULL;
2761 bool didModify = false;
2762 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2763 if (mFastMixer != NULL) {
2764 sq = mFastMixer->sq();
2765 state = sq->begin();
2766 }
2767
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002769 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 if (t == 0) continue;
2771
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002772 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002774
Glenn Kasten288ed212012-04-25 17:52:27 -07002775 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002776 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002777
2778 // It's theoretically possible (though unlikely) for a fast track to be created
2779 // and then removed within the same normal mix cycle. This is not a problem, as
2780 // the track never becomes active so it's fast mixer slot is never touched.
2781 // The converse, of removing an (active) track and then creating a new track
2782 // at the identical fast mixer slot within the same normal mix cycle,
2783 // is impossible because the slot isn't marked available until the end of each cycle.
2784 int j = track->mFastIndex;
2785 FastTrack *fastTrack = &state->mFastTracks[j];
2786
2787 // Determine whether the track is currently in underrun condition,
2788 // and whether it had a recent underrun.
Glenn Kasten09474df2012-05-10 14:48:07 -07002789 FastTrackUnderruns underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2790 uint32_t recentFull = (underruns.mBitFields.mFull -
2791 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2792 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2793 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2794 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2795 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2796 uint32_t recentUnderruns = recentPartial + recentEmpty;
2797 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002798 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002799 // or stopped which can occur when flush() is called while active
2800 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002801 track->mUnderrunCount += recentUnderruns;
2802 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002803
Glenn Kastend08f48c2012-05-01 18:14:02 -07002804 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002805 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002806 bool isActive = true;
2807 switch (track->mState) {
2808 case TrackBase::STOPPING_1:
2809 // track stays active in STOPPING_1 state until first underrun
2810 if (recentUnderruns > 0) {
2811 track->mState = TrackBase::STOPPING_2;
2812 }
2813 break;
2814 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002815 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002816 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002817 break;
2818 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002819 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002820 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002821 break;
2822 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002823 if (recentFull > 0 || recentPartial > 0) {
2824 // track has provided at least some frames recently: reset retry count
2825 track->mRetryCount = kMaxTrackRetries;
2826 }
2827 if (recentUnderruns == 0) {
2828 // no recent underruns: stay active
2829 break;
2830 }
2831 // there has recently been an underrun of some kind
2832 if (track->sharedBuffer() == 0) {
2833 // were any of the recent underruns "empty" (no frames available)?
2834 if (recentEmpty == 0) {
2835 // no, then ignore the partial underruns as they are allowed indefinitely
2836 break;
2837 }
2838 // there has recently been an "empty" underrun: decrement the retry counter
2839 if (--(track->mRetryCount) > 0) {
2840 break;
2841 }
2842 // indicate to client process that the track was disabled because of underrun;
2843 // it will then automatically call start() when data is available
2844 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2845 // remove from active list, but state remains ACTIVE [confusing but true]
2846 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002847 break;
2848 }
2849 // fall through
2850 case TrackBase::STOPPING_2:
2851 case TrackBase::PAUSED:
2852 case TrackBase::TERMINATED:
2853 case TrackBase::STOPPED: // flush() while active
2854 // Check for presentation complete if track is inactive
2855 // We have consumed all the buffers of this track.
2856 // This would be incomplete if we auto-paused on underrun
2857 {
2858 size_t audioHALFrames =
2859 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2860 size_t framesWritten =
2861 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2862 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2863 // track stays in active list until presentation is complete
2864 break;
2865 }
2866 }
2867 if (track->isStopping_2()) {
2868 track->mState = TrackBase::STOPPED;
2869 }
2870 if (track->isStopped()) {
2871 // Can't reset directly, as fast mixer is still polling this track
2872 // track->reset();
2873 // So instead mark this track as needing to be reset after push with ack
2874 resetMask |= 1 << i;
2875 }
2876 isActive = false;
2877 break;
2878 case TrackBase::IDLE:
2879 default:
2880 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002881 }
2882
2883 if (isActive) {
2884 // was it previously inactive?
2885 if (!(state->mTrackMask & (1 << j))) {
2886 ExtendedAudioBufferProvider *eabp = track;
2887 VolumeProvider *vp = track;
2888 fastTrack->mBufferProvider = eabp;
2889 fastTrack->mVolumeProvider = vp;
2890 fastTrack->mSampleRate = track->mSampleRate;
2891 fastTrack->mChannelMask = track->mChannelMask;
2892 fastTrack->mGeneration++;
2893 state->mTrackMask |= 1 << j;
2894 didModify = true;
2895 // no acknowledgement required for newly active tracks
2896 }
2897 // cache the combined master volume and stream type volume for fast mixer; this
2898 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2899 track->mCachedVolume = track->isMuted() ?
2900 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2901 ++fastTracks;
2902 } else {
2903 // was it previously active?
2904 if (state->mTrackMask & (1 << j)) {
2905 fastTrack->mBufferProvider = NULL;
2906 fastTrack->mGeneration++;
2907 state->mTrackMask &= ~(1 << j);
2908 didModify = true;
2909 // If any fast tracks were removed, we must wait for acknowledgement
2910 // because we're about to decrement the last sp<> on those tracks.
2911 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002912 } else {
2913 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002914 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002915 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002916 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07002917 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002918 }
2919 continue;
2920 }
2921
2922 { // local variable scope to avoid goto warning
2923
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 audio_track_cblk_t* cblk = track->cblk();
2925
2926 // The first time a track is added we wait
2927 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002928 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002929 // make sure that we have enough frames to mix one full buffer.
2930 // enforce this condition only once to enable draining the buffer in case the client
2931 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002932 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002933 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002934 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002935 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002936 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002937 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002938 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002939 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002940 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002941 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002942 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002943 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002944 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2945 // the minimum track buffer size is normally twice the number of frames necessary
2946 // to fill one buffer and the resampler should not leave more than one buffer worth
2947 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002948 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002949 }
2950 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002951 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 !track->isPaused() && !track->isTerminated())
2953 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002954 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955
2956 mixedTracks++;
2957
2958 // track->mainBuffer() != mMixBuffer means there is an effect chain
2959 // connected to the track
2960 chain.clear();
2961 if (track->mainBuffer() != mMixBuffer) {
2962 chain = getEffectChain_l(track->sessionId());
2963 // Delegate volume control to effect in track effect chain if needed
2964 if (chain != 0) {
2965 tracksWithEffect++;
2966 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002967 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002968 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969 }
2970 }
2971
2972
2973 int param = AudioMixer::VOLUME;
2974 if (track->mFillingUpStatus == Track::FS_FILLED) {
2975 // no ramp for the first volume setting
2976 track->mFillingUpStatus = Track::FS_ACTIVE;
2977 if (track->mState == TrackBase::RESUMING) {
2978 track->mState = TrackBase::ACTIVE;
2979 param = AudioMixer::RAMP_VOLUME;
2980 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002981 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 } else if (cblk->server != 0) {
2983 // If the track is stopped before the first frame was mixed,
2984 // do not apply ramp
2985 param = AudioMixer::RAMP_VOLUME;
2986 }
2987
2988 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002989 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002990 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002991 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002992 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 if (track->isPausing()) {
2994 track->setPaused();
2995 }
2996 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002997
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002999 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003001 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003002 vl = vlr & 0xFFFF;
3003 vr = vlr >> 16;
3004 // track volumes come from shared memory, so can't be trusted and must be clamped
3005 if (vl > MAX_GAIN_INT) {
3006 ALOGV("Track left volume out of range: %04X", vl);
3007 vl = MAX_GAIN_INT;
3008 }
3009 if (vr > MAX_GAIN_INT) {
3010 ALOGV("Track right volume out of range: %04X", vr);
3011 vr = MAX_GAIN_INT;
3012 }
3013 // now apply the master volume and stream type volume
3014 vl = (uint32_t)(v * vl) << 12;
3015 vr = (uint32_t)(v * vr) << 12;
3016 // assuming master volume and stream type volume each go up to 1.0,
3017 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018
Glenn Kasten05632a52012-01-03 14:22:33 -08003019 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3020 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003021 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003022 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003023 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003024 }
3025 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003027 // Delegate volume control to effect in track effect chain if needed
3028 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3029 // Do not ramp volume if volume is controlled by effect
3030 param = AudioMixer::VOLUME;
3031 track->mHasVolumeController = true;
3032 } else {
3033 // force no volume ramp when volume controller was just disabled or removed
3034 // from effect chain to avoid volume spike
3035 if (track->mHasVolumeController) {
3036 param = AudioMixer::VOLUME;
3037 }
3038 track->mHasVolumeController = false;
3039 }
3040
3041 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003042 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003043 vl = (vl + (1 << 11)) >> 12;
3044 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3045 vr = (vr + (1 << 11)) >> 12;
3046 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003047
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003048 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 -07003049
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003051 mAudioMixer->setBufferProvider(name, track);
3052 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003054 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3055 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3056 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003058 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059 AudioMixer::TRACK,
3060 AudioMixer::FORMAT, (void *)track->format());
3061 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003062 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003064 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003065 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003066 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003067 AudioMixer::RESAMPLE,
3068 AudioMixer::SAMPLE_RATE,
3069 (void *)(cblk->sampleRate));
3070 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003071 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 AudioMixer::TRACK,
3073 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3074 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003075 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 AudioMixer::TRACK,
3077 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3078
3079 // reset retry count
3080 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003081
Eric Laurent27741442012-01-17 19:20:12 -08003082 // If one track is ready, set the mixer ready if:
3083 // - the mixer was not ready during previous round OR
3084 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003085 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003086 mixerStatus != MIXER_TRACKS_ENABLED) {
3087 mixerStatus = MIXER_TRACKS_READY;
3088 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003090 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 if (track->isStopped()) {
3092 track->reset();
3093 }
Eric Laurent83faee02012-04-27 18:24:29 -07003094 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3095 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096 // We have consumed all the buffers of this track.
3097 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003098 // TODO: use actual buffer filling status instead of latency when available from
3099 // audio HAL
3100 size_t audioHALFrames =
3101 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3102 size_t framesWritten =
3103 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3104 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3105 tracksToRemove->add(track);
3106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 } else {
3108 // No buffers for this track. Give it a few chances to
3109 // fill a buffer, then remove it from active list.
3110 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003111 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003113 // indicate to client process that the track was disabled because of underrun;
3114 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003115 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003116 // If one track is not ready, mark the mixer also not ready if:
3117 // - the mixer was ready during previous round OR
3118 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003119 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003120 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121 mixerStatus = MIXER_TRACKS_ENABLED;
3122 }
3123 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003124 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 }
Glenn Kasten58912562012-04-03 10:45:00 -07003126
3127 } // local variable scope to avoid goto warning
3128track_is_ready: ;
3129
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130 }
3131
Glenn Kasten288ed212012-04-25 17:52:27 -07003132 // Push the new FastMixer state if necessary
3133 if (didModify) {
3134 state->mFastTracksGen++;
3135 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3136 if (kUseFastMixer == FastMixer_Dynamic &&
3137 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3138 state->mCommand = FastMixerState::COLD_IDLE;
3139 state->mColdFutexAddr = &mFastMixerFutex;
3140 state->mColdGen++;
3141 mFastMixerFutex = 0;
3142 if (kUseFastMixer == FastMixer_Dynamic) {
3143 mNormalSink = mOutputSink;
3144 }
3145 // If we go into cold idle, need to wait for acknowledgement
3146 // so that fast mixer stops doing I/O.
3147 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3148 }
3149 sq->end();
3150 }
3151 if (sq != NULL) {
3152 sq->end(didModify);
3153 sq->push(block);
3154 }
3155
3156 // Now perform the deferred reset on fast tracks that have stopped
3157 while (resetMask != 0) {
3158 size_t i = __builtin_ctz(resetMask);
3159 ALOG_ASSERT(i < count);
3160 resetMask &= ~(1 << i);
3161 sp<Track> t = mActiveTracks[i].promote();
3162 if (t == 0) continue;
3163 Track* track = t.get();
3164 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3165 track->reset();
3166 }
Glenn Kasten58912562012-04-03 10:45:00 -07003167
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 // remove all the tracks that need to be...
3169 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003170 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 for (size_t i=0 ; i<count ; i++) {
3172 const sp<Track>& track = tracksToRemove->itemAt(i);
3173 mActiveTracks.remove(track);
3174 if (track->mainBuffer() != mMixBuffer) {
3175 chain = getEffectChain_l(track->sessionId());
3176 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003177 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003178 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 }
3180 }
3181 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003182 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 }
3184 }
3185 }
3186
3187 // mix buffer must be cleared if all tracks are connected to an
3188 // effect chain as in this case the mixer will not write to
3189 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003190 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3191 // FIXME as a performance optimization, should remember previous zero status
3192 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 }
3194
Glenn Kasten58912562012-04-03 10:45:00 -07003195 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003196 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003197 if (fastTracks > 0) {
3198 mixerStatus = MIXER_TRACKS_READY;
3199 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 return mixerStatus;
3201}
3202
Glenn Kasten66fcab92012-02-24 14:59:21 -08003203/*
3204The derived values that are cached:
3205 - mixBufferSize from frame count * frame size
3206 - activeSleepTime from activeSleepTimeUs()
3207 - idleSleepTime from idleSleepTimeUs()
3208 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3209 - maxPeriod from frame count and sample rate (MIXER only)
3210
3211The parameters that affect these derived values are:
3212 - frame count
3213 - frame size
3214 - sample rate
3215 - device type: A2DP or not
3216 - device latency
3217 - format: PCM or not
3218 - active sleep time
3219 - idle sleep time
3220*/
3221
3222void AudioFlinger::PlaybackThread::cacheParameters_l()
3223{
Glenn Kasten58912562012-04-03 10:45:00 -07003224 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003225 activeSleepTime = activeSleepTimeUs();
3226 idleSleepTime = idleSleepTimeUs();
3227}
3228
Glenn Kastenfff6d712012-01-12 16:38:12 -08003229void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230{
Steve Block3856b092011-10-20 11:56:00 +01003231 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003232 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003234
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 size_t size = mTracks.size();
3236 for (size_t i = 0; i < size; i++) {
3237 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003238 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003239 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 }
3242 }
3243}
3244
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003246int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003248 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249}
3250
3251// deleteTrackName_l() must be called with ThreadBase::mLock held
3252void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3253{
Steve Block3856b092011-10-20 11:56:00 +01003254 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 mAudioMixer->deleteTrackName(name);
3256}
3257
3258// checkForNewParameters_l() must be called with ThreadBase::mLock held
3259bool AudioFlinger::MixerThread::checkForNewParameters_l()
3260{
Glenn Kasten58912562012-04-03 10:45:00 -07003261 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3262 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 bool reconfig = false;
3264
3265 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003266
3267 if (mFastMixer != NULL) {
3268 FastMixerStateQueue *sq = mFastMixer->sq();
3269 FastMixerState *state = sq->begin();
3270 if (!(state->mCommand & FastMixerState::IDLE)) {
3271 previousCommand = state->mCommand;
3272 state->mCommand = FastMixerState::HOT_IDLE;
3273 sq->end();
3274 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3275 } else {
3276 sq->end(false /*didModify*/);
3277 }
3278 }
3279
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 status_t status = NO_ERROR;
3281 String8 keyValuePair = mNewParameters[0];
3282 AudioParameter param = AudioParameter(keyValuePair);
3283 int value;
3284
3285 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3286 reconfig = true;
3287 }
3288 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003289 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 status = BAD_VALUE;
3291 } else {
3292 reconfig = true;
3293 }
3294 }
3295 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003296 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 status = BAD_VALUE;
3298 } else {
3299 reconfig = true;
3300 }
3301 }
3302 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3303 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003304 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 // if frame count is changed after track creation
3306 if (!mTracks.isEmpty()) {
3307 status = INVALID_OPERATION;
3308 } else {
3309 reconfig = true;
3310 }
3311 }
3312 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003313#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003314 // when changing the audio output device, call addBatteryData to notify
3315 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003316 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003317 uint32_t params = 0;
3318 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003319 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003320 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3321 }
3322
3323 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003324 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003325 // check if any other device (except speaker) is on
3326 if (value & deviceWithoutSpeaker ) {
3327 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3328 }
3329
3330 if (params != 0) {
3331 addBatteryData(params);
3332 }
3333 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003334#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003335
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 // forward device change to effects that have requested to be
3337 // aware of attached audio device.
3338 mDevice = (uint32_t)value;
3339 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003340 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 }
3342 }
3343
3344 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003345 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003346 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003348 mOutput->stream->common.standby(&mOutput->stream->common);
3349 mStandby = true;
3350 mBytesWritten = 0;
3351 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003352 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 }
3354 if (status == NO_ERROR && reconfig) {
3355 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003356 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3357 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003359 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003361 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 if (name < 0) break;
3363 mTracks[i]->mName = name;
3364 // limit track sample rate to 2 x new output sample rate
3365 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3366 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3367 }
3368 }
3369 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3370 }
3371 }
3372
3373 mNewParameters.removeAt(0);
3374
3375 mParamStatus = status;
3376 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003377 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3378 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003379 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 }
Glenn Kasten58912562012-04-03 10:45:00 -07003381
3382 if (!(previousCommand & FastMixerState::IDLE)) {
3383 ALOG_ASSERT(mFastMixer != NULL);
3384 FastMixerStateQueue *sq = mFastMixer->sq();
3385 FastMixerState *state = sq->begin();
3386 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3387 state->mCommand = previousCommand;
3388 sq->end();
3389 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3390 }
3391
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 return reconfig;
3393}
3394
3395status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3396{
3397 const size_t SIZE = 256;
3398 char buffer[SIZE];
3399 String8 result;
3400
3401 PlaybackThread::dumpInternals(fd, args);
3402
3403 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3404 result.append(buffer);
3405 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003406
3407 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3408 FastMixerDumpState copy = mFastMixerDumpState;
3409 copy.dump(fd);
3410
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 return NO_ERROR;
3412}
3413
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003414uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415{
Glenn Kasten58912562012-04-03 10:45:00 -07003416 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417}
3418
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003419uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003420{
Glenn Kasten58912562012-04-03 10:45:00 -07003421 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003422}
3423
Glenn Kasten66fcab92012-02-24 14:59:21 -08003424void AudioFlinger::MixerThread::cacheParameters_l()
3425{
3426 PlaybackThread::cacheParameters_l();
3427
3428 // FIXME: Relaxed timing because of a certain device that can't meet latency
3429 // Should be reduced to 2x after the vendor fixes the driver issue
3430 // increase threshold again due to low power audio mode. The way this warning
3431 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003432 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003433}
3434
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003436AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3437 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003438 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003439 // mLeftVolFloat, mRightVolFloat
3440 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442}
3443
3444AudioFlinger::DirectOutputThread::~DirectOutputThread()
3445{
3446}
3447
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003448AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3449 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003450)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003452 sp<Track> trackToRemove;
3453
Glenn Kastenfec279f2012-03-08 07:47:15 -08003454 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455
Glenn Kasten952eeb22012-03-06 11:30:57 -08003456 // find out which tracks need to be processed
3457 if (mActiveTracks.size() != 0) {
3458 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003459 // The track died recently
3460 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461
Glenn Kasten952eeb22012-03-06 11:30:57 -08003462 Track* const track = t.get();
3463 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464
Glenn Kasten952eeb22012-03-06 11:30:57 -08003465 // The first time a track is added we wait
3466 // for all its buffers to be filled before processing it
3467 if (cblk->framesReady() && track->isReady() &&
3468 !track->isPaused() && !track->isTerminated())
3469 {
3470 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471
Glenn Kasten952eeb22012-03-06 11:30:57 -08003472 if (track->mFillingUpStatus == Track::FS_FILLED) {
3473 track->mFillingUpStatus = Track::FS_ACTIVE;
3474 mLeftVolFloat = mRightVolFloat = 0;
3475 mLeftVolShort = mRightVolShort = 0;
3476 if (track->mState == TrackBase::RESUMING) {
3477 track->mState = TrackBase::ACTIVE;
3478 rampVolume = true;
3479 }
3480 } else if (cblk->server != 0) {
3481 // If the track is stopped before the first frame was mixed,
3482 // do not apply ramp
3483 rampVolume = true;
3484 }
3485 // compute volume for this track
3486 float left, right;
3487 if (track->isMuted() || mMasterMute || track->isPausing() ||
3488 mStreamTypes[track->streamType()].mute) {
3489 left = right = 0;
3490 if (track->isPausing()) {
3491 track->setPaused();
3492 }
3493 } else {
3494 float typeVolume = mStreamTypes[track->streamType()].volume;
3495 float v = mMasterVolume * typeVolume;
3496 uint32_t vlr = cblk->getVolumeLR();
3497 float v_clamped = v * (vlr & 0xFFFF);
3498 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3499 left = v_clamped/MAX_GAIN;
3500 v_clamped = v * (vlr >> 16);
3501 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3502 right = v_clamped/MAX_GAIN;
3503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504
Glenn Kasten952eeb22012-03-06 11:30:57 -08003505 if (left != mLeftVolFloat || right != mRightVolFloat) {
3506 mLeftVolFloat = left;
3507 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508
Glenn Kasten952eeb22012-03-06 11:30:57 -08003509 // If audio HAL implements volume control,
3510 // force software volume to nominal value
3511 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3512 left = 1.0f;
3513 right = 1.0f;
3514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515
Glenn Kasten952eeb22012-03-06 11:30:57 -08003516 // Convert volumes from float to 8.24
3517 uint32_t vl = (uint32_t)(left * (1 << 24));
3518 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519
Glenn Kasten952eeb22012-03-06 11:30:57 -08003520 // Delegate volume control to effect in track effect chain if needed
3521 // only one effect chain can be present on DirectOutputThread, so if
3522 // there is one, the track is connected to it
3523 if (!mEffectChains.isEmpty()) {
3524 // Do not ramp volume if volume is controlled by effect
3525 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526 rampVolume = false;
3527 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003528 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529
Glenn Kasten952eeb22012-03-06 11:30:57 -08003530 // Convert volumes from 8.24 to 4.12 format
3531 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3532 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3533 leftVol = (uint16_t)v_clamped;
3534 v_clamped = (vr + (1 << 11)) >> 12;
3535 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3536 rightVol = (uint16_t)v_clamped;
3537 } else {
3538 leftVol = mLeftVolShort;
3539 rightVol = mRightVolShort;
3540 rampVolume = false;
3541 }
3542
3543 // reset retry count
3544 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003545 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003546 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003547 } else {
3548 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3549 if (track->isStopped()) {
3550 track->reset();
3551 }
3552 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3553 // We have consumed all the buffers of this track.
3554 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003555 // TODO: implement behavior for compressed audio
3556 size_t audioHALFrames =
3557 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3558 size_t framesWritten =
3559 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3560 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3561 trackToRemove = track;
3562 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003563 } else {
3564 // No buffers for this track. Give it a few chances to
3565 // fill a buffer, then remove it from active list.
3566 if (--(track->mRetryCount) <= 0) {
3567 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3568 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003570 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 }
3572 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003573 }
3574 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003576 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003577 // remove all the tracks that need to be...
3578 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003579 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003580 mActiveTracks.remove(trackToRemove);
3581 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003582 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003583 trackToRemove->sessionId());
3584 mEffectChains[0]->decActiveTrackCnt();
3585 }
3586 if (trackToRemove->isTerminated()) {
3587 removeTrack_l(trackToRemove);
3588 }
3589 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590
Glenn Kastenfec279f2012-03-08 07:47:15 -08003591 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003592}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593
Glenn Kasten000f0e32012-03-01 17:10:56 -08003594void AudioFlinger::DirectOutputThread::threadLoop_mix()
3595{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003596 AudioBufferProvider::Buffer buffer;
3597 size_t frameCount = mFrameCount;
3598 int8_t *curBuf = (int8_t *)mMixBuffer;
3599 // output audio to hardware
3600 while (frameCount) {
3601 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003602 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003603 if (CC_UNLIKELY(buffer.raw == NULL)) {
3604 memset(curBuf, 0, frameCount * mFrameSize);
3605 break;
3606 }
3607 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3608 frameCount -= buffer.frameCount;
3609 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003610 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003611 }
3612 sleepTime = 0;
3613 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003614 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003615
3616 // apply volume
3617
3618 // Do not apply volume on compressed audio
3619 if (!audio_is_linear_pcm(mFormat)) {
3620 return;
3621 }
3622
3623 // convert to signed 16 bit before volume calculation
3624 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3625 size_t count = mFrameCount * mChannelCount;
3626 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3627 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003628 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003629 *dst-- = (int16_t)(*src--^0x80) << 8;
3630 }
3631 }
3632
3633 frameCount = mFrameCount;
3634 int16_t *out = mMixBuffer;
3635 if (rampVolume) {
3636 if (mChannelCount == 1) {
3637 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3638 int32_t vlInc = d / (int32_t)frameCount;
3639 int32_t vl = ((int32_t)mLeftVolShort << 16);
3640 do {
3641 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3642 out++;
3643 vl += vlInc;
3644 } while (--frameCount);
3645
3646 } else {
3647 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3648 int32_t vlInc = d / (int32_t)frameCount;
3649 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3650 int32_t vrInc = d / (int32_t)frameCount;
3651 int32_t vl = ((int32_t)mLeftVolShort << 16);
3652 int32_t vr = ((int32_t)mRightVolShort << 16);
3653 do {
3654 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3655 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3656 out += 2;
3657 vl += vlInc;
3658 vr += vrInc;
3659 } while (--frameCount);
3660 }
3661 } else {
3662 if (mChannelCount == 1) {
3663 do {
3664 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3665 out++;
3666 } while (--frameCount);
3667 } else {
3668 do {
3669 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3670 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3671 out += 2;
3672 } while (--frameCount);
3673 }
3674 }
3675
3676 // convert back to unsigned 8 bit after volume calculation
3677 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3678 size_t count = mFrameCount * mChannelCount;
3679 int16_t *src = mMixBuffer;
3680 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003681 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003682 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3683 }
3684 }
3685
3686 mLeftVolShort = leftVol;
3687 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003688}
3689
3690void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3691{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003692 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003693 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 sleepTime = activeSleepTime;
3695 } else {
3696 sleepTime = idleSleepTime;
3697 }
3698 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003699 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003700 sleepTime = 0;
3701 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702}
3703
3704// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003705int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706{
3707 return 0;
3708}
3709
3710// deleteTrackName_l() must be called with ThreadBase::mLock held
3711void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3712{
3713}
3714
3715// checkForNewParameters_l() must be called with ThreadBase::mLock held
3716bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3717{
3718 bool reconfig = false;
3719
3720 while (!mNewParameters.isEmpty()) {
3721 status_t status = NO_ERROR;
3722 String8 keyValuePair = mNewParameters[0];
3723 AudioParameter param = AudioParameter(keyValuePair);
3724 int value;
3725
3726 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3727 // do not accept frame count changes if tracks are open as the track buffer
3728 // size depends on frame count and correct behavior would not be garantied
3729 // if frame count is changed after track creation
3730 if (!mTracks.isEmpty()) {
3731 status = INVALID_OPERATION;
3732 } else {
3733 reconfig = true;
3734 }
3735 }
3736 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003737 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003738 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003739 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003740 mOutput->stream->common.standby(&mOutput->stream->common);
3741 mStandby = true;
3742 mBytesWritten = 0;
3743 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003744 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745 }
3746 if (status == NO_ERROR && reconfig) {
3747 readOutputParameters();
3748 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3749 }
3750 }
3751
3752 mNewParameters.removeAt(0);
3753
3754 mParamStatus = status;
3755 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003756 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3757 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003758 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759 }
3760 return reconfig;
3761}
3762
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003763uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764{
3765 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003766 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003767 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 } else {
3769 time = 10000;
3770 }
3771 return time;
3772}
3773
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003774uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775{
3776 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003777 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003778 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779 } else {
3780 time = 10000;
3781 }
3782 return time;
3783}
3784
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003785uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003786{
3787 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003788 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003789 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3790 } else {
3791 time = 10000;
3792 }
3793 return time;
3794}
3795
Glenn Kasten66fcab92012-02-24 14:59:21 -08003796void AudioFlinger::DirectOutputThread::cacheParameters_l()
3797{
3798 PlaybackThread::cacheParameters_l();
3799
3800 // use shorter standby delay as on normal output to release
3801 // hardware resources as soon as possible
3802 standbyDelay = microseconds(activeSleepTime*2);
3803}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003804
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805// ----------------------------------------------------------------------------
3806
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003807AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003808 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003809 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3810 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003811{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812 addOutputTrack(mainThread);
3813}
3814
3815AudioFlinger::DuplicatingThread::~DuplicatingThread()
3816{
3817 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3818 mOutputTracks[i]->destroy();
3819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820}
3821
Glenn Kasten000f0e32012-03-01 17:10:56 -08003822void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003824 // mix buffers...
3825 if (outputsReady(outputTracks)) {
3826 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3827 } else {
3828 memset(mMixBuffer, 0, mixBufferSize);
3829 }
3830 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003831 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003832}
3833
3834void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3835{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003836 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003837 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003838 sleepTime = activeSleepTime;
3839 } else {
3840 sleepTime = idleSleepTime;
3841 }
3842 } else if (mBytesWritten != 0) {
3843 // flush remaining overflow buffers in output tracks
3844 for (size_t i = 0; i < outputTracks.size(); i++) {
3845 if (outputTracks[i]->isActive()) {
3846 sleepTime = 0;
3847 writeFrames = 0;
3848 memset(mMixBuffer, 0, mixBufferSize);
3849 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003851 }
3852 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003853}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003854
Glenn Kasten000f0e32012-03-01 17:10:56 -08003855void AudioFlinger::DuplicatingThread::threadLoop_write()
3856{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003857 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003858 for (size_t i = 0; i < outputTracks.size(); i++) {
3859 outputTracks[i]->write(mMixBuffer, writeFrames);
3860 }
3861 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003862}
Glenn Kasten688a6402012-02-29 07:57:06 -08003863
Glenn Kasten000f0e32012-03-01 17:10:56 -08003864void AudioFlinger::DuplicatingThread::threadLoop_standby()
3865{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003866 // DuplicatingThread implements standby by stopping all tracks
3867 for (size_t i = 0; i < outputTracks.size(); i++) {
3868 outputTracks[i]->stop();
3869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870}
3871
Glenn Kastenfa26a852012-03-06 11:28:04 -08003872void AudioFlinger::DuplicatingThread::saveOutputTracks()
3873{
3874 outputTracks = mOutputTracks;
3875}
3876
3877void AudioFlinger::DuplicatingThread::clearOutputTracks()
3878{
3879 outputTracks.clear();
3880}
3881
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3883{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003884 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003885 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003886 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003887 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003888 this,
3889 mSampleRate,
3890 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003891 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 frameCount);
3893 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003894 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003896 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003897 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898 }
3899}
3900
3901void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3902{
3903 Mutex::Autolock _l(mLock);
3904 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003905 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 mOutputTracks[i]->destroy();
3907 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003908 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 return;
3910 }
3911 }
Steve Block3856b092011-10-20 11:56:00 +01003912 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913}
3914
Glenn Kasten438b0362012-03-06 11:24:48 -08003915// caller must hold mLock
3916void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917{
3918 mWaitTimeMs = UINT_MAX;
3919 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3920 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003921 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003922 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3923 if (waitTimeMs < mWaitTimeMs) {
3924 mWaitTimeMs = waitTimeMs;
3925 }
3926 }
3927 }
3928}
3929
3930
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003931bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932{
3933 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003934 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003936 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937 return false;
3938 }
3939 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3940 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003941 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942 return false;
3943 }
3944 }
3945 return true;
3946}
3947
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003948uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003949{
3950 return (mWaitTimeMs * 1000) / 2;
3951}
3952
Glenn Kasten66fcab92012-02-24 14:59:21 -08003953void AudioFlinger::DuplicatingThread::cacheParameters_l()
3954{
3955 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3956 updateWaitTime_l();
3957
3958 MixerThread::cacheParameters_l();
3959}
3960
Mathias Agopian65ab4712010-07-14 17:59:35 -07003961// ----------------------------------------------------------------------------
3962
3963// TrackBase constructor must be called with AudioFlinger::mLock held
3964AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003965 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966 const sp<Client>& client,
3967 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003968 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003969 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003970 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971 const sp<IMemory>& sharedBuffer,
3972 int sessionId)
3973 : RefBase(),
3974 mThread(thread),
3975 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003976 mCblk(NULL),
3977 // mBuffer
3978 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003979 mFrameCount(0),
3980 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003981 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003982 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003983 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003985 // mChannelCount
3986 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987{
Steve Block3856b092011-10-20 11:56:00 +01003988 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989
Steve Blockb8a80522011-12-20 16:23:08 +00003990 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003991 size_t size = sizeof(audio_track_cblk_t);
3992 uint8_t channelCount = popcount(channelMask);
3993 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3994 if (sharedBuffer == 0) {
3995 size += bufferSize;
3996 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003998 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999 mCblkMemory = client->heap()->allocate(size);
4000 if (mCblkMemory != 0) {
4001 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004002 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003 new(mCblk) audio_track_cblk_t();
4004 // clear all buffers
4005 mCblk->frameCount = frameCount;
4006 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004007// uncomment the following lines to quickly test 32-bit wraparound
4008// mCblk->user = 0xffff0000;
4009// mCblk->server = 0xffff0000;
4010// mCblk->userBase = 0xffff0000;
4011// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004012 mChannelCount = channelCount;
4013 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 if (sharedBuffer == 0) {
4015 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4016 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4017 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004018 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019 mCblk->flags = CBLK_UNDERRUN_ON;
4020 } else {
4021 mBuffer = sharedBuffer->pointer();
4022 }
4023 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4024 }
4025 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004026 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 client->heap()->dump("AudioTrack");
4028 return;
4029 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004030 } else {
4031 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004032 // construct the shared structure in-place.
4033 new(mCblk) audio_track_cblk_t();
4034 // clear all buffers
4035 mCblk->frameCount = frameCount;
4036 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004037// uncomment the following lines to quickly test 32-bit wraparound
4038// mCblk->user = 0xffff0000;
4039// mCblk->server = 0xffff0000;
4040// mCblk->userBase = 0xffff0000;
4041// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004042 mChannelCount = channelCount;
4043 mChannelMask = channelMask;
4044 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4045 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4046 // Force underrun condition to avoid false underrun callback until first data is
4047 // written to buffer (other flags are cleared)
4048 mCblk->flags = CBLK_UNDERRUN_ON;
4049 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051}
4052
4053AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4054{
Glenn Kastena0d68332012-01-27 16:47:15 -08004055 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004056 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004058 } else {
4059 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 }
4061 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004062 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004063 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004064 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004066 // If the client's reference count drops to zero, the associated destructor
4067 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4068 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069 mClient.clear();
4070 }
4071}
4072
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004073// AudioBufferProvider interface
4074// getNextBuffer() = 0;
4075// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4077{
Glenn Kastene0feee32011-12-13 11:53:26 -08004078 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004080 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004081 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082 buffer->frameCount = 0;
4083}
4084
4085bool AudioFlinger::ThreadBase::TrackBase::step() {
4086 bool result;
4087 audio_track_cblk_t* cblk = this->cblk();
4088
4089 result = cblk->stepServer(mFrameCount);
4090 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004091 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004092 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 }
4094 return result;
4095}
4096
4097void AudioFlinger::ThreadBase::TrackBase::reset() {
4098 audio_track_cblk_t* cblk = this->cblk();
4099
4100 cblk->user = 0;
4101 cblk->server = 0;
4102 cblk->userBase = 0;
4103 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004104 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004105 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106}
4107
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4109 return (int)mCblk->sampleRate;
4110}
4111
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4113 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004114 size_t frameSize = cblk->frameSize;
4115 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4116 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117
4118 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004119 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4120 "TrackBase::getBuffer buffer out of range:\n"
4121 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4122 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004124 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125
4126 return bufferStart;
4127}
4128
Eric Laurenta011e352012-03-29 15:51:43 -07004129status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4130{
4131 mSyncEvents.add(event);
4132 return NO_ERROR;
4133}
4134
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135// ----------------------------------------------------------------------------
4136
4137// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4138AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004139 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004141 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004143 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004144 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 int frameCount,
4146 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004147 int sessionId,
4148 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004149 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004150 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004151 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004152 // mRetryCount initialized later when needed
4153 mSharedBuffer(sharedBuffer),
4154 mStreamType(streamType),
4155 mName(-1), // see note below
4156 mMainBuffer(thread->mixBuffer()),
4157 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004158 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004159 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004160 mFlags(flags),
4161 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004162 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004163 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164{
4165 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4167 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004168 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004169 if (flags & IAudioFlinger::TRACK_FAST) {
4170 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4171 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4172 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4173 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004174 // FIXME This is too eager. We allocate a fast track index before the
4175 // fast track becomes active. Since fast tracks are a scarce resource,
4176 // this means we are potentially denying other more important fast tracks from
4177 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004178 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004179 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004180 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004181 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004182 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004183 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004184 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004185 if (mName < 0) {
4186 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004187 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4188 // then we leak a fast track index. Should swap these two sections, or better yet
4189 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004192 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193}
4194
4195AudioFlinger::PlaybackThread::Track::~Track()
4196{
Steve Block3856b092011-10-20 11:56:00 +01004197 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 sp<ThreadBase> thread = mThread.promote();
4199 if (thread != 0) {
4200 Mutex::Autolock _l(thread->mLock);
4201 mState = TERMINATED;
4202 }
4203}
4204
4205void AudioFlinger::PlaybackThread::Track::destroy()
4206{
4207 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4208 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004209 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 // we must acquire a strong reference on this Track before locking mLock
4211 // here so that the destructor is called only when exiting this function.
4212 // On the other hand, as long as Track::destroy() is only called by
4213 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4214 // this Track with its member mTrack.
4215 sp<Track> keep(this);
4216 { // scope for mLock
4217 sp<ThreadBase> thread = mThread.promote();
4218 if (thread != 0) {
4219 if (!isOutputTrack()) {
4220 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004221 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004222
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004223#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004224 // to track the speaker usage
4225 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004226#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 }
4228 AudioSystem::releaseOutput(thread->id());
4229 }
4230 Mutex::Autolock _l(thread->mLock);
4231 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4232 playbackThread->destroyTrack_l(this);
4233 }
4234 }
4235}
4236
Glenn Kasten288ed212012-04-25 17:52:27 -07004237/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4238{
Glenn Kastene213c862012-04-25 13:46:15 -07004239 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4240 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004241}
4242
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4244{
Glenn Kasten83d86532012-01-17 14:39:34 -08004245 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004246 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004247 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004248 } else {
4249 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4250 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004251 track_state state = mState;
4252 char stateChar;
4253 switch (state) {
4254 case IDLE:
4255 stateChar = 'I';
4256 break;
4257 case TERMINATED:
4258 stateChar = 'T';
4259 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004260 case STOPPING_1:
4261 stateChar = 's';
4262 break;
4263 case STOPPING_2:
4264 stateChar = '5';
4265 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004266 case STOPPED:
4267 stateChar = 'S';
4268 break;
4269 case RESUMING:
4270 stateChar = 'R';
4271 break;
4272 case ACTIVE:
4273 stateChar = 'A';
4274 break;
4275 case PAUSING:
4276 stateChar = 'p';
4277 break;
4278 case PAUSED:
4279 stateChar = 'P';
4280 break;
4281 default:
4282 stateChar = '?';
4283 break;
4284 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004285 char nowInUnderrun;
4286 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4287 case UNDERRUN_FULL:
4288 nowInUnderrun = ' ';
4289 break;
4290 case UNDERRUN_PARTIAL:
4291 nowInUnderrun = '<';
4292 break;
4293 case UNDERRUN_EMPTY:
4294 nowInUnderrun = '*';
4295 break;
4296 default:
4297 nowInUnderrun = '?';
4298 break;
4299 }
Glenn Kastene213c862012-04-25 13:46:15 -07004300 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4301 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004302 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 mStreamType,
4304 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004305 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 mSessionId,
4307 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004308 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004309 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 mMute,
4311 mFillingUpStatus,
4312 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004313 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4314 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 mCblk->server,
4316 mCblk->user,
4317 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004318 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004319 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004320 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004321 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322}
4323
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004324// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004325status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004326 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004328 audio_track_cblk_t* cblk = this->cblk();
4329 uint32_t framesReady;
4330 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004332 // Check if last stepServer failed, try to step now
4333 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004334 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4335 // Since the fast mixer is higher priority than client callback thread,
4336 // it does not result in priority inversion for client.
4337 // But a non-blocking solution would be preferable to avoid
4338 // fast mixer being unable to tryLock(), and
4339 // to avoid the extra context switches if the client wakes up,
4340 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004341 if (!step()) goto getNextBuffer_exit;
4342 ALOGV("stepServer recovered");
4343 mStepServerFailed = false;
4344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345
Glenn Kasten288ed212012-04-25 17:52:27 -07004346 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004347 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004349 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004350 uint32_t s = cblk->server;
4351 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4352
4353 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4354 if (framesReq > framesReady) {
4355 framesReq = framesReady;
4356 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004357 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004358 framesReq = bufferEnd - s;
4359 }
4360
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004361 buffer->raw = getBuffer(s, framesReq);
4362 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004364 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004366 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004367
4368getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004369 buffer->raw = NULL;
4370 buffer->frameCount = 0;
4371 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4372 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373}
4374
Glenn Kasten288ed212012-04-25 17:52:27 -07004375// Note that framesReady() takes a mutex on the control block using tryLock().
4376// This could result in priority inversion if framesReady() is called by the normal mixer,
4377// as the normal mixer thread runs at lower
4378// priority than the client's callback thread: there is a short window within framesReady()
4379// during which the normal mixer could be preempted, and the client callback would block.
4380// Another problem can occur if framesReady() is called by the fast mixer:
4381// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4382// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4383size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004384 return mCblk->framesReady();
4385}
4386
Glenn Kasten288ed212012-04-25 17:52:27 -07004387// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004389 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390
John Grossman4ff14ba2012-02-08 16:37:41 -08004391 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4393 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004394 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395 return true;
4396 }
4397 return false;
4398}
4399
Glenn Kasten3acbd052012-02-28 10:39:56 -08004400status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004401 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402{
4403 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004404 ALOGV("start(%d), calling pid %d session %d",
4405 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004406
Mathias Agopian65ab4712010-07-14 17:59:35 -07004407 sp<ThreadBase> thread = mThread.promote();
4408 if (thread != 0) {
4409 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004410 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411 // here the track could be either new, or restarted
4412 // in both cases "unstop" the track
4413 if (mState == PAUSED) {
4414 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004415 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004416 } else {
4417 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004418 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004419 }
4420
4421 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4422 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004423 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004425
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004426#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004427 // to track the speaker usage
4428 if (status == NO_ERROR) {
4429 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4430 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004431#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 }
4433 if (status == NO_ERROR) {
4434 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4435 playbackThread->addTrack_l(this);
4436 } else {
4437 mState = state;
4438 }
4439 } else {
4440 status = BAD_VALUE;
4441 }
4442 return status;
4443}
4444
4445void AudioFlinger::PlaybackThread::Track::stop()
4446{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004447 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 sp<ThreadBase> thread = mThread.promote();
4449 if (thread != 0) {
4450 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004451 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004452 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 // If the track is not active (PAUSED and buffers full), flush buffers
4454 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4455 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4456 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004457 mState = STOPPED;
4458 } else if (!isFastTrack()) {
4459 mState = STOPPED;
4460 } else {
4461 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4462 // and then to STOPPED and reset() when presentation is complete
4463 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004465 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466 }
4467 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4468 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004469 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004471
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004472#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004473 // to track the speaker usage
4474 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004475#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476 }
4477 }
4478}
4479
4480void AudioFlinger::PlaybackThread::Track::pause()
4481{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004482 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483 sp<ThreadBase> thread = mThread.promote();
4484 if (thread != 0) {
4485 Mutex::Autolock _l(thread->mLock);
4486 if (mState == ACTIVE || mState == RESUMING) {
4487 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004488 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 if (!isOutputTrack()) {
4490 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004491 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004493
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004494#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004495 // to track the speaker usage
4496 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004497#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 }
4499 }
4500 }
4501}
4502
4503void AudioFlinger::PlaybackThread::Track::flush()
4504{
Steve Block3856b092011-10-20 11:56:00 +01004505 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 sp<ThreadBase> thread = mThread.promote();
4507 if (thread != 0) {
4508 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004509 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4510 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 return;
4512 }
4513 // No point remaining in PAUSED state after a flush => go to
4514 // STOPPED state
4515 mState = STOPPED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004516 // do not reset the track if it is still in the process of being stopped or paused.
4517 // this will be done by prepareTracks_l() when the track is stopped.
Glenn Kastend08f48c2012-05-01 18:14:02 -07004518 // prepareTracks_l() will see mState == STOPPED, then
4519 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004520 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4521 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4522 reset();
4523 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 }
4525}
4526
4527void AudioFlinger::PlaybackThread::Track::reset()
4528{
4529 // Do not reset twice to avoid discarding data written just after a flush and before
4530 // the audioflinger thread detects the track is stopped.
4531 if (!mResetDone) {
4532 TrackBase::reset();
4533 // Force underrun condition to avoid false underrun callback until first data is
4534 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004535 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4536 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 mFillingUpStatus = FS_FILLING;
4538 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004539 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 }
4541}
4542
4543void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4544{
4545 mMute = muted;
4546}
4547
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4549{
4550 status_t status = DEAD_OBJECT;
4551 sp<ThreadBase> thread = mThread.promote();
4552 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004553 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4554 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 }
4556 return status;
4557}
4558
4559void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4560{
4561 mAuxEffectId = EffectId;
4562 mAuxBuffer = buffer;
4563}
4564
Eric Laurenta011e352012-03-29 15:51:43 -07004565bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4566 size_t audioHalFrames)
4567{
4568 // a track is considered presented when the total number of frames written to audio HAL
4569 // corresponds to the number of frames written when presentationComplete() is called for the
4570 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4571 if (mPresentationCompleteFrames == 0) {
4572 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4573 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4574 mPresentationCompleteFrames, audioHalFrames);
4575 }
4576 if (framesWritten >= mPresentationCompleteFrames) {
4577 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4578 mSessionId, framesWritten);
4579 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4580 mPresentationCompleteFrames = 0;
4581 return true;
4582 }
4583 return false;
4584}
4585
4586void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4587{
4588 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4589 if (mSyncEvents[i]->type() == type) {
4590 mSyncEvents[i]->trigger();
4591 mSyncEvents.removeAt(i);
4592 i--;
4593 }
4594 }
4595}
4596
Glenn Kasten58912562012-04-03 10:45:00 -07004597// implement VolumeBufferProvider interface
4598
4599uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4600{
4601 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4602 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4603 uint32_t vlr = mCblk->getVolumeLR();
4604 uint32_t vl = vlr & 0xFFFF;
4605 uint32_t vr = vlr >> 16;
4606 // track volumes come from shared memory, so can't be trusted and must be clamped
4607 if (vl > MAX_GAIN_INT) {
4608 vl = MAX_GAIN_INT;
4609 }
4610 if (vr > MAX_GAIN_INT) {
4611 vr = MAX_GAIN_INT;
4612 }
4613 // now apply the cached master volume and stream type volume;
4614 // this is trusted but lacks any synchronization or barrier so may be stale
4615 float v = mCachedVolume;
4616 vl *= v;
4617 vr *= v;
4618 // re-combine into U4.16
4619 vlr = (vr << 16) | (vl & 0xFFFF);
4620 // FIXME look at mute, pause, and stop flags
4621 return vlr;
4622}
Eric Laurenta011e352012-03-29 15:51:43 -07004623
John Grossman4ff14ba2012-02-08 16:37:41 -08004624// timed audio tracks
4625
4626sp<AudioFlinger::PlaybackThread::TimedTrack>
4627AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004628 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004629 const sp<Client>& client,
4630 audio_stream_type_t streamType,
4631 uint32_t sampleRate,
4632 audio_format_t format,
4633 uint32_t channelMask,
4634 int frameCount,
4635 const sp<IMemory>& sharedBuffer,
4636 int sessionId) {
4637 if (!client->reserveTimedTrack())
4638 return NULL;
4639
Glenn Kastena0356762012-03-19 10:38:51 -07004640 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004641 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4642 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004643}
4644
4645AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004646 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004647 const sp<Client>& client,
4648 audio_stream_type_t streamType,
4649 uint32_t sampleRate,
4650 audio_format_t format,
4651 uint32_t channelMask,
4652 int frameCount,
4653 const sp<IMemory>& sharedBuffer,
4654 int sessionId)
4655 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004656 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004657 mQueueHeadInFlight(false),
4658 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004659 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004660 mTimedSilenceBuffer(NULL),
4661 mTimedSilenceBufferSize(0),
4662 mTimedAudioOutputOnTime(false),
4663 mMediaTimeTransformValid(false)
4664{
4665 LocalClock lc;
4666 mLocalTimeFreq = lc.getLocalFreq();
4667
4668 mLocalTimeToSampleTransform.a_zero = 0;
4669 mLocalTimeToSampleTransform.b_zero = 0;
4670 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4671 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4672 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4673 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004674
4675 mMediaTimeToSampleTransform.a_zero = 0;
4676 mMediaTimeToSampleTransform.b_zero = 0;
4677 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4678 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4679 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4680 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004681}
4682
4683AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4684 mClient->releaseTimedTrack();
4685 delete [] mTimedSilenceBuffer;
4686}
4687
4688status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4689 size_t size, sp<IMemory>* buffer) {
4690
4691 Mutex::Autolock _l(mTimedBufferQueueLock);
4692
4693 trimTimedBufferQueue_l();
4694
4695 // lazily initialize the shared memory heap for timed buffers
4696 if (mTimedMemoryDealer == NULL) {
4697 const int kTimedBufferHeapSize = 512 << 10;
4698
4699 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4700 "AudioFlingerTimed");
4701 if (mTimedMemoryDealer == NULL)
4702 return NO_MEMORY;
4703 }
4704
4705 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4706 if (newBuffer == NULL) {
4707 newBuffer = mTimedMemoryDealer->allocate(size);
4708 if (newBuffer == NULL)
4709 return NO_MEMORY;
4710 }
4711
4712 *buffer = newBuffer;
4713 return NO_ERROR;
4714}
4715
4716// caller must hold mTimedBufferQueueLock
4717void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4718 int64_t mediaTimeNow;
4719 {
4720 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4721 if (!mMediaTimeTransformValid)
4722 return;
4723
4724 int64_t targetTimeNow;
4725 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4726 ? mCCHelper.getCommonTime(&targetTimeNow)
4727 : mCCHelper.getLocalTime(&targetTimeNow);
4728
4729 if (OK != res)
4730 return;
4731
4732 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4733 &mediaTimeNow)) {
4734 return;
4735 }
4736 }
4737
John Grossman1c345192012-03-27 14:00:17 -07004738 size_t trimEnd;
4739 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004740 int64_t bufEnd;
4741
John Grossmanc95cfbb2012-04-12 11:53:11 -07004742 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4743 // We have a next buffer. Just use its PTS as the PTS of the frame
4744 // following the last frame in this buffer. If the stream is sparse
4745 // (ie, there are deliberate gaps left in the stream which should be
4746 // filled with silence by the TimedAudioTrack), then this can result
4747 // in one extra buffer being left un-trimmed when it could have
4748 // been. In general, this is not typical, and we would rather
4749 // optimized away the TS calculation below for the more common case
4750 // where PTSes are contiguous.
4751 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4752 } else {
4753 // We have no next buffer. Compute the PTS of the frame following
4754 // the last frame in this buffer by computing the duration of of
4755 // this frame in media time units and adding it to the PTS of the
4756 // buffer.
4757 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4758 / mCblk->frameSize;
4759
4760 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4761 &bufEnd)) {
4762 ALOGE("Failed to convert frame count of %lld to media time"
4763 " duration" " (scale factor %d/%u) in %s",
4764 frameCount,
4765 mMediaTimeToSampleTransform.a_to_b_numer,
4766 mMediaTimeToSampleTransform.a_to_b_denom,
4767 __PRETTY_FUNCTION__);
4768 break;
4769 }
4770 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004771 }
John Grossman9fbdee12012-03-26 17:51:46 -07004772
4773 if (bufEnd > mediaTimeNow)
4774 break;
4775
4776 // Is the buffer we want to use in the middle of a mix operation right
4777 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4778 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004779 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004780 mTrimQueueHeadOnRelease = true;
4781 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004782 }
4783
John Grossman9fbdee12012-03-26 17:51:46 -07004784 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004785 if (trimStart < trimEnd) {
4786 // Update the bookkeeping for framesReady()
4787 for (size_t i = trimStart; i < trimEnd; ++i) {
4788 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4789 }
4790
4791 // Now actually remove the buffers from the queue.
4792 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004793 }
4794}
4795
John Grossman1c345192012-03-27 14:00:17 -07004796void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4797 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004798 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4799 "%s called (reason \"%s\"), but timed buffer queue has no"
4800 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004801
4802 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4803 mTimedBufferQueue.removeAt(0);
4804}
4805
4806void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4807 const TimedBuffer& buf,
4808 const char* logTag) {
4809 uint32_t bufBytes = buf.buffer()->size();
4810 uint32_t consumedAlready = buf.position();
4811
Eric Laurentb388e532012-04-14 13:32:48 -07004812 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004813 "Bad bookkeeping while updating frames pending. Timed buffer is"
4814 " only %u bytes long, but claims to have consumed %u"
4815 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004816 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004817
4818 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004819 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4820 "Bad bookkeeping while updating frames pending. Should have at"
4821 " least %u queued frames, but we think we have only %u. (update"
4822 " reason: \"%s\")",
4823 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004824
4825 mFramesPendingInQueue -= bufFrames;
4826}
4827
John Grossman4ff14ba2012-02-08 16:37:41 -08004828status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4829 const sp<IMemory>& buffer, int64_t pts) {
4830
4831 {
4832 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4833 if (!mMediaTimeTransformValid)
4834 return INVALID_OPERATION;
4835 }
4836
4837 Mutex::Autolock _l(mTimedBufferQueueLock);
4838
John Grossman1c345192012-03-27 14:00:17 -07004839 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4840 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004841 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4842
4843 return NO_ERROR;
4844}
4845
4846status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4847 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4848
John Grossman1c345192012-03-27 14:00:17 -07004849 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4850 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4851 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004852
4853 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4854 target == TimedAudioTrack::COMMON_TIME)) {
4855 return BAD_VALUE;
4856 }
4857
4858 Mutex::Autolock lock(mMediaTimeTransformLock);
4859 mMediaTimeTransform = xform;
4860 mMediaTimeTransformTarget = target;
4861 mMediaTimeTransformValid = true;
4862
4863 return NO_ERROR;
4864}
4865
4866#define min(a, b) ((a) < (b) ? (a) : (b))
4867
4868// implementation of getNextBuffer for tracks whose buffers have timestamps
4869status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4870 AudioBufferProvider::Buffer* buffer, int64_t pts)
4871{
4872 if (pts == AudioBufferProvider::kInvalidPTS) {
4873 buffer->raw = 0;
4874 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004875 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004876 return INVALID_OPERATION;
4877 }
4878
John Grossman4ff14ba2012-02-08 16:37:41 -08004879 Mutex::Autolock _l(mTimedBufferQueueLock);
4880
John Grossman9fbdee12012-03-26 17:51:46 -07004881 ALOG_ASSERT(!mQueueHeadInFlight,
4882 "getNextBuffer called without releaseBuffer!");
4883
John Grossman4ff14ba2012-02-08 16:37:41 -08004884 while (true) {
4885
4886 // if we have no timed buffers, then fail
4887 if (mTimedBufferQueue.isEmpty()) {
4888 buffer->raw = 0;
4889 buffer->frameCount = 0;
4890 return NOT_ENOUGH_DATA;
4891 }
4892
4893 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4894
4895 // calculate the PTS of the head of the timed buffer queue expressed in
4896 // local time
4897 int64_t headLocalPTS;
4898 {
4899 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4900
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004901 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004902
4903 if (mMediaTimeTransform.a_to_b_denom == 0) {
4904 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004905 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004906 return NO_ERROR;
4907 }
4908
4909 int64_t transformedPTS;
4910 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4911 &transformedPTS)) {
4912 // the transform failed. this shouldn't happen, but if it does
4913 // then just drop this buffer
4914 ALOGW("timedGetNextBuffer transform failed");
4915 buffer->raw = 0;
4916 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004917 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004918 return NO_ERROR;
4919 }
4920
4921 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4922 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4923 &headLocalPTS)) {
4924 buffer->raw = 0;
4925 buffer->frameCount = 0;
4926 return INVALID_OPERATION;
4927 }
4928 } else {
4929 headLocalPTS = transformedPTS;
4930 }
4931 }
4932
4933 // adjust the head buffer's PTS to reflect the portion of the head buffer
4934 // that has already been consumed
4935 int64_t effectivePTS = headLocalPTS +
4936 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4937
4938 // Calculate the delta in samples between the head of the input buffer
4939 // queue and the start of the next output buffer that will be written.
4940 // If the transformation fails because of over or underflow, it means
4941 // that the sample's position in the output stream is so far out of
4942 // whack that it should just be dropped.
4943 int64_t sampleDelta;
4944 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4945 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004946 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4947 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004948 continue;
4949 }
4950 if (!mLocalTimeToSampleTransform.doForwardTransform(
4951 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004952 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004953 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004954 continue;
4955 }
4956
John Grossman1c345192012-03-27 14:00:17 -07004957 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4958 " sampleDelta=[%d.%08x]",
4959 head.pts(), head.position(), pts,
4960 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4961 + (sampleDelta >> 32)),
4962 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004963
4964 // if the delta between the ideal placement for the next input sample and
4965 // the current output position is within this threshold, then we will
4966 // concatenate the next input samples to the previous output
4967 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004968 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004969
4970 // if this is the first buffer of audio that we're emitting from this track
4971 // then it should be almost exactly on time.
4972 const int64_t kSampleStartupThreshold = 1LL << 32;
4973
4974 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004975 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004976 // the next input is close enough to being on time, so concatenate it
4977 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004978 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004979
John Grossman1c345192012-03-27 14:00:17 -07004980 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4981 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004982 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004983 }
4984
4985 // Looks like our output is not on time. Reset our on timed status.
4986 // Next time we mix samples from our input queue, then should be within
4987 // the StartupThreshold.
4988 mTimedAudioOutputOnTime = false;
4989 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004990 // the gap between the current output position and the proper start of
4991 // the next input sample is too big, so fill it with silence
4992 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4993
John Grossman9fbdee12012-03-26 17:51:46 -07004994 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004995 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4996 return NO_ERROR;
4997 } else {
4998 // the next input sample is late
4999 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5000 size_t onTimeSamplePosition =
5001 head.position() + lateFrames * mCblk->frameSize;
5002
5003 if (onTimeSamplePosition > head.buffer()->size()) {
5004 // all the remaining samples in the head are too late, so
5005 // drop it and move on
5006 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005007 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005008 continue;
5009 } else {
5010 // skip over the late samples
5011 head.setPosition(onTimeSamplePosition);
5012
5013 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005014 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005015
5016 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5017 return NO_ERROR;
5018 }
5019 }
5020 }
5021}
5022
5023// Yield samples from the timed buffer queue head up to the given output
5024// buffer's capacity.
5025//
5026// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005027void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005028 AudioBufferProvider::Buffer* buffer) {
5029
5030 const TimedBuffer& head = mTimedBufferQueue[0];
5031
5032 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5033 head.position());
5034
5035 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5036 mCblk->frameSize);
5037 size_t framesRequested = buffer->frameCount;
5038 buffer->frameCount = min(framesLeftInHead, framesRequested);
5039
John Grossman9fbdee12012-03-26 17:51:46 -07005040 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005041 mTimedAudioOutputOnTime = true;
5042}
5043
5044// Yield samples of silence up to the given output buffer's capacity
5045//
5046// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005047void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005048 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5049
5050 // lazily allocate a buffer filled with silence
5051 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5052 delete [] mTimedSilenceBuffer;
5053 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5054 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5055 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5056 }
5057
5058 buffer->raw = mTimedSilenceBuffer;
5059 size_t framesRequested = buffer->frameCount;
5060 buffer->frameCount = min(numFrames, framesRequested);
5061
5062 mTimedAudioOutputOnTime = false;
5063}
5064
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005065// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005066void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5067 AudioBufferProvider::Buffer* buffer) {
5068
5069 Mutex::Autolock _l(mTimedBufferQueueLock);
5070
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005071 // If the buffer which was just released is part of the buffer at the head
5072 // of the queue, be sure to update the amt of the buffer which has been
5073 // consumed. If the buffer being returned is not part of the head of the
5074 // queue, its either because the buffer is part of the silence buffer, or
5075 // because the head of the timed queue was trimmed after the mixer called
5076 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005077 if (buffer->raw == mTimedSilenceBuffer) {
5078 ALOG_ASSERT(!mQueueHeadInFlight,
5079 "Queue head in flight during release of silence buffer!");
5080 goto done;
5081 }
5082
5083 ALOG_ASSERT(mQueueHeadInFlight,
5084 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5085 " head in flight.");
5086
5087 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005088 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005089
5090 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005091 void* end = reinterpret_cast<void*>(
5092 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5093 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005094
John Grossman9fbdee12012-03-26 17:51:46 -07005095 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5096 "released buffer not within the head of the timed buffer"
5097 " queue; qHead = [%p, %p], released buffer = %p",
5098 start, end, buffer->raw);
5099
5100 head.setPosition(head.position() +
5101 (buffer->frameCount * mCblk->frameSize));
5102 mQueueHeadInFlight = false;
5103
John Grossman1c345192012-03-27 14:00:17 -07005104 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5105 "Bad bookkeeping during releaseBuffer! Should have at"
5106 " least %u queued frames, but we think we have only %u",
5107 buffer->frameCount, mFramesPendingInQueue);
5108
5109 mFramesPendingInQueue -= buffer->frameCount;
5110
John Grossman9fbdee12012-03-26 17:51:46 -07005111 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5112 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005113 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005114 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005115 }
John Grossman9fbdee12012-03-26 17:51:46 -07005116 } else {
5117 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5118 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005119 }
5120
John Grossman9fbdee12012-03-26 17:51:46 -07005121done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005122 buffer->raw = 0;
5123 buffer->frameCount = 0;
5124}
5125
Glenn Kasten288ed212012-04-25 17:52:27 -07005126size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005127 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005128 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005129}
5130
5131AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5132 : mPTS(0), mPosition(0) {}
5133
5134AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5135 const sp<IMemory>& buffer, int64_t pts)
5136 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5137
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138// ----------------------------------------------------------------------------
5139
5140// RecordTrack constructor must be called with AudioFlinger::mLock held
5141AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005142 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005143 const sp<Client>& client,
5144 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005145 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005146 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148 int sessionId)
5149 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005150 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 mOverflow(false)
5152{
5153 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005154 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5155 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5156 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5157 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5158 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5159 } else {
5160 mCblk->frameSize = sizeof(int8_t);
5161 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 }
5163}
5164
5165AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5166{
5167 sp<ThreadBase> thread = mThread.promote();
5168 if (thread != 0) {
5169 AudioSystem::releaseInput(thread->id());
5170 }
5171}
5172
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005173// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005174status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175{
5176 audio_track_cblk_t* cblk = this->cblk();
5177 uint32_t framesAvail;
5178 uint32_t framesReq = buffer->frameCount;
5179
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005180 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005181 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005183 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005184 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005185 }
5186
5187 framesAvail = cblk->framesAvailable_l();
5188
Glenn Kastenf6b16782011-12-15 09:51:17 -08005189 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 uint32_t s = cblk->server;
5191 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5192
5193 if (framesReq > framesAvail) {
5194 framesReq = framesAvail;
5195 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005196 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005197 framesReq = bufferEnd - s;
5198 }
5199
5200 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005201 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202
5203 buffer->frameCount = framesReq;
5204 return NO_ERROR;
5205 }
5206
5207getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005208 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005209 buffer->frameCount = 0;
5210 return NOT_ENOUGH_DATA;
5211}
5212
Glenn Kasten3acbd052012-02-28 10:39:56 -08005213status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005214 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005215{
5216 sp<ThreadBase> thread = mThread.promote();
5217 if (thread != 0) {
5218 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005219 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005220 } else {
5221 return BAD_VALUE;
5222 }
5223}
5224
5225void AudioFlinger::RecordThread::RecordTrack::stop()
5226{
5227 sp<ThreadBase> thread = mThread.promote();
5228 if (thread != 0) {
5229 RecordThread *recordThread = (RecordThread *)thread.get();
5230 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005231 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005232 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005233 // read from buffer
5234 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005235 }
5236}
5237
5238void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5239{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005240 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005241 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005242 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005243 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005244 mSessionId,
5245 mFrameCount,
5246 mState,
5247 mCblk->sampleRate,
5248 mCblk->server,
5249 mCblk->user);
5250}
5251
5252
5253// ----------------------------------------------------------------------------
5254
5255AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005256 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005257 DuplicatingThread *sourceThread,
5258 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005259 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005260 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005262 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5263 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264 mActive(false), mSourceThread(sourceThread)
5265{
5266
Mathias Agopian65ab4712010-07-14 17:59:35 -07005267 if (mCblk != NULL) {
5268 mCblk->flags |= CBLK_DIRECTION_OUT;
5269 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005270 mOutBuffer.frameCount = 0;
5271 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005272 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005273 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5274 mCblk, mBuffer, mCblk->buffers,
5275 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005277 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005278 }
5279}
5280
5281AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5282{
5283 clearBufferQueue();
5284}
5285
Glenn Kasten3acbd052012-02-28 10:39:56 -08005286status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005287 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005289 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005290 if (status != NO_ERROR) {
5291 return status;
5292 }
5293
5294 mActive = true;
5295 mRetryCount = 127;
5296 return status;
5297}
5298
5299void AudioFlinger::PlaybackThread::OutputTrack::stop()
5300{
5301 Track::stop();
5302 clearBufferQueue();
5303 mOutBuffer.frameCount = 0;
5304 mActive = false;
5305}
5306
5307bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5308{
5309 Buffer *pInBuffer;
5310 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005311 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312 bool outputBufferFull = false;
5313 inBuffer.frameCount = frames;
5314 inBuffer.i16 = data;
5315
5316 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5317
5318 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005319 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320 sp<ThreadBase> thread = mThread.promote();
5321 if (thread != 0) {
5322 MixerThread *mixerThread = (MixerThread *)thread.get();
5323 if (mCblk->frameCount > frames){
5324 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5325 uint32_t startFrames = (mCblk->frameCount - frames);
5326 pInBuffer = new Buffer;
5327 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5328 pInBuffer->frameCount = startFrames;
5329 pInBuffer->i16 = pInBuffer->mBuffer;
5330 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5331 mBufferQueue.add(pInBuffer);
5332 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005333 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 }
5335 }
5336 }
5337 }
5338
5339 while (waitTimeLeftMs) {
5340 // First write pending buffers, then new data
5341 if (mBufferQueue.size()) {
5342 pInBuffer = mBufferQueue.itemAt(0);
5343 } else {
5344 pInBuffer = &inBuffer;
5345 }
5346
5347 if (pInBuffer->frameCount == 0) {
5348 break;
5349 }
5350
5351 if (mOutBuffer.frameCount == 0) {
5352 mOutBuffer.frameCount = pInBuffer->frameCount;
5353 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005354 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005355 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 outputBufferFull = true;
5357 break;
5358 }
5359 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5360 if (waitTimeLeftMs >= waitTimeMs) {
5361 waitTimeLeftMs -= waitTimeMs;
5362 } else {
5363 waitTimeLeftMs = 0;
5364 }
5365 }
5366
5367 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5368 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5369 mCblk->stepUser(outFrames);
5370 pInBuffer->frameCount -= outFrames;
5371 pInBuffer->i16 += outFrames * channelCount;
5372 mOutBuffer.frameCount -= outFrames;
5373 mOutBuffer.i16 += outFrames * channelCount;
5374
5375 if (pInBuffer->frameCount == 0) {
5376 if (mBufferQueue.size()) {
5377 mBufferQueue.removeAt(0);
5378 delete [] pInBuffer->mBuffer;
5379 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005380 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005381 } else {
5382 break;
5383 }
5384 }
5385 }
5386
5387 // If we could not write all frames, allocate a buffer and queue it for next time.
5388 if (inBuffer.frameCount) {
5389 sp<ThreadBase> thread = mThread.promote();
5390 if (thread != 0 && !thread->standby()) {
5391 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5392 pInBuffer = new Buffer;
5393 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5394 pInBuffer->frameCount = inBuffer.frameCount;
5395 pInBuffer->i16 = pInBuffer->mBuffer;
5396 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5397 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005398 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005400 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005401 }
5402 }
5403 }
5404
5405 // Calling write() with a 0 length buffer, means that no more data will be written:
5406 // If no more buffers are pending, fill output track buffer to make sure it is started
5407 // by output mixer.
5408 if (frames == 0 && mBufferQueue.size() == 0) {
5409 if (mCblk->user < mCblk->frameCount) {
5410 frames = mCblk->frameCount - mCblk->user;
5411 pInBuffer = new Buffer;
5412 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5413 pInBuffer->frameCount = frames;
5414 pInBuffer->i16 = pInBuffer->mBuffer;
5415 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5416 mBufferQueue.add(pInBuffer);
5417 } else if (mActive) {
5418 stop();
5419 }
5420 }
5421
5422 return outputBufferFull;
5423}
5424
5425status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5426{
5427 int active;
5428 status_t result;
5429 audio_track_cblk_t* cblk = mCblk;
5430 uint32_t framesReq = buffer->frameCount;
5431
Steve Block3856b092011-10-20 11:56:00 +01005432// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433 buffer->frameCount = 0;
5434
5435 uint32_t framesAvail = cblk->framesAvailable();
5436
5437
5438 if (framesAvail == 0) {
5439 Mutex::Autolock _l(cblk->lock);
5440 goto start_loop_here;
5441 while (framesAvail == 0) {
5442 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005443 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005444 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005445 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 }
5447 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5448 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005449 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 }
5451 // read the server count again
5452 start_loop_here:
5453 framesAvail = cblk->framesAvailable_l();
5454 }
5455 }
5456
5457// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005458// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459// }
5460
5461 if (framesReq > framesAvail) {
5462 framesReq = framesAvail;
5463 }
5464
5465 uint32_t u = cblk->user;
5466 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5467
Marco Nelissena1472d92012-03-30 14:36:54 -07005468 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 framesReq = bufferEnd - u;
5470 }
5471
5472 buffer->frameCount = framesReq;
5473 buffer->raw = (void *)cblk->buffer(u);
5474 return NO_ERROR;
5475}
5476
5477
5478void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5479{
5480 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481
5482 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005483 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 delete [] pBuffer->mBuffer;
5485 delete pBuffer;
5486 }
5487 mBufferQueue.clear();
5488}
5489
5490// ----------------------------------------------------------------------------
5491
5492AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5493 : RefBase(),
5494 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005495 // 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 -07005496 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005497 mPid(pid),
5498 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499{
5500 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5501}
5502
5503// Client destructor must be called with AudioFlinger::mLock held
5504AudioFlinger::Client::~Client()
5505{
5506 mAudioFlinger->removeClient_l(mPid);
5507}
5508
Glenn Kasten435dbe62012-01-30 10:15:48 -08005509sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510{
5511 return mMemoryDealer;
5512}
5513
John Grossman4ff14ba2012-02-08 16:37:41 -08005514// Reserve one of the limited slots for a timed audio track associated
5515// with this client
5516bool AudioFlinger::Client::reserveTimedTrack()
5517{
5518 const int kMaxTimedTracksPerClient = 4;
5519
5520 Mutex::Autolock _l(mTimedTrackLock);
5521
5522 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5523 ALOGW("can not create timed track - pid %d has exceeded the limit",
5524 mPid);
5525 return false;
5526 }
5527
5528 mTimedTrackCount++;
5529 return true;
5530}
5531
5532// Release a slot for a timed audio track
5533void AudioFlinger::Client::releaseTimedTrack()
5534{
5535 Mutex::Autolock _l(mTimedTrackLock);
5536 mTimedTrackCount--;
5537}
5538
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539// ----------------------------------------------------------------------------
5540
5541AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5542 const sp<IAudioFlingerClient>& client,
5543 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005544 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545{
5546}
5547
5548AudioFlinger::NotificationClient::~NotificationClient()
5549{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550}
5551
5552void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5553{
5554 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005555 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556}
5557
5558// ----------------------------------------------------------------------------
5559
5560AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5561 : BnAudioTrack(),
5562 mTrack(track)
5563{
5564}
5565
5566AudioFlinger::TrackHandle::~TrackHandle() {
5567 // just stop the track on deletion, associated resources
5568 // will be freed from the main thread once all pending buffers have
5569 // been played. Unless it's not in the active track list, in which
5570 // case we free everything now...
5571 mTrack->destroy();
5572}
5573
Glenn Kasten90716c52012-01-26 13:40:12 -08005574sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5575 return mTrack->getCblk();
5576}
5577
Glenn Kasten3acbd052012-02-28 10:39:56 -08005578status_t AudioFlinger::TrackHandle::start() {
5579 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005580}
5581
5582void AudioFlinger::TrackHandle::stop() {
5583 mTrack->stop();
5584}
5585
5586void AudioFlinger::TrackHandle::flush() {
5587 mTrack->flush();
5588}
5589
5590void AudioFlinger::TrackHandle::mute(bool e) {
5591 mTrack->mute(e);
5592}
5593
5594void AudioFlinger::TrackHandle::pause() {
5595 mTrack->pause();
5596}
5597
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5599{
5600 return mTrack->attachAuxEffect(EffectId);
5601}
5602
John Grossman4ff14ba2012-02-08 16:37:41 -08005603status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5604 sp<IMemory>* buffer) {
5605 if (!mTrack->isTimedTrack())
5606 return INVALID_OPERATION;
5607
5608 PlaybackThread::TimedTrack* tt =
5609 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5610 return tt->allocateTimedBuffer(size, buffer);
5611}
5612
5613status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5614 int64_t pts) {
5615 if (!mTrack->isTimedTrack())
5616 return INVALID_OPERATION;
5617
5618 PlaybackThread::TimedTrack* tt =
5619 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5620 return tt->queueTimedBuffer(buffer, pts);
5621}
5622
5623status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5624 const LinearTransform& xform, int target) {
5625
5626 if (!mTrack->isTimedTrack())
5627 return INVALID_OPERATION;
5628
5629 PlaybackThread::TimedTrack* tt =
5630 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5631 return tt->setMediaTimeTransform(
5632 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5633}
5634
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635status_t AudioFlinger::TrackHandle::onTransact(
5636 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5637{
5638 return BnAudioTrack::onTransact(code, data, reply, flags);
5639}
5640
5641// ----------------------------------------------------------------------------
5642
5643sp<IAudioRecord> AudioFlinger::openRecord(
5644 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005645 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005647 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005648 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005650 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 int *sessionId,
5652 status_t *status)
5653{
5654 sp<RecordThread::RecordTrack> recordTrack;
5655 sp<RecordHandle> recordHandle;
5656 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657 status_t lStatus;
5658 RecordThread *thread;
5659 size_t inFrameCount;
5660 int lSessionId;
5661
5662 // check calling permissions
5663 if (!recordingAllowed()) {
5664 lStatus = PERMISSION_DENIED;
5665 goto Exit;
5666 }
5667
5668 // add client to list
5669 { // scope for mLock
5670 Mutex::Autolock _l(mLock);
5671 thread = checkRecordThread_l(input);
5672 if (thread == NULL) {
5673 lStatus = BAD_VALUE;
5674 goto Exit;
5675 }
5676
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005677 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678
5679 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005680 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681 lSessionId = *sessionId;
5682 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005683 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005684 if (sessionId != NULL) {
5685 *sessionId = lSessionId;
5686 }
5687 }
5688 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005689 recordTrack = thread->createRecordTrack_l(client,
5690 sampleRate,
5691 format,
5692 channelMask,
5693 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005694 lSessionId,
5695 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005697 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5699 // destructor is called by the TrackBase destructor with mLock held
5700 client.clear();
5701 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702 goto Exit;
5703 }
5704
5705 // return to handle to client
5706 recordHandle = new RecordHandle(recordTrack);
5707 lStatus = NO_ERROR;
5708
5709Exit:
5710 if (status) {
5711 *status = lStatus;
5712 }
5713 return recordHandle;
5714}
5715
5716// ----------------------------------------------------------------------------
5717
5718AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5719 : BnAudioRecord(),
5720 mRecordTrack(recordTrack)
5721{
5722}
5723
5724AudioFlinger::RecordHandle::~RecordHandle() {
5725 stop();
5726}
5727
Glenn Kasten90716c52012-01-26 13:40:12 -08005728sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5729 return mRecordTrack->getCblk();
5730}
5731
Glenn Kasten3acbd052012-02-28 10:39:56 -08005732status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005733 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005734 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735}
5736
5737void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005738 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 mRecordTrack->stop();
5740}
5741
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742status_t AudioFlinger::RecordHandle::onTransact(
5743 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5744{
5745 return BnAudioRecord::onTransact(code, data, reply, flags);
5746}
5747
5748// ----------------------------------------------------------------------------
5749
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005750AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5751 AudioStreamIn *input,
5752 uint32_t sampleRate,
5753 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005754 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005755 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005756 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005757 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5758 // mRsmpInIndex and mInputBytes set by readInputParameters()
5759 mReqChannelCount(popcount(channels)),
5760 mReqSampleRate(sampleRate)
5761 // mBytesRead is only meaningful while active, and so is cleared in start()
5762 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763{
Glenn Kasten480b4682012-02-28 12:30:08 -08005764 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005765
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766 readInputParameters();
5767}
5768
5769
5770AudioFlinger::RecordThread::~RecordThread()
5771{
5772 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005773 delete mResampler;
5774 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775}
5776
5777void AudioFlinger::RecordThread::onFirstRef()
5778{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005779 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780}
5781
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005782status_t AudioFlinger::RecordThread::readyToRun()
5783{
5784 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005785 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005786 return status;
5787}
5788
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789bool AudioFlinger::RecordThread::threadLoop()
5790{
5791 AudioBufferProvider::Buffer buffer;
5792 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005793 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794
Eric Laurent44d98482010-09-30 16:12:31 -07005795 nsecs_t lastWarning = 0;
5796
Eric Laurentfeb0db62011-07-22 09:04:31 -07005797 acquireWakeLock();
5798
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799 // start recording
5800 while (!exitPending()) {
5801
5802 processConfigEvents();
5803
5804 { // scope for mLock
5805 Mutex::Autolock _l(mLock);
5806 checkForNewParameters_l();
5807 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5808 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005809 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 mStandby = true;
5811 }
5812
5813 if (exitPending()) break;
5814
Eric Laurentfeb0db62011-07-22 09:04:31 -07005815 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005816 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817 // go to sleep
5818 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005819 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005820 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 continue;
5822 }
5823 if (mActiveTrack != 0) {
5824 if (mActiveTrack->mState == TrackBase::PAUSING) {
5825 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005826 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 mStandby = true;
5828 }
5829 mActiveTrack.clear();
5830 mStartStopCond.broadcast();
5831 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5832 if (mReqChannelCount != mActiveTrack->channelCount()) {
5833 mActiveTrack.clear();
5834 mStartStopCond.broadcast();
5835 } else if (mBytesRead != 0) {
5836 // record start succeeds only if first read from audio input
5837 // succeeds
5838 if (mBytesRead > 0) {
5839 mActiveTrack->mState = TrackBase::ACTIVE;
5840 } else {
5841 mActiveTrack.clear();
5842 }
5843 mStartStopCond.broadcast();
5844 }
5845 mStandby = false;
5846 }
5847 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005848 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849 }
5850
5851 if (mActiveTrack != 0) {
5852 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5853 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005854 unlockEffectChains(effectChains);
5855 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856 continue;
5857 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005858 for (size_t i = 0; i < effectChains.size(); i ++) {
5859 effectChains[i]->process_l();
5860 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005861
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005863 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005865 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866 // no resampling
5867 while (framesOut) {
5868 size_t framesIn = mFrameCount - mRsmpInIndex;
5869 if (framesIn) {
5870 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5871 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5872 if (framesIn > framesOut)
5873 framesIn = framesOut;
5874 mRsmpInIndex += framesIn;
5875 framesOut -= framesIn;
5876 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005877 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 memcpy(dst, src, framesIn * mFrameSize);
5879 } else {
5880 int16_t *src16 = (int16_t *)src;
5881 int16_t *dst16 = (int16_t *)dst;
5882 if (mChannelCount == 1) {
5883 while (framesIn--) {
5884 *dst16++ = *src16;
5885 *dst16++ = *src16++;
5886 }
5887 } else {
5888 while (framesIn--) {
5889 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5890 src16 += 2;
5891 }
5892 }
5893 }
5894 }
5895 if (framesOut && mFrameCount == mRsmpInIndex) {
5896 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005897 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005898 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 framesOut = 0;
5900 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005901 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005902 mRsmpInIndex = 0;
5903 }
5904 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005905 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5907 // Force input into standby so that it tries to
5908 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005909 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005910 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005911 }
5912 mRsmpInIndex = mFrameCount;
5913 framesOut = 0;
5914 buffer.frameCount = 0;
5915 }
5916 }
5917 }
5918 } else {
5919 // resampling
5920
5921 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5922 // alter output frame count as if we were expecting stereo samples
5923 if (mChannelCount == 1 && mReqChannelCount == 1) {
5924 framesOut >>= 1;
5925 }
5926 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5927 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5928 // are 32 bit aligned which should be always true.
5929 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005930 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931 // the resampler always outputs stereo samples: do post stereo to mono conversion
5932 int16_t *src = (int16_t *)mRsmpOutBuffer;
5933 int16_t *dst = buffer.i16;
5934 while (framesOut--) {
5935 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5936 src += 2;
5937 }
5938 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005939 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 }
5941
5942 }
Eric Laurenta011e352012-03-29 15:51:43 -07005943 if (mFramestoDrop == 0) {
5944 mActiveTrack->releaseBuffer(&buffer);
5945 } else {
5946 if (mFramestoDrop > 0) {
5947 mFramestoDrop -= buffer.frameCount;
5948 if (mFramestoDrop < 0) {
5949 mFramestoDrop = 0;
5950 }
5951 }
5952 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 mActiveTrack->overflow();
5954 }
5955 // client isn't retrieving buffers fast enough
5956 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005957 if (!mActiveTrack->setOverflow()) {
5958 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005959 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005960 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005961 lastWarning = now;
5962 }
5963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 // Release the processor for a while before asking for a new buffer.
5965 // This will give the application more chance to read from the buffer and
5966 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005967 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 }
5969 }
Eric Laurentec437d82011-07-26 20:54:46 -07005970 // enable changes in effect chain
5971 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005972 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973 }
5974
5975 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005976 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 }
5978 mActiveTrack.clear();
5979
5980 mStartStopCond.broadcast();
5981
Eric Laurentfeb0db62011-07-22 09:04:31 -07005982 releaseWakeLock();
5983
Steve Block3856b092011-10-20 11:56:00 +01005984 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 return false;
5986}
5987
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005988
5989sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5990 const sp<AudioFlinger::Client>& client,
5991 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005992 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005993 int channelMask,
5994 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005995 int sessionId,
5996 status_t *status)
5997{
5998 sp<RecordTrack> track;
5999 status_t lStatus;
6000
6001 lStatus = initCheck();
6002 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006003 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006004 goto Exit;
6005 }
6006
6007 { // scope for mLock
6008 Mutex::Autolock _l(mLock);
6009
6010 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006011 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006012
Glenn Kasten7378ca52012-01-20 13:44:40 -08006013 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006014 lStatus = NO_MEMORY;
6015 goto Exit;
6016 }
6017
6018 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006019 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6020 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006021 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006022 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6023 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006024 }
6025 lStatus = NO_ERROR;
6026
6027Exit:
6028 if (status) {
6029 *status = lStatus;
6030 }
6031 return track;
6032}
6033
Eric Laurenta011e352012-03-29 15:51:43 -07006034status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006035 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006036 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037{
Glenn Kasten58912562012-04-03 10:45:00 -07006038 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006039 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006041
6042 if (event == AudioSystem::SYNC_EVENT_NONE) {
6043 mSyncStartEvent.clear();
6044 mFramestoDrop = 0;
6045 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6046 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6047 triggerSession,
6048 recordTrack->sessionId(),
6049 syncStartEventCallback,
6050 this);
6051 mFramestoDrop = -1;
6052 }
6053
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006055 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056 if (mActiveTrack != 0) {
6057 if (recordTrack != mActiveTrack.get()) {
6058 status = -EBUSY;
6059 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6060 mActiveTrack->mState = TrackBase::ACTIVE;
6061 }
6062 return status;
6063 }
6064
6065 recordTrack->mState = TrackBase::IDLE;
6066 mActiveTrack = recordTrack;
6067 mLock.unlock();
6068 status_t status = AudioSystem::startInput(mId);
6069 mLock.lock();
6070 if (status != NO_ERROR) {
6071 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006072 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073 return status;
6074 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 mRsmpInIndex = mFrameCount;
6076 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006077 if (mResampler != NULL) {
6078 mResampler->reset();
6079 }
6080 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006082 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 mWaitWorkCV.signal();
6084 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006085 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 mActiveTrack.clear();
6087 status = INVALID_OPERATION;
6088 goto startError;
6089 }
6090 mStartStopCond.wait(mLock);
6091 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006092 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 status = BAD_VALUE;
6094 goto startError;
6095 }
Steve Block3856b092011-10-20 11:56:00 +01006096 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097 return status;
6098 }
6099startError:
6100 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006101 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 return status;
6103}
6104
Eric Laurenta011e352012-03-29 15:51:43 -07006105void AudioFlinger::RecordThread::clearSyncStartEvent()
6106{
6107 if (mSyncStartEvent != 0) {
6108 mSyncStartEvent->cancel();
6109 }
6110 mSyncStartEvent.clear();
6111}
6112
6113void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6114{
6115 sp<SyncEvent> strongEvent = event.promote();
6116
6117 if (strongEvent != 0) {
6118 RecordThread *me = (RecordThread *)strongEvent->cookie();
6119 me->handleSyncStartEvent(strongEvent);
6120 }
6121}
6122
6123void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6124{
6125 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
6126 mActiveTrack.get(),
6127 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
6128 event->listenerSession());
6129
6130 if (mActiveTrack != 0 &&
6131 event == mSyncStartEvent) {
6132 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6133 // from audio HAL
6134 mFramestoDrop = mFrameCount * 2;
6135 mSyncStartEvent.clear();
6136 }
6137}
6138
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006140 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006141 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006143 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6145 mActiveTrack->mState = TrackBase::PAUSING;
6146 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006147 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 return;
6149 }
6150 mStartStopCond.wait(mLock);
6151 // if we have been restarted, recordTrack == mActiveTrack.get() here
6152 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6153 mLock.unlock();
6154 AudioSystem::stopInput(mId);
6155 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006156 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 }
6158 }
6159 }
6160}
6161
Eric Laurenta011e352012-03-29 15:51:43 -07006162bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6163{
6164 return false;
6165}
6166
6167status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6168{
6169 if (!isValidSyncEvent(event)) {
6170 return BAD_VALUE;
6171 }
6172
6173 Mutex::Autolock _l(mLock);
6174
6175 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6176 mTrack->setSyncEvent(event);
6177 return NO_ERROR;
6178 }
6179 return NAME_NOT_FOUND;
6180}
6181
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6183{
6184 const size_t SIZE = 256;
6185 char buffer[SIZE];
6186 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187
6188 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6189 result.append(buffer);
6190
6191 if (mActiveTrack != 0) {
6192 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006193 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 mActiveTrack->dump(buffer, SIZE);
6195 result.append(buffer);
6196
6197 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6198 result.append(buffer);
6199 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6200 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006201 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202 result.append(buffer);
6203 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6204 result.append(buffer);
6205 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6206 result.append(buffer);
6207
6208
6209 } else {
6210 result.append("No record client\n");
6211 }
6212 write(fd, result.string(), result.size());
6213
6214 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006215 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216
6217 return NO_ERROR;
6218}
6219
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006220// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006221status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222{
6223 size_t framesReq = buffer->frameCount;
6224 size_t framesReady = mFrameCount - mRsmpInIndex;
6225 int channelCount;
6226
6227 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006228 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006230 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6232 // Force input into standby so that it tries to
6233 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006234 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006235 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006237 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238 buffer->frameCount = 0;
6239 return NOT_ENOUGH_DATA;
6240 }
6241 mRsmpInIndex = 0;
6242 framesReady = mFrameCount;
6243 }
6244
6245 if (framesReq > framesReady) {
6246 framesReq = framesReady;
6247 }
6248
6249 if (mChannelCount == 1 && mReqChannelCount == 2) {
6250 channelCount = 1;
6251 } else {
6252 channelCount = 2;
6253 }
6254 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6255 buffer->frameCount = framesReq;
6256 return NO_ERROR;
6257}
6258
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006259// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6261{
6262 mRsmpInIndex += buffer->frameCount;
6263 buffer->frameCount = 0;
6264}
6265
6266bool AudioFlinger::RecordThread::checkForNewParameters_l()
6267{
6268 bool reconfig = false;
6269
6270 while (!mNewParameters.isEmpty()) {
6271 status_t status = NO_ERROR;
6272 String8 keyValuePair = mNewParameters[0];
6273 AudioParameter param = AudioParameter(keyValuePair);
6274 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006275 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276 int reqSamplingRate = mReqSampleRate;
6277 int reqChannelCount = mReqChannelCount;
6278
6279 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6280 reqSamplingRate = value;
6281 reconfig = true;
6282 }
6283 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006284 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 reconfig = true;
6286 }
6287 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006288 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 reconfig = true;
6290 }
6291 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6292 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006293 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294 // if frame count is changed after track creation
6295 if (mActiveTrack != 0) {
6296 status = INVALID_OPERATION;
6297 } else {
6298 reconfig = true;
6299 }
6300 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006301 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6302 // forward device change to effects that have requested to be
6303 // aware of attached audio device.
6304 for (size_t i = 0; i < mEffectChains.size(); i++) {
6305 mEffectChains[i]->setDevice_l(value);
6306 }
6307 // store input device and output device but do not forward output device to audio HAL.
6308 // Note that status is ignored by the caller for output device
6309 // (see AudioFlinger::setParameters()
6310 if (value & AUDIO_DEVICE_OUT_ALL) {
6311 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6312 status = BAD_VALUE;
6313 } else {
6314 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006315 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6316 if (mTrack != NULL) {
6317 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006318 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006319 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6320 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6321 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006322 }
6323 mDevice |= (uint32_t)value;
6324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006325 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006326 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006328 mInput->stream->common.standby(&mInput->stream->common);
6329 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6330 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331 }
6332 if (reconfig) {
6333 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006334 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006335 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006336 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006337 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6338 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 status = NO_ERROR;
6340 }
6341 if (status == NO_ERROR) {
6342 readInputParameters();
6343 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6344 }
6345 }
6346 }
6347
6348 mNewParameters.removeAt(0);
6349
6350 mParamStatus = status;
6351 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006352 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6353 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006354 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 }
6356 return reconfig;
6357}
6358
6359String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6360{
Dima Zavinfce7a472011-04-19 22:30:36 -07006361 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006362 String8 out_s8 = String8();
6363
6364 Mutex::Autolock _l(mLock);
6365 if (initCheck() != NO_ERROR) {
6366 return out_s8;
6367 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006368
Dima Zavin799a70e2011-04-18 16:57:27 -07006369 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006370 out_s8 = String8(s);
6371 free(s);
6372 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006373}
6374
6375void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6376 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006377 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378
6379 switch (event) {
6380 case AudioSystem::INPUT_OPENED:
6381 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006382 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 desc.samplingRate = mSampleRate;
6384 desc.format = mFormat;
6385 desc.frameCount = mFrameCount;
6386 desc.latency = 0;
6387 param2 = &desc;
6388 break;
6389
6390 case AudioSystem::INPUT_CLOSED:
6391 default:
6392 break;
6393 }
6394 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6395}
6396
6397void AudioFlinger::RecordThread::readInputParameters()
6398{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006399 delete mRsmpInBuffer;
6400 // mRsmpInBuffer is always assigned a new[] below
6401 delete mRsmpOutBuffer;
6402 mRsmpOutBuffer = NULL;
6403 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006404 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405
Dima Zavin799a70e2011-04-18 16:57:27 -07006406 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006407 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6408 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006409 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006410 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006411 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006412 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006413 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6415
Glenn Kasten53d76db2012-03-08 12:32:47 -08006416 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 {
6418 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006419 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6420 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 if (mChannelCount == 1 && mReqChannelCount == 2) {
6422 channelCount = 1;
6423 } else {
6424 channelCount = 2;
6425 }
6426 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6427 mResampler->setSampleRate(mSampleRate);
6428 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6429 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6430
6431 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6432 if (mChannelCount == 1 && mReqChannelCount == 1) {
6433 mFrameCount >>= 1;
6434 }
6435
6436 }
6437 mRsmpInIndex = mFrameCount;
6438}
6439
6440unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6441{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006442 Mutex::Autolock _l(mLock);
6443 if (initCheck() != NO_ERROR) {
6444 return 0;
6445 }
6446
Dima Zavin799a70e2011-04-18 16:57:27 -07006447 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448}
6449
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006450uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6451{
6452 Mutex::Autolock _l(mLock);
6453 uint32_t result = 0;
6454 if (getEffectChain_l(sessionId) != 0) {
6455 result = EFFECT_SESSION;
6456 }
6457
6458 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6459 result |= TRACK_SESSION;
6460 }
6461
6462 return result;
6463}
6464
Eric Laurent59bd0da2011-08-01 09:52:20 -07006465AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6466{
6467 Mutex::Autolock _l(mLock);
6468 return mTrack;
6469}
6470
Glenn Kastenaed850d2012-01-26 09:46:34 -08006471AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006472{
6473 Mutex::Autolock _l(mLock);
6474 return mInput;
6475}
6476
6477AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6478{
6479 Mutex::Autolock _l(mLock);
6480 AudioStreamIn *input = mInput;
6481 mInput = NULL;
6482 return input;
6483}
6484
6485// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006486audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006487{
6488 if (mInput == NULL) {
6489 return NULL;
6490 }
6491 return &mInput->stream->common;
6492}
6493
6494
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495// ----------------------------------------------------------------------------
6496
Eric Laurenta4c5a552012-03-29 10:12:40 -07006497audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6498{
6499 if (!settingsAllowed()) {
6500 return 0;
6501 }
6502 Mutex::Autolock _l(mLock);
6503 return loadHwModule_l(name);
6504}
6505
6506// loadHwModule_l() must be called with AudioFlinger::mLock held
6507audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6508{
6509 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6510 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6511 ALOGW("loadHwModule() module %s already loaded", name);
6512 return mAudioHwDevs.keyAt(i);
6513 }
6514 }
6515
Eric Laurenta4c5a552012-03-29 10:12:40 -07006516 audio_hw_device_t *dev;
6517
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006518 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006519 if (rc) {
6520 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6521 return 0;
6522 }
6523
6524 mHardwareStatus = AUDIO_HW_INIT;
6525 rc = dev->init_check(dev);
6526 mHardwareStatus = AUDIO_HW_IDLE;
6527 if (rc) {
6528 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6529 return 0;
6530 }
6531
6532 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6533 (NULL != dev->set_master_volume)) {
6534 AutoMutex lock(mHardwareLock);
6535 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6536 dev->set_master_volume(dev, mMasterVolume);
6537 mHardwareStatus = AUDIO_HW_IDLE;
6538 }
6539
6540 audio_module_handle_t handle = nextUniqueId();
6541 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6542
6543 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006544 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006545
6546 return handle;
6547
6548}
6549
6550audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6551 audio_devices_t *pDevices,
6552 uint32_t *pSamplingRate,
6553 audio_format_t *pFormat,
6554 audio_channel_mask_t *pChannelMask,
6555 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006556 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557{
6558 status_t status;
6559 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006560 struct audio_config config = {
6561 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6562 channel_mask: pChannelMask ? *pChannelMask : 0,
6563 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6564 };
6565 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006566 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567
Eric Laurenta4c5a552012-03-29 10:12:40 -07006568 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6569 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006570 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006571 config.sample_rate,
6572 config.format,
6573 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006574 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575
6576 if (pDevices == NULL || *pDevices == 0) {
6577 return 0;
6578 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006579
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580 Mutex::Autolock _l(mLock);
6581
Eric Laurenta4c5a552012-03-29 10:12:40 -07006582 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006583 if (outHwDev == NULL)
6584 return 0;
6585
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006586 audio_io_handle_t id = nextUniqueId();
6587
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006588 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006589
6590 status = outHwDev->open_output_stream(outHwDev,
6591 id,
6592 *pDevices,
6593 (audio_output_flags_t)flags,
6594 &config,
6595 &outStream);
6596
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006597 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006598 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006599 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006600 config.sample_rate,
6601 config.format,
6602 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 status);
6604
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006605 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006606 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006607
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006608 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006609 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6610 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006612 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613 } else {
6614 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006615 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 }
6617 mPlaybackThreads.add(id, thread);
6618
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006619 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6620 if (pFormat != NULL) *pFormat = config.format;
6621 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006622 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006623
6624 // notify client processes of the new output creation
6625 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006626
6627 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006628 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006629 ALOGI("Using module %d has the primary audio interface", module);
6630 mPrimaryHardwareDev = outHwDev;
6631
6632 AutoMutex lock(mHardwareLock);
6633 mHardwareStatus = AUDIO_HW_SET_MODE;
6634 outHwDev->set_mode(outHwDev, mMode);
6635
6636 // Determine the level of master volume support the primary audio HAL has,
6637 // and set the initial master volume at the same time.
6638 float initialVolume = 1.0;
6639 mMasterVolumeSupportLvl = MVS_NONE;
6640
6641 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6642 if ((NULL != outHwDev->get_master_volume) &&
6643 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6644 mMasterVolumeSupportLvl = MVS_FULL;
6645 } else {
6646 mMasterVolumeSupportLvl = MVS_SETONLY;
6647 initialVolume = 1.0;
6648 }
6649
6650 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6651 if ((NULL == outHwDev->set_master_volume) ||
6652 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6653 mMasterVolumeSupportLvl = MVS_NONE;
6654 }
6655 // now that we have a primary device, initialize master volume on other devices
6656 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6657 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6658
6659 if ((dev != mPrimaryHardwareDev) &&
6660 (NULL != dev->set_master_volume)) {
6661 dev->set_master_volume(dev, initialVolume);
6662 }
6663 }
6664 mHardwareStatus = AUDIO_HW_IDLE;
6665 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6666 ? initialVolume
6667 : 1.0;
6668 mMasterVolume = initialVolume;
6669 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670 return id;
6671 }
6672
6673 return 0;
6674}
6675
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006676audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6677 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678{
6679 Mutex::Autolock _l(mLock);
6680 MixerThread *thread1 = checkMixerThread_l(output1);
6681 MixerThread *thread2 = checkMixerThread_l(output2);
6682
6683 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006684 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006685 return 0;
6686 }
6687
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006688 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6690 thread->addOutputTrack(thread2);
6691 mPlaybackThreads.add(id, thread);
6692 // notify client processes of the new output creation
6693 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6694 return id;
6695}
6696
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006697status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006698{
6699 // keep strong reference on the playback thread so that
6700 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006701 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702 {
6703 Mutex::Autolock _l(mLock);
6704 thread = checkPlaybackThread_l(output);
6705 if (thread == NULL) {
6706 return BAD_VALUE;
6707 }
6708
Steve Block3856b092011-10-20 11:56:00 +01006709 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006711 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006713 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6715 dupThread->removeOutputTrack((MixerThread *)thread.get());
6716 }
6717 }
6718 }
Glenn Kastena1117922012-01-26 10:53:32 -08006719 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 mPlaybackThreads.removeItem(output);
6721 }
6722 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006723 // The thread entity (active unit of execution) is no longer running here,
6724 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006726 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006727 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006728 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006729 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006730 out->hwDev->close_output_stream(out->hwDev, out->stream);
6731 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006732 }
6733 return NO_ERROR;
6734}
6735
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006736status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737{
6738 Mutex::Autolock _l(mLock);
6739 PlaybackThread *thread = checkPlaybackThread_l(output);
6740
6741 if (thread == NULL) {
6742 return BAD_VALUE;
6743 }
6744
Steve Block3856b092011-10-20 11:56:00 +01006745 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746 thread->suspend();
6747
6748 return NO_ERROR;
6749}
6750
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006751status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006752{
6753 Mutex::Autolock _l(mLock);
6754 PlaybackThread *thread = checkPlaybackThread_l(output);
6755
6756 if (thread == NULL) {
6757 return BAD_VALUE;
6758 }
6759
Steve Block3856b092011-10-20 11:56:00 +01006760 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761
6762 thread->restore();
6763
6764 return NO_ERROR;
6765}
6766
Eric Laurenta4c5a552012-03-29 10:12:40 -07006767audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6768 audio_devices_t *pDevices,
6769 uint32_t *pSamplingRate,
6770 audio_format_t *pFormat,
6771 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772{
6773 status_t status;
6774 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006775 struct audio_config config = {
6776 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6777 channel_mask: pChannelMask ? *pChannelMask : 0,
6778 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6779 };
6780 uint32_t reqSamplingRate = config.sample_rate;
6781 audio_format_t reqFormat = config.format;
6782 audio_channel_mask_t reqChannels = config.channel_mask;
6783 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006784 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785
6786 if (pDevices == NULL || *pDevices == 0) {
6787 return 0;
6788 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006789
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 Mutex::Autolock _l(mLock);
6791
Eric Laurenta4c5a552012-03-29 10:12:40 -07006792 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006793 if (inHwDev == NULL)
6794 return 0;
6795
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006796 audio_io_handle_t id = nextUniqueId();
6797
6798 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006799 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006800 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006801 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006802 config.sample_rate,
6803 config.format,
6804 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006805 status);
6806
6807 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6808 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6809 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006810 if (status == BAD_VALUE &&
6811 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6812 (config.sample_rate <= 2 * reqSamplingRate) &&
6813 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006814 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006815 inStream = NULL;
6816 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 }
6818
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006819 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006820 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6821
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006822 // Start record thread
6823 // RecorThread require both input and output device indication to forward to audio
6824 // pre processing modules
6825 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6826 thread = new RecordThread(this,
6827 input,
6828 reqSamplingRate,
6829 reqChannels,
6830 id,
6831 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006833 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006834 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006835 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006836 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837
Dima Zavin799a70e2011-04-18 16:57:27 -07006838 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839
6840 // notify client processes of the new input creation
6841 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6842 return id;
6843 }
6844
6845 return 0;
6846}
6847
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006848status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849{
6850 // keep strong reference on the record thread so that
6851 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006852 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 {
6854 Mutex::Autolock _l(mLock);
6855 thread = checkRecordThread_l(input);
6856 if (thread == NULL) {
6857 return BAD_VALUE;
6858 }
6859
Steve Block3856b092011-10-20 11:56:00 +01006860 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006861 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862 mRecordThreads.removeItem(input);
6863 }
6864 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006865 // The thread entity (active unit of execution) is no longer running here,
6866 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006868 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006869 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006870 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006871 in->hwDev->close_input_stream(in->hwDev, in->stream);
6872 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873
6874 return NO_ERROR;
6875}
6876
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006877status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878{
6879 Mutex::Autolock _l(mLock);
6880 MixerThread *dstThread = checkMixerThread_l(output);
6881 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006882 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 return BAD_VALUE;
6884 }
6885
Steve Block3856b092011-10-20 11:56:00 +01006886 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6888
6889 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6890 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006891 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892 MixerThread *srcThread = (MixerThread *)thread;
6893 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 }
Eric Laurentde070132010-07-13 04:45:46 -07006895 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896
6897 return NO_ERROR;
6898}
6899
6900
6901int AudioFlinger::newAudioSessionId()
6902{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006903 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904}
6905
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006906void AudioFlinger::acquireAudioSessionId(int audioSession)
6907{
6908 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006909 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006910 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006911 size_t num = mAudioSessionRefs.size();
6912 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006913 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006914 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6915 ref->mCnt++;
6916 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006917 return;
6918 }
6919 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006920 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6921 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006922}
6923
6924void AudioFlinger::releaseAudioSessionId(int audioSession)
6925{
6926 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006927 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006928 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006929 size_t num = mAudioSessionRefs.size();
6930 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006931 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006932 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6933 ref->mCnt--;
6934 ALOGV(" decremented refcount to %d", ref->mCnt);
6935 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006936 mAudioSessionRefs.removeAt(i);
6937 delete ref;
6938 purgeStaleEffects_l();
6939 }
6940 return;
6941 }
6942 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006943 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006944}
6945
6946void AudioFlinger::purgeStaleEffects_l() {
6947
Steve Block3856b092011-10-20 11:56:00 +01006948 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006949
6950 Vector< sp<EffectChain> > chains;
6951
6952 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6953 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6954 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6955 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006956 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6957 chains.push(ec);
6958 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006959 }
6960 }
6961 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6962 sp<RecordThread> t = mRecordThreads.valueAt(i);
6963 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6964 sp<EffectChain> ec = t->mEffectChains[j];
6965 chains.push(ec);
6966 }
6967 }
6968
6969 for (size_t i = 0; i < chains.size(); i++) {
6970 sp<EffectChain> ec = chains[i];
6971 int sessionid = ec->sessionId();
6972 sp<ThreadBase> t = ec->mThread.promote();
6973 if (t == 0) {
6974 continue;
6975 }
6976 size_t numsessionrefs = mAudioSessionRefs.size();
6977 bool found = false;
6978 for (size_t k = 0; k < numsessionrefs; k++) {
6979 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006980 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006981 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006982 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006983 found = true;
6984 break;
6985 }
6986 }
6987 if (!found) {
6988 // remove all effects from the chain
6989 while (ec->mEffects.size()) {
6990 sp<EffectModule> effect = ec->mEffects[0];
6991 effect->unPin();
6992 Mutex::Autolock _l (t->mLock);
6993 t->removeEffect_l(effect);
6994 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6995 sp<EffectHandle> handle = effect->mHandles[j].promote();
6996 if (handle != 0) {
6997 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006998 if (handle->mHasControl && handle->mEnabled) {
6999 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7000 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007001 }
7002 }
7003 AudioSystem::unregisterEffect(effect->id());
7004 }
7005 }
7006 }
7007 return;
7008}
7009
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007011AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012{
Glenn Kastena1117922012-01-26 10:53:32 -08007013 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014}
7015
7016// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007017AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018{
7019 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007020 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021}
7022
7023// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007024AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025{
Glenn Kastena1117922012-01-26 10:53:32 -08007026 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027}
7028
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007029uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007031 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032}
7033
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007034AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007035{
7036 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7037 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007038 AudioStreamOut *output = thread->getOutput();
7039 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007040 return thread;
7041 }
7042 }
7043 return NULL;
7044}
7045
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007046uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007047{
7048 PlaybackThread *thread = primaryPlaybackThread_l();
7049
7050 if (thread == NULL) {
7051 return 0;
7052 }
7053
7054 return thread->device();
7055}
7056
Eric Laurenta011e352012-03-29 15:51:43 -07007057sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7058 int triggerSession,
7059 int listenerSession,
7060 sync_event_callback_t callBack,
7061 void *cookie)
7062{
7063 Mutex::Autolock _l(mLock);
7064
7065 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7066 status_t playStatus = NAME_NOT_FOUND;
7067 status_t recStatus = NAME_NOT_FOUND;
7068 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7069 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7070 if (playStatus == NO_ERROR) {
7071 return event;
7072 }
7073 }
7074 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7075 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7076 if (recStatus == NO_ERROR) {
7077 return event;
7078 }
7079 }
7080 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7081 mPendingSyncEvents.add(event);
7082 } else {
7083 ALOGV("createSyncEvent() invalid event %d", event->type());
7084 event.clear();
7085 }
7086 return event;
7087}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007088
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089// ----------------------------------------------------------------------------
7090// Effect management
7091// ----------------------------------------------------------------------------
7092
7093
Glenn Kastenf587ba52012-01-26 16:25:10 -08007094status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095{
7096 Mutex::Autolock _l(mLock);
7097 return EffectQueryNumberEffects(numEffects);
7098}
7099
Glenn Kastenf587ba52012-01-26 16:25:10 -08007100status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101{
7102 Mutex::Autolock _l(mLock);
7103 return EffectQueryEffect(index, descriptor);
7104}
7105
Glenn Kasten5e92a782012-01-30 07:40:52 -08007106status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007107 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108{
7109 Mutex::Autolock _l(mLock);
7110 return EffectGetDescriptor(pUuid, descriptor);
7111}
7112
7113
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7115 effect_descriptor_t *pDesc,
7116 const sp<IEffectClient>& effectClient,
7117 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007118 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 int sessionId,
7120 status_t *status,
7121 int *id,
7122 int *enabled)
7123{
7124 status_t lStatus = NO_ERROR;
7125 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007126 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007127
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007128 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007129 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130
7131 if (pDesc == NULL) {
7132 lStatus = BAD_VALUE;
7133 goto Exit;
7134 }
7135
Eric Laurent84e9a102010-09-23 16:10:16 -07007136 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007137 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007138 lStatus = PERMISSION_DENIED;
7139 goto Exit;
7140 }
7141
Dima Zavinfce7a472011-04-19 22:30:36 -07007142 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007143 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007144 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007145 lStatus = PERMISSION_DENIED;
7146 goto Exit;
7147 }
7148
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007149 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007150 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007151 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007152 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007153 lStatus = BAD_VALUE;
7154 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007155 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007156 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007157 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007158 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007159 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007160 }
7161 }
7162
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163 {
7164 Mutex::Autolock _l(mLock);
7165
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166
7167 if (!EffectIsNullUuid(&pDesc->uuid)) {
7168 // if uuid is specified, request effect descriptor
7169 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7170 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007171 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 goto Exit;
7173 }
7174 } else {
7175 // if uuid is not specified, look for an available implementation
7176 // of the required type in effect factory
7177 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007178 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179 lStatus = BAD_VALUE;
7180 goto Exit;
7181 }
7182 uint32_t numEffects = 0;
7183 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007184 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185 bool found = false;
7186
7187 lStatus = EffectQueryNumberEffects(&numEffects);
7188 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007189 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190 goto Exit;
7191 }
7192 for (uint32_t i = 0; i < numEffects; i++) {
7193 lStatus = EffectQueryEffect(i, &desc);
7194 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007195 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196 continue;
7197 }
7198 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7199 // If matching type found save effect descriptor. If the session is
7200 // 0 and the effect is not auxiliary, continue enumeration in case
7201 // an auxiliary version of this effect type is available
7202 found = true;
7203 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007204 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007205 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7206 break;
7207 }
7208 }
7209 }
7210 if (!found) {
7211 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007212 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213 goto Exit;
7214 }
7215 // For same effect type, chose auxiliary version over insert version if
7216 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007217 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007218 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7219 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7220 }
7221 }
7222
7223 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007224 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007225 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7226 lStatus = INVALID_OPERATION;
7227 goto Exit;
7228 }
7229
Eric Laurent59255e42011-07-27 19:49:51 -07007230 // check recording permission for visualizer
7231 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7232 !recordingAllowed()) {
7233 lStatus = PERMISSION_DENIED;
7234 goto Exit;
7235 }
7236
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237 // return effect descriptor
7238 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7239
7240 // If output is not specified try to find a matching audio session ID in one of the
7241 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007242 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7243 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007244 // Note: io is never 0 when creating an effect on an input
7245 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007246 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007247 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7248 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007249 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007250 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007251 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007252 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007253 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007254 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7255 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7256 io = mRecordThreads.keyAt(i);
7257 break;
7258 }
7259 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007260 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007261 // If no output thread contains the requested session ID, default to
7262 // first output. The effect chain will be moved to the correct output
7263 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007264 if (io == 0 && mPlaybackThreads.size()) {
7265 io = mPlaybackThreads.keyAt(0);
7266 }
Steve Block3856b092011-10-20 11:56:00 +01007267 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007268 }
7269 ThreadBase *thread = checkRecordThread_l(io);
7270 if (thread == NULL) {
7271 thread = checkPlaybackThread_l(io);
7272 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007273 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007274 lStatus = BAD_VALUE;
7275 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007278
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007279 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007281 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007282 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7283 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 if (handle != 0 && id != NULL) {
7285 *id = handle->id();
7286 }
7287 }
7288
7289Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007290 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291 *status = lStatus;
7292 }
7293 return handle;
7294}
7295
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007296status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7297 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007298{
Steve Block3856b092011-10-20 11:56:00 +01007299 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007300 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007301 Mutex::Autolock _l(mLock);
7302 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007303 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007304 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305 }
Eric Laurentde070132010-07-13 04:45:46 -07007306 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7307 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007308 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007309 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310 }
Eric Laurentde070132010-07-13 04:45:46 -07007311 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7312 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007313 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007314 return BAD_VALUE;
7315 }
7316
7317 Mutex::Autolock _dl(dstThread->mLock);
7318 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007319 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007320
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321 return NO_ERROR;
7322}
7323
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007324// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007325status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007326 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007327 AudioFlinger::PlaybackThread *dstThread,
7328 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007329{
Steve Block3856b092011-10-20 11:56:00 +01007330 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007331 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007332
Eric Laurent59255e42011-07-27 19:49:51 -07007333 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007334 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007335 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007336 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007337 return INVALID_OPERATION;
7338 }
7339
Eric Laurent39e94f82010-07-28 01:32:47 -07007340 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007341 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007342 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007343 // removed.
7344 srcThread->removeEffectChain_l(chain);
7345
7346 // transfer all effects one by one so that new effect chain is created on new thread with
7347 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007348 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007349 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007350 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007351 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7352 while (effect != 0) {
7353 srcThread->removeEffect_l(effect);
7354 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007355 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7356 if (effect->state() == EffectModule::ACTIVE ||
7357 effect->state() == EffectModule::STOPPING) {
7358 effect->start();
7359 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007360 // if the move request is not received from audio policy manager, the effect must be
7361 // re-registered with the new strategy and output
7362 if (dstChain == 0) {
7363 dstChain = effect->chain().promote();
7364 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007365 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007366 srcThread->addEffect_l(effect);
7367 return NO_INIT;
7368 }
7369 strategy = dstChain->strategy();
7370 }
7371 if (reRegister) {
7372 AudioSystem::unregisterEffect(effect->id());
7373 AudioSystem::registerEffect(&effect->desc(),
7374 dstOutput,
7375 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007376 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007377 effect->id());
7378 }
Eric Laurentde070132010-07-13 04:45:46 -07007379 effect = chain->getEffectFromId_l(0);
7380 }
7381
7382 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383}
7384
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007385
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007387sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 const sp<AudioFlinger::Client>& client,
7389 const sp<IEffectClient>& effectClient,
7390 int32_t priority,
7391 int sessionId,
7392 effect_descriptor_t *desc,
7393 int *enabled,
7394 status_t *status
7395 )
7396{
7397 sp<EffectModule> effect;
7398 sp<EffectHandle> handle;
7399 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007401 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402 bool effectCreated = false;
7403 bool effectRegistered = false;
7404
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007405 lStatus = initCheck();
7406 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007407 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007408 goto Exit;
7409 }
7410
7411 // Do not allow effects with session ID 0 on direct output or duplicating threads
7412 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007413 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007414 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007415 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416 lStatus = BAD_VALUE;
7417 goto Exit;
7418 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007419 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007420 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007421 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007422 desc->name, desc->flags, mType);
7423 lStatus = BAD_VALUE;
7424 goto Exit;
7425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426
Steve Block3856b092011-10-20 11:56:00 +01007427 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007428
7429 { // scope for mLock
7430 Mutex::Autolock _l(mLock);
7431
7432 // check for existing effect chain with the requested audio session
7433 chain = getEffectChain_l(sessionId);
7434 if (chain == 0) {
7435 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007436 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437 chain = new EffectChain(this, sessionId);
7438 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007439 chain->setStrategy(getStrategyForSession_l(sessionId));
7440 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007441 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007442 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 }
7444
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007445 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446
7447 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007448 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007450 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451 if (lStatus != NO_ERROR) {
7452 goto Exit;
7453 }
7454 effectRegistered = true;
7455 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007456 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 lStatus = effect->status();
7458 if (lStatus != NO_ERROR) {
7459 goto Exit;
7460 }
Eric Laurentcab11242010-07-15 12:50:15 -07007461 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462 if (lStatus != NO_ERROR) {
7463 goto Exit;
7464 }
7465 effectCreated = true;
7466
7467 effect->setDevice(mDevice);
7468 effect->setMode(mAudioFlinger->getMode());
7469 }
7470 // create effect handle and connect it to effect module
7471 handle = new EffectHandle(effect, client, effectClient, priority);
7472 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007473 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474 *enabled = (int)effect->isEnabled();
7475 }
7476 }
7477
7478Exit:
7479 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007480 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007482 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483 }
7484 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007485 AudioSystem::unregisterEffect(effect->id());
7486 }
7487 if (chainCreated) {
7488 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007489 }
7490 handle.clear();
7491 }
7492
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007493 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007494 *status = lStatus;
7495 }
7496 return handle;
7497}
7498
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007499sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7500{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007501 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007502 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007503}
7504
Eric Laurentde070132010-07-13 04:45:46 -07007505// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7506// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007507status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007508{
7509 // check for existing effect chain with the requested audio session
7510 int sessionId = effect->sessionId();
7511 sp<EffectChain> chain = getEffectChain_l(sessionId);
7512 bool chainCreated = false;
7513
7514 if (chain == 0) {
7515 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007516 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007517 chain = new EffectChain(this, sessionId);
7518 addEffectChain_l(chain);
7519 chain->setStrategy(getStrategyForSession_l(sessionId));
7520 chainCreated = true;
7521 }
Steve Block3856b092011-10-20 11:56:00 +01007522 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007523
7524 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007525 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007526 this, effect->desc().name, chain.get());
7527 return BAD_VALUE;
7528 }
7529
7530 status_t status = chain->addEffect_l(effect);
7531 if (status != NO_ERROR) {
7532 if (chainCreated) {
7533 removeEffectChain_l(chain);
7534 }
7535 return status;
7536 }
7537
7538 effect->setDevice(mDevice);
7539 effect->setMode(mAudioFlinger->getMode());
7540 return NO_ERROR;
7541}
7542
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007543void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007544
Steve Block3856b092011-10-20 11:56:00 +01007545 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007546 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007547 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7548 detachAuxEffect_l(effect->id());
7549 }
7550
7551 sp<EffectChain> chain = effect->chain().promote();
7552 if (chain != 0) {
7553 // remove effect chain if removing last effect
7554 if (chain->removeEffect_l(effect) == 0) {
7555 removeEffectChain_l(chain);
7556 }
7557 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007558 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007559 }
7560}
7561
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007562void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007563 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007564{
7565 effectChains = mEffectChains;
7566 for (size_t i = 0; i < mEffectChains.size(); i++) {
7567 mEffectChains[i]->lock();
7568 }
7569}
7570
7571void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007572 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007573{
7574 for (size_t i = 0; i < effectChains.size(); i++) {
7575 effectChains[i]->unlock();
7576 }
7577}
7578
7579sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7580{
7581 Mutex::Autolock _l(mLock);
7582 return getEffectChain_l(sessionId);
7583}
7584
7585sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7586{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007587 size_t size = mEffectChains.size();
7588 for (size_t i = 0; i < size; i++) {
7589 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007590 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007591 }
7592 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007593 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007594}
7595
Glenn Kastenf78aee72012-01-04 11:00:47 -08007596void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007597{
7598 Mutex::Autolock _l(mLock);
7599 size_t size = mEffectChains.size();
7600 for (size_t i = 0; i < size; i++) {
7601 mEffectChains[i]->setMode_l(mode);
7602 }
7603}
7604
7605void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007606 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007607 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007608
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007610 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611 // delete the effect module if removing last handle on it
7612 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007613 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007614 removeEffect_l(effect);
7615 AudioSystem::unregisterEffect(effect->id());
7616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007617 }
7618}
7619
7620status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7621{
7622 int session = chain->sessionId();
7623 int16_t *buffer = mMixBuffer;
7624 bool ownsBuffer = false;
7625
Steve Block3856b092011-10-20 11:56:00 +01007626 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007627 if (session > 0) {
7628 // Only one effect chain can be present in direct output thread and it uses
7629 // the mix buffer as input
7630 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007631 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 buffer = new int16_t[numSamples];
7633 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007634 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635 ownsBuffer = true;
7636 }
7637
7638 // Attach all tracks with same session ID to this chain.
7639 for (size_t i = 0; i < mTracks.size(); ++i) {
7640 sp<Track> track = mTracks[i];
7641 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007642 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007644 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 }
7646 }
7647
7648 // indicate all active tracks in the chain
7649 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7650 sp<Track> track = mActiveTracks[i].promote();
7651 if (track == 0) continue;
7652 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007653 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007654 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007655 }
7656 }
7657 }
7658
7659 chain->setInBuffer(buffer, ownsBuffer);
7660 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007661 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007662 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007663 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7664 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007665 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007666 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7667 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007668 // Effect chain for other sessions are inserted at beginning of effect
7669 // chains list to be processed before output mix effects. Relative order between other
7670 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671 size_t size = mEffectChains.size();
7672 size_t i = 0;
7673 for (i = 0; i < size; i++) {
7674 if (mEffectChains[i]->sessionId() < session) break;
7675 }
7676 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007677 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678
7679 return NO_ERROR;
7680}
7681
7682size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7683{
7684 int session = chain->sessionId();
7685
Steve Block3856b092011-10-20 11:56:00 +01007686 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687
7688 for (size_t i = 0; i < mEffectChains.size(); i++) {
7689 if (chain == mEffectChains[i]) {
7690 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007691 // detach all active tracks from the chain
7692 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7693 sp<Track> track = mActiveTracks[i].promote();
7694 if (track == 0) continue;
7695 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007696 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007697 chain.get(), session);
7698 chain->decActiveTrackCnt();
7699 }
7700 }
7701
Mathias Agopian65ab4712010-07-14 17:59:35 -07007702 // detach all tracks with same session ID from this chain
7703 for (size_t i = 0; i < mTracks.size(); ++i) {
7704 sp<Track> track = mTracks[i];
7705 if (session == track->sessionId()) {
7706 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007707 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708 }
7709 }
Eric Laurentde070132010-07-13 04:45:46 -07007710 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711 }
7712 }
7713 return mEffectChains.size();
7714}
7715
Eric Laurentde070132010-07-13 04:45:46 -07007716status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7717 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718{
7719 Mutex::Autolock _l(mLock);
7720 return attachAuxEffect_l(track, EffectId);
7721}
7722
Eric Laurentde070132010-07-13 04:45:46 -07007723status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7724 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725{
7726 status_t status = NO_ERROR;
7727
7728 if (EffectId == 0) {
7729 track->setAuxBuffer(0, NULL);
7730 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007731 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7732 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733 if (effect != 0) {
7734 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7735 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7736 } else {
7737 status = INVALID_OPERATION;
7738 }
7739 } else {
7740 status = BAD_VALUE;
7741 }
7742 }
7743 return status;
7744}
7745
7746void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7747{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007748 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007749 sp<Track> track = mTracks[i];
7750 if (track->auxEffectId() == effectId) {
7751 attachAuxEffect_l(track, 0);
7752 }
7753 }
7754}
7755
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007756status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7757{
7758 // only one chain per input thread
7759 if (mEffectChains.size() != 0) {
7760 return INVALID_OPERATION;
7761 }
Steve Block3856b092011-10-20 11:56:00 +01007762 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007763
7764 chain->setInBuffer(NULL);
7765 chain->setOutBuffer(NULL);
7766
Eric Laurent59255e42011-07-27 19:49:51 -07007767 checkSuspendOnAddEffectChain_l(chain);
7768
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007769 mEffectChains.add(chain);
7770
7771 return NO_ERROR;
7772}
7773
7774size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7775{
Steve Block3856b092011-10-20 11:56:00 +01007776 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007777 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007778 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7779 chain.get(), mEffectChains.size(), this);
7780 if (mEffectChains.size() == 1) {
7781 mEffectChains.removeAt(0);
7782 }
7783 return 0;
7784}
7785
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786// ----------------------------------------------------------------------------
7787// EffectModule implementation
7788// ----------------------------------------------------------------------------
7789
7790#undef LOG_TAG
7791#define LOG_TAG "AudioFlinger::EffectModule"
7792
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007793AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 const wp<AudioFlinger::EffectChain>& chain,
7795 effect_descriptor_t *desc,
7796 int id,
7797 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007798 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007799 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800{
Steve Block3856b092011-10-20 11:56:00 +01007801 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007803 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804 return;
7805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806
7807 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7808
7809 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007810 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811
7812 if (mStatus != NO_ERROR) {
7813 return;
7814 }
7815 lStatus = init();
7816 if (lStatus < 0) {
7817 mStatus = lStatus;
7818 goto Error;
7819 }
7820
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007821 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7822 mPinned = true;
7823 }
Steve Block3856b092011-10-20 11:56:00 +01007824 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 return;
7826Error:
7827 EffectRelease(mEffectInterface);
7828 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007829 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007830}
7831
7832AudioFlinger::EffectModule::~EffectModule()
7833{
Steve Block3856b092011-10-20 11:56:00 +01007834 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007835 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007836 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7837 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7838 sp<ThreadBase> thread = mThread.promote();
7839 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007840 audio_stream_t *stream = thread->stream();
7841 if (stream != NULL) {
7842 stream->remove_audio_effect(stream, mEffectInterface);
7843 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007844 }
7845 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007846 // release effect engine
7847 EffectRelease(mEffectInterface);
7848 }
7849}
7850
Glenn Kasten435dbe62012-01-30 10:15:48 -08007851status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852{
7853 status_t status;
7854
7855 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856 int priority = handle->priority();
7857 size_t size = mHandles.size();
7858 sp<EffectHandle> h;
7859 size_t i;
7860 for (i = 0; i < size; i++) {
7861 h = mHandles[i].promote();
7862 if (h == 0) continue;
7863 if (h->priority() <= priority) break;
7864 }
7865 // if inserted in first place, move effect control from previous owner to this handle
7866 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007867 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007869 enabled = h->enabled();
7870 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 }
Eric Laurent59255e42011-07-27 19:49:51 -07007872 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873 status = NO_ERROR;
7874 } else {
7875 status = ALREADY_EXISTS;
7876 }
Steve Block3856b092011-10-20 11:56:00 +01007877 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 mHandles.insertAt(handle, i);
7879 return status;
7880}
7881
7882size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7883{
7884 Mutex::Autolock _l(mLock);
7885 size_t size = mHandles.size();
7886 size_t i;
7887 for (i = 0; i < size; i++) {
7888 if (mHandles[i] == handle) break;
7889 }
7890 if (i == size) {
7891 return size;
7892 }
Steve Block3856b092011-10-20 11:56:00 +01007893 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007894
7895 bool enabled = false;
7896 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007897 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007898 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007899 enabled = hdl->enabled();
7900 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007901 mHandles.removeAt(i);
7902 size = mHandles.size();
7903 // if removed from first place, move effect control from this handle to next in line
7904 if (i == 0 && size != 0) {
7905 sp<EffectHandle> h = mHandles[0].promote();
7906 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007907 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908 }
7909 }
7910
Eric Laurentec437d82011-07-26 20:54:46 -07007911 // Prevent calls to process() and other functions on effect interface from now on.
7912 // The effect engine will be released by the destructor when the last strong reference on
7913 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007914 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007915 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007916 }
7917
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918 return size;
7919}
7920
Eric Laurent59255e42011-07-27 19:49:51 -07007921sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7922{
7923 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007924 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007925}
7926
Glenn Kasten58123c32012-02-03 10:32:24 -08007927void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007928{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007929 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007930 // keep a strong reference on this EffectModule to avoid calling the
7931 // destructor before we exit
7932 sp<EffectModule> keep(this);
7933 {
7934 sp<ThreadBase> thread = mThread.promote();
7935 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007936 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937 }
7938 }
7939}
7940
7941void AudioFlinger::EffectModule::updateState() {
7942 Mutex::Autolock _l(mLock);
7943
7944 switch (mState) {
7945 case RESTART:
7946 reset_l();
7947 // FALL THROUGH
7948
7949 case STARTING:
7950 // clear auxiliary effect input buffer for next accumulation
7951 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7952 memset(mConfig.inputCfg.buffer.raw,
7953 0,
7954 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7955 }
7956 start_l();
7957 mState = ACTIVE;
7958 break;
7959 case STOPPING:
7960 stop_l();
7961 mDisableWaitCnt = mMaxDisableWaitCnt;
7962 mState = STOPPED;
7963 break;
7964 case STOPPED:
7965 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7966 // turn off sequence.
7967 if (--mDisableWaitCnt == 0) {
7968 reset_l();
7969 mState = IDLE;
7970 }
7971 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007972 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007973 break;
7974 }
7975}
7976
7977void AudioFlinger::EffectModule::process()
7978{
7979 Mutex::Autolock _l(mLock);
7980
Eric Laurentec437d82011-07-26 20:54:46 -07007981 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007982 mConfig.inputCfg.buffer.raw == NULL ||
7983 mConfig.outputCfg.buffer.raw == NULL) {
7984 return;
7985 }
7986
Eric Laurent8f45bd72010-08-31 13:50:07 -07007987 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7989 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007990 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007992 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007993 }
7994
7995 // do the actual processing in the effect engine
7996 int ret = (*mEffectInterface)->process(mEffectInterface,
7997 &mConfig.inputCfg.buffer,
7998 &mConfig.outputCfg.buffer);
7999
8000 // force transition to IDLE state when engine is ready
8001 if (mState == STOPPED && ret == -ENODATA) {
8002 mDisableWaitCnt = 1;
8003 }
8004
8005 // clear auxiliary effect input buffer for next accumulation
8006 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008007 memset(mConfig.inputCfg.buffer.raw, 0,
8008 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009 }
8010 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008011 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8012 // If an insert effect is idle and input buffer is different from output buffer,
8013 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008014 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008015 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008016 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8017 int16_t *in = mConfig.inputCfg.buffer.s16;
8018 int16_t *out = mConfig.outputCfg.buffer.s16;
8019 for (size_t i = 0; i < frameCnt; i++) {
8020 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008022 }
8023 }
8024}
8025
8026void AudioFlinger::EffectModule::reset_l()
8027{
8028 if (mEffectInterface == NULL) {
8029 return;
8030 }
8031 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8032}
8033
8034status_t AudioFlinger::EffectModule::configure()
8035{
8036 uint32_t channels;
8037 if (mEffectInterface == NULL) {
8038 return NO_INIT;
8039 }
8040
8041 sp<ThreadBase> thread = mThread.promote();
8042 if (thread == 0) {
8043 return DEAD_OBJECT;
8044 }
8045
8046 // TODO: handle configuration of effects replacing track process
8047 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008048 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008049 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008050 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008051 }
8052
8053 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008054 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008055 } else {
8056 mConfig.inputCfg.channels = channels;
8057 }
8058 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008059 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8060 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 mConfig.inputCfg.samplingRate = thread->sampleRate();
8062 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8063 mConfig.inputCfg.bufferProvider.cookie = NULL;
8064 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8065 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8066 mConfig.outputCfg.bufferProvider.cookie = NULL;
8067 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8068 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8069 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8070 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008071 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008072 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073 // - in other sessions:
8074 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8075 // other effect: overwrites output buffer: input buffer == output buffer
8076 // Auxiliary effect:
8077 // accumulates in output buffer: input buffer != output buffer
8078 // Therefore: accumulate <=> input buffer != output buffer
8079 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8080 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8081 } else {
8082 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8083 }
8084 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8085 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8086 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8087 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8088
Steve Block3856b092011-10-20 11:56:00 +01008089 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008090 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8091
Mathias Agopian65ab4712010-07-14 17:59:35 -07008092 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008093 uint32_t size = sizeof(int);
8094 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008095 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008096 sizeof(effect_config_t),
8097 &mConfig,
8098 &size,
8099 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008100 if (status == 0) {
8101 status = cmdStatus;
8102 }
8103
8104 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8105 (1000 * mConfig.outputCfg.buffer.frameCount);
8106
8107 return status;
8108}
8109
8110status_t AudioFlinger::EffectModule::init()
8111{
8112 Mutex::Autolock _l(mLock);
8113 if (mEffectInterface == NULL) {
8114 return NO_INIT;
8115 }
8116 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008117 uint32_t size = sizeof(status_t);
8118 status_t status = (*mEffectInterface)->command(mEffectInterface,
8119 EFFECT_CMD_INIT,
8120 0,
8121 NULL,
8122 &size,
8123 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008124 if (status == 0) {
8125 status = cmdStatus;
8126 }
8127 return status;
8128}
8129
Eric Laurentec35a142011-10-05 17:42:25 -07008130status_t AudioFlinger::EffectModule::start()
8131{
8132 Mutex::Autolock _l(mLock);
8133 return start_l();
8134}
8135
Mathias Agopian65ab4712010-07-14 17:59:35 -07008136status_t AudioFlinger::EffectModule::start_l()
8137{
8138 if (mEffectInterface == NULL) {
8139 return NO_INIT;
8140 }
8141 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008142 uint32_t size = sizeof(status_t);
8143 status_t status = (*mEffectInterface)->command(mEffectInterface,
8144 EFFECT_CMD_ENABLE,
8145 0,
8146 NULL,
8147 &size,
8148 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008149 if (status == 0) {
8150 status = cmdStatus;
8151 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008152 if (status == 0 &&
8153 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8154 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8155 sp<ThreadBase> thread = mThread.promote();
8156 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008157 audio_stream_t *stream = thread->stream();
8158 if (stream != NULL) {
8159 stream->add_audio_effect(stream, mEffectInterface);
8160 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008161 }
8162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008163 return status;
8164}
8165
Eric Laurentec437d82011-07-26 20:54:46 -07008166status_t AudioFlinger::EffectModule::stop()
8167{
8168 Mutex::Autolock _l(mLock);
8169 return stop_l();
8170}
8171
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172status_t AudioFlinger::EffectModule::stop_l()
8173{
8174 if (mEffectInterface == NULL) {
8175 return NO_INIT;
8176 }
8177 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008178 uint32_t size = sizeof(status_t);
8179 status_t status = (*mEffectInterface)->command(mEffectInterface,
8180 EFFECT_CMD_DISABLE,
8181 0,
8182 NULL,
8183 &size,
8184 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185 if (status == 0) {
8186 status = cmdStatus;
8187 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008188 if (status == 0 &&
8189 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8190 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8191 sp<ThreadBase> thread = mThread.promote();
8192 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008193 audio_stream_t *stream = thread->stream();
8194 if (stream != NULL) {
8195 stream->remove_audio_effect(stream, mEffectInterface);
8196 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008197 }
8198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199 return status;
8200}
8201
Eric Laurent25f43952010-07-28 05:40:18 -07008202status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8203 uint32_t cmdSize,
8204 void *pCmdData,
8205 uint32_t *replySize,
8206 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008207{
8208 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008209// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008210
Eric Laurentec437d82011-07-26 20:54:46 -07008211 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008212 return NO_INIT;
8213 }
Eric Laurent25f43952010-07-28 05:40:18 -07008214 status_t status = (*mEffectInterface)->command(mEffectInterface,
8215 cmdCode,
8216 cmdSize,
8217 pCmdData,
8218 replySize,
8219 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008220 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008221 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008222 for (size_t i = 1; i < mHandles.size(); i++) {
8223 sp<EffectHandle> h = mHandles[i].promote();
8224 if (h != 0) {
8225 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8226 }
8227 }
8228 }
8229 return status;
8230}
8231
8232status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8233{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008234
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008236 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237
8238 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008239 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8240 if (enabled && status != NO_ERROR) {
8241 return status;
8242 }
8243
Mathias Agopian65ab4712010-07-14 17:59:35 -07008244 switch (mState) {
8245 // going from disabled to enabled
8246 case IDLE:
8247 mState = STARTING;
8248 break;
8249 case STOPPED:
8250 mState = RESTART;
8251 break;
8252 case STOPPING:
8253 mState = ACTIVE;
8254 break;
8255
8256 // going from enabled to disabled
8257 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008258 mState = STOPPED;
8259 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008260 case STARTING:
8261 mState = IDLE;
8262 break;
8263 case ACTIVE:
8264 mState = STOPPING;
8265 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008266 case DESTROYED:
8267 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008268 }
8269 for (size_t i = 1; i < mHandles.size(); i++) {
8270 sp<EffectHandle> h = mHandles[i].promote();
8271 if (h != 0) {
8272 h->setEnabled(enabled);
8273 }
8274 }
8275 }
8276 return NO_ERROR;
8277}
8278
Glenn Kastenc59c0042012-02-02 14:06:11 -08008279bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280{
8281 switch (mState) {
8282 case RESTART:
8283 case STARTING:
8284 case ACTIVE:
8285 return true;
8286 case IDLE:
8287 case STOPPING:
8288 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008289 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008290 default:
8291 return false;
8292 }
8293}
8294
Glenn Kastenc59c0042012-02-02 14:06:11 -08008295bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008296{
8297 switch (mState) {
8298 case RESTART:
8299 case ACTIVE:
8300 case STOPPING:
8301 case STOPPED:
8302 return true;
8303 case IDLE:
8304 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008305 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008306 default:
8307 return false;
8308 }
8309}
8310
Mathias Agopian65ab4712010-07-14 17:59:35 -07008311status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8312{
8313 Mutex::Autolock _l(mLock);
8314 status_t status = NO_ERROR;
8315
8316 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8317 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008318 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008319 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8320 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008321 status_t cmdStatus;
8322 uint32_t volume[2];
8323 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008324 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008325 volume[0] = *left;
8326 volume[1] = *right;
8327 if (controller) {
8328 pVolume = volume;
8329 }
Eric Laurent25f43952010-07-28 05:40:18 -07008330 status = (*mEffectInterface)->command(mEffectInterface,
8331 EFFECT_CMD_SET_VOLUME,
8332 size,
8333 volume,
8334 &size,
8335 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8337 *left = volume[0];
8338 *right = volume[1];
8339 }
8340 }
8341 return status;
8342}
8343
8344status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8345{
8346 Mutex::Autolock _l(mLock);
8347 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008348 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8349 // audio pre processing modules on RecordThread can receive both output and
8350 // input device indication in the same call
8351 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8352 if (dev) {
8353 status_t cmdStatus;
8354 uint32_t size = sizeof(status_t);
8355
8356 status = (*mEffectInterface)->command(mEffectInterface,
8357 EFFECT_CMD_SET_DEVICE,
8358 sizeof(uint32_t),
8359 &dev,
8360 &size,
8361 &cmdStatus);
8362 if (status == NO_ERROR) {
8363 status = cmdStatus;
8364 }
8365 }
8366 dev = device & AUDIO_DEVICE_IN_ALL;
8367 if (dev) {
8368 status_t cmdStatus;
8369 uint32_t size = sizeof(status_t);
8370
8371 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8372 EFFECT_CMD_SET_INPUT_DEVICE,
8373 sizeof(uint32_t),
8374 &dev,
8375 &size,
8376 &cmdStatus);
8377 if (status2 == NO_ERROR) {
8378 status2 = cmdStatus;
8379 }
8380 if (status == NO_ERROR) {
8381 status = status2;
8382 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008383 }
8384 }
8385 return status;
8386}
8387
Glenn Kastenf78aee72012-01-04 11:00:47 -08008388status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008389{
8390 Mutex::Autolock _l(mLock);
8391 status_t status = NO_ERROR;
8392 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008393 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008394 uint32_t size = sizeof(status_t);
8395 status = (*mEffectInterface)->command(mEffectInterface,
8396 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008397 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008398 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008399 &size,
8400 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008401 if (status == NO_ERROR) {
8402 status = cmdStatus;
8403 }
8404 }
8405 return status;
8406}
8407
Eric Laurent59255e42011-07-27 19:49:51 -07008408void AudioFlinger::EffectModule::setSuspended(bool suspended)
8409{
8410 Mutex::Autolock _l(mLock);
8411 mSuspended = suspended;
8412}
Glenn Kastena3a85482012-01-04 11:01:11 -08008413
8414bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008415{
8416 Mutex::Autolock _l(mLock);
8417 return mSuspended;
8418}
8419
Mathias Agopian65ab4712010-07-14 17:59:35 -07008420status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8421{
8422 const size_t SIZE = 256;
8423 char buffer[SIZE];
8424 String8 result;
8425
8426 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8427 result.append(buffer);
8428
8429 bool locked = tryLock(mLock);
8430 // failed to lock - AudioFlinger is probably deadlocked
8431 if (!locked) {
8432 result.append("\t\tCould not lock Fx mutex:\n");
8433 }
8434
8435 result.append("\t\tSession Status State Engine:\n");
8436 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8437 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8438 result.append(buffer);
8439
8440 result.append("\t\tDescriptor:\n");
8441 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8442 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8443 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8444 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8445 result.append(buffer);
8446 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8447 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8448 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8449 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8450 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008451 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452 mDescriptor.apiVersion,
8453 mDescriptor.flags);
8454 result.append(buffer);
8455 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8456 mDescriptor.name);
8457 result.append(buffer);
8458 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8459 mDescriptor.implementor);
8460 result.append(buffer);
8461
8462 result.append("\t\t- Input configuration:\n");
8463 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8464 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8465 (uint32_t)mConfig.inputCfg.buffer.raw,
8466 mConfig.inputCfg.buffer.frameCount,
8467 mConfig.inputCfg.samplingRate,
8468 mConfig.inputCfg.channels,
8469 mConfig.inputCfg.format);
8470 result.append(buffer);
8471
8472 result.append("\t\t- Output configuration:\n");
8473 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8474 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8475 (uint32_t)mConfig.outputCfg.buffer.raw,
8476 mConfig.outputCfg.buffer.frameCount,
8477 mConfig.outputCfg.samplingRate,
8478 mConfig.outputCfg.channels,
8479 mConfig.outputCfg.format);
8480 result.append(buffer);
8481
8482 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8483 result.append(buffer);
8484 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8485 for (size_t i = 0; i < mHandles.size(); ++i) {
8486 sp<EffectHandle> handle = mHandles[i].promote();
8487 if (handle != 0) {
8488 handle->dump(buffer, SIZE);
8489 result.append(buffer);
8490 }
8491 }
8492
8493 result.append("\n");
8494
8495 write(fd, result.string(), result.length());
8496
8497 if (locked) {
8498 mLock.unlock();
8499 }
8500
8501 return NO_ERROR;
8502}
8503
8504// ----------------------------------------------------------------------------
8505// EffectHandle implementation
8506// ----------------------------------------------------------------------------
8507
8508#undef LOG_TAG
8509#define LOG_TAG "AudioFlinger::EffectHandle"
8510
8511AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8512 const sp<AudioFlinger::Client>& client,
8513 const sp<IEffectClient>& effectClient,
8514 int32_t priority)
8515 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008516 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008517 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518{
Steve Block3856b092011-10-20 11:56:00 +01008519 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008520
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008521 if (client == 0) {
8522 return;
8523 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008524 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8525 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8526 if (mCblkMemory != 0) {
8527 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8528
Glenn Kastena0d68332012-01-27 16:47:15 -08008529 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008530 new(mCblk) effect_param_cblk_t();
8531 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008533 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008534 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008535 return;
8536 }
8537}
8538
8539AudioFlinger::EffectHandle::~EffectHandle()
8540{
Steve Block3856b092011-10-20 11:56:00 +01008541 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008542 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008543 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008544}
8545
8546status_t AudioFlinger::EffectHandle::enable()
8547{
Steve Block3856b092011-10-20 11:56:00 +01008548 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008549 if (!mHasControl) return INVALID_OPERATION;
8550 if (mEffect == 0) return DEAD_OBJECT;
8551
Eric Laurentdb7c0792011-08-10 10:37:50 -07008552 if (mEnabled) {
8553 return NO_ERROR;
8554 }
8555
Eric Laurent59255e42011-07-27 19:49:51 -07008556 mEnabled = true;
8557
8558 sp<ThreadBase> thread = mEffect->thread().promote();
8559 if (thread != 0) {
8560 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8561 }
8562
8563 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8564 if (mEffect->suspended()) {
8565 return NO_ERROR;
8566 }
8567
Eric Laurentdb7c0792011-08-10 10:37:50 -07008568 status_t status = mEffect->setEnabled(true);
8569 if (status != NO_ERROR) {
8570 if (thread != 0) {
8571 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8572 }
8573 mEnabled = false;
8574 }
8575 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008576}
8577
8578status_t AudioFlinger::EffectHandle::disable()
8579{
Steve Block3856b092011-10-20 11:56:00 +01008580 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008581 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008582 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008583
Eric Laurentdb7c0792011-08-10 10:37:50 -07008584 if (!mEnabled) {
8585 return NO_ERROR;
8586 }
Eric Laurent59255e42011-07-27 19:49:51 -07008587 mEnabled = false;
8588
8589 if (mEffect->suspended()) {
8590 return NO_ERROR;
8591 }
8592
8593 status_t status = mEffect->setEnabled(false);
8594
8595 sp<ThreadBase> thread = mEffect->thread().promote();
8596 if (thread != 0) {
8597 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8598 }
8599
8600 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008601}
8602
8603void AudioFlinger::EffectHandle::disconnect()
8604{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008605 disconnect(true);
8606}
8607
Glenn Kasten58123c32012-02-03 10:32:24 -08008608void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008609{
Glenn Kasten58123c32012-02-03 10:32:24 -08008610 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008611 if (mEffect == 0) {
8612 return;
8613 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008614 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008615
Eric Laurenta85a74a2011-10-19 11:44:54 -07008616 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008617 sp<ThreadBase> thread = mEffect->thread().promote();
8618 if (thread != 0) {
8619 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8620 }
Eric Laurent59255e42011-07-27 19:49:51 -07008621 }
8622
Mathias Agopian65ab4712010-07-14 17:59:35 -07008623 // release sp on module => module destructor can be called now
8624 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008626 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008627 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008628 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8629 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008630 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008631 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008632 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8633 mClient.clear();
8634 }
8635}
8636
Eric Laurent25f43952010-07-28 05:40:18 -07008637status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8638 uint32_t cmdSize,
8639 void *pCmdData,
8640 uint32_t *replySize,
8641 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008642{
Steve Block3856b092011-10-20 11:56:00 +01008643// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008644// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008645
8646 // only get parameter command is permitted for applications not controlling the effect
8647 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8648 return INVALID_OPERATION;
8649 }
8650 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008651 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008652
8653 // handle commands that are not forwarded transparently to effect engine
8654 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8655 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8656 // no risk to block the whole media server process or mixer threads is we are stuck here
8657 Mutex::Autolock _l(mCblk->lock);
8658 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8659 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8660 mCblk->serverIndex = 0;
8661 mCblk->clientIndex = 0;
8662 return BAD_VALUE;
8663 }
8664 status_t status = NO_ERROR;
8665 while (mCblk->serverIndex < mCblk->clientIndex) {
8666 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008667 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008668 int *p = (int *)(mBuffer + mCblk->serverIndex);
8669 int size = *p++;
8670 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008671 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008672 break;
8673 }
8674 effect_param_t *param = (effect_param_t *)p;
8675 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008676 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008677 mCblk->serverIndex += size;
8678 continue;
8679 }
Eric Laurent25f43952010-07-28 05:40:18 -07008680 uint32_t psize = sizeof(effect_param_t) +
8681 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8682 param->vsize;
8683 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8684 psize,
8685 p,
8686 &rsize,
8687 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008688 // stop at first error encountered
8689 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008691 *(int *)pReplyData = reply;
8692 break;
8693 } else if (reply != NO_ERROR) {
8694 *(int *)pReplyData = reply;
8695 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008696 }
8697 mCblk->serverIndex += size;
8698 }
8699 mCblk->serverIndex = 0;
8700 mCblk->clientIndex = 0;
8701 return status;
8702 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008703 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008704 return enable();
8705 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008706 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 return disable();
8708 }
8709
8710 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8711}
8712
Eric Laurent59255e42011-07-27 19:49:51 -07008713void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008714{
Steve Block3856b092011-10-20 11:56:00 +01008715 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008716
8717 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008718 mEnabled = enabled;
8719
Mathias Agopian65ab4712010-07-14 17:59:35 -07008720 if (signal && mEffectClient != 0) {
8721 mEffectClient->controlStatusChanged(hasControl);
8722 }
8723}
8724
Eric Laurent25f43952010-07-28 05:40:18 -07008725void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8726 uint32_t cmdSize,
8727 void *pCmdData,
8728 uint32_t replySize,
8729 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008730{
8731 if (mEffectClient != 0) {
8732 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8733 }
8734}
8735
8736
8737
8738void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8739{
8740 if (mEffectClient != 0) {
8741 mEffectClient->enableStatusChanged(enabled);
8742 }
8743}
8744
8745status_t AudioFlinger::EffectHandle::onTransact(
8746 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8747{
8748 return BnEffect::onTransact(code, data, reply, flags);
8749}
8750
8751
8752void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8753{
Glenn Kastena0d68332012-01-27 16:47:15 -08008754 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755
8756 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008757 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008758 mPriority,
8759 mHasControl,
8760 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008761 mCblk ? mCblk->clientIndex : 0,
8762 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008763 );
8764
8765 if (locked) {
8766 mCblk->lock.unlock();
8767 }
8768}
8769
8770#undef LOG_TAG
8771#define LOG_TAG "AudioFlinger::EffectChain"
8772
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008773AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008774 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008775 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008776 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8777 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008778{
Dima Zavinfce7a472011-04-19 22:30:36 -07008779 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008780 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008781 return;
8782 }
8783 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8784 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008785}
8786
8787AudioFlinger::EffectChain::~EffectChain()
8788{
8789 if (mOwnInBuffer) {
8790 delete mInBuffer;
8791 }
8792
8793}
8794
Eric Laurent59255e42011-07-27 19:49:51 -07008795// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008796sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008797{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008798 size_t size = mEffects.size();
8799
8800 for (size_t i = 0; i < size; i++) {
8801 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008802 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008803 }
8804 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008805 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008806}
8807
Eric Laurent59255e42011-07-27 19:49:51 -07008808// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008809sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008811 size_t size = mEffects.size();
8812
8813 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008814 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8815 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008816 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008817 }
8818 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008819 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008820}
8821
Eric Laurent59255e42011-07-27 19:49:51 -07008822// getEffectFromType_l() must be called with ThreadBase::mLock held
8823sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8824 const effect_uuid_t *type)
8825{
Eric Laurent59255e42011-07-27 19:49:51 -07008826 size_t size = mEffects.size();
8827
8828 for (size_t i = 0; i < size; i++) {
8829 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008830 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008831 }
8832 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008833 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008834}
8835
Mathias Agopian65ab4712010-07-14 17:59:35 -07008836// Must be called with EffectChain::mLock locked
8837void AudioFlinger::EffectChain::process_l()
8838{
Eric Laurentdac69112010-09-28 14:09:57 -07008839 sp<ThreadBase> thread = mThread.promote();
8840 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008841 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008842 return;
8843 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008844 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8845 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008846 // always process effects unless no more tracks are on the session and the effect tail
8847 // has been rendered
8848 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008849 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008850 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008851
Eric Laurent544fe9b2011-11-11 15:42:52 -08008852 if (!tracksOnSession && mTailBufferCount == 0) {
8853 doProcess = false;
8854 }
8855
8856 if (activeTrackCnt() == 0) {
8857 // if no track is active and the effect tail has not been rendered,
8858 // the input buffer must be cleared here as the mixer process will not do it
8859 if (tracksOnSession || mTailBufferCount > 0) {
8860 size_t numSamples = thread->frameCount() * thread->channelCount();
8861 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8862 if (mTailBufferCount > 0) {
8863 mTailBufferCount--;
8864 }
8865 }
8866 }
Eric Laurentdac69112010-09-28 14:09:57 -07008867 }
8868
Mathias Agopian65ab4712010-07-14 17:59:35 -07008869 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008870 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008871 for (size_t i = 0; i < size; i++) {
8872 mEffects[i]->process();
8873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008874 }
8875 for (size_t i = 0; i < size; i++) {
8876 mEffects[i]->updateState();
8877 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008878}
8879
Eric Laurentcab11242010-07-15 12:50:15 -07008880// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008881status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008882{
8883 effect_descriptor_t desc = effect->desc();
8884 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8885
8886 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008887 effect->setChain(this);
8888 sp<ThreadBase> thread = mThread.promote();
8889 if (thread == 0) {
8890 return NO_INIT;
8891 }
8892 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008893
8894 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8895 // Auxiliary effects are inserted at the beginning of mEffects vector as
8896 // they are processed first and accumulated in chain input buffer
8897 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008898
Mathias Agopian65ab4712010-07-14 17:59:35 -07008899 // the input buffer for auxiliary effect contains mono samples in
8900 // 32 bit format. This is to avoid saturation in AudoMixer
8901 // accumulation stage. Saturation is done in EffectModule::process() before
8902 // calling the process in effect engine
8903 size_t numSamples = thread->frameCount();
8904 int32_t *buffer = new int32_t[numSamples];
8905 memset(buffer, 0, numSamples * sizeof(int32_t));
8906 effect->setInBuffer((int16_t *)buffer);
8907 // auxiliary effects output samples to chain input buffer for further processing
8908 // by insert effects
8909 effect->setOutBuffer(mInBuffer);
8910 } else {
8911 // Insert effects are inserted at the end of mEffects vector as they are processed
8912 // after track and auxiliary effects.
8913 // Insert effect order as a function of indicated preference:
8914 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8915 // another effect is present
8916 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8917 // last effect claiming first position
8918 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8919 // first effect claiming last position
8920 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8921 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8922 // already present
8923
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008924 size_t size = mEffects.size();
8925 size_t idx_insert = size;
8926 ssize_t idx_insert_first = -1;
8927 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008929 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008930 effect_descriptor_t d = mEffects[i]->desc();
8931 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8932 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8933 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8934 // check invalid effect chaining combinations
8935 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8936 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008937 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008938 return INVALID_OPERATION;
8939 }
8940 // remember position of first insert effect and by default
8941 // select this as insert position for new effect
8942 if (idx_insert == size) {
8943 idx_insert = i;
8944 }
8945 // remember position of last insert effect claiming
8946 // first position
8947 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8948 idx_insert_first = i;
8949 }
8950 // remember position of first insert effect claiming
8951 // last position
8952 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8953 idx_insert_last == -1) {
8954 idx_insert_last = i;
8955 }
8956 }
8957 }
8958
8959 // modify idx_insert from first position if needed
8960 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8961 if (idx_insert_last != -1) {
8962 idx_insert = idx_insert_last;
8963 } else {
8964 idx_insert = size;
8965 }
8966 } else {
8967 if (idx_insert_first != -1) {
8968 idx_insert = idx_insert_first + 1;
8969 }
8970 }
8971
8972 // always read samples from chain input buffer
8973 effect->setInBuffer(mInBuffer);
8974
8975 // if last effect in the chain, output samples to chain
8976 // output buffer, otherwise to chain input buffer
8977 if (idx_insert == size) {
8978 if (idx_insert != 0) {
8979 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8980 mEffects[idx_insert-1]->configure();
8981 }
8982 effect->setOutBuffer(mOutBuffer);
8983 } else {
8984 effect->setOutBuffer(mInBuffer);
8985 }
8986 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008987
Steve Block3856b092011-10-20 11:56:00 +01008988 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989 }
8990 effect->configure();
8991 return NO_ERROR;
8992}
8993
Eric Laurentcab11242010-07-15 12:50:15 -07008994// removeEffect_l() must be called with PlaybackThread::mLock held
8995size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008996{
8997 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008998 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008999 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9000
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009001 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009003 // calling stop here will remove pre-processing effect from the audio HAL.
9004 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9005 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009006 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9007 mEffects[i]->state() == EffectModule::STOPPING) {
9008 mEffects[i]->stop();
9009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009010 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9011 delete[] effect->inBuffer();
9012 } else {
9013 if (i == size - 1 && i != 0) {
9014 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9015 mEffects[i - 1]->configure();
9016 }
9017 }
9018 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009019 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009020 break;
9021 }
9022 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023
9024 return mEffects.size();
9025}
9026
Eric Laurentcab11242010-07-15 12:50:15 -07009027// setDevice_l() must be called with PlaybackThread::mLock held
9028void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029{
9030 size_t size = mEffects.size();
9031 for (size_t i = 0; i < size; i++) {
9032 mEffects[i]->setDevice(device);
9033 }
9034}
9035
Eric Laurentcab11242010-07-15 12:50:15 -07009036// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009037void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038{
9039 size_t size = mEffects.size();
9040 for (size_t i = 0; i < size; i++) {
9041 mEffects[i]->setMode(mode);
9042 }
9043}
9044
Eric Laurentcab11242010-07-15 12:50:15 -07009045// setVolume_l() must be called with PlaybackThread::mLock held
9046bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009047{
9048 uint32_t newLeft = *left;
9049 uint32_t newRight = *right;
9050 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009051 int ctrlIdx = -1;
9052 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009053
Eric Laurentcab11242010-07-15 12:50:15 -07009054 // first update volume controller
9055 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009056 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009057 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9058 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009059 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009060 break;
9061 }
9062 }
9063
9064 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009065 if (hasControl) {
9066 *left = mNewLeftVolume;
9067 *right = mNewRightVolume;
9068 }
9069 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009070 }
9071
9072 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009073 mLeftVolume = newLeft;
9074 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009075
9076 // second get volume update from volume controller
9077 if (ctrlIdx >= 0) {
9078 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009079 mNewLeftVolume = newLeft;
9080 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009081 }
9082 // then indicate volume to all other effects in chain.
9083 // Pass altered volume to effects before volume controller
9084 // and requested volume to effects after controller
9085 uint32_t lVol = newLeft;
9086 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009087
Mathias Agopian65ab4712010-07-14 17:59:35 -07009088 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009089 if ((int)i == ctrlIdx) continue;
9090 // this also works for ctrlIdx == -1 when there is no volume controller
9091 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009092 lVol = *left;
9093 rVol = *right;
9094 }
9095 mEffects[i]->setVolume(&lVol, &rVol, false);
9096 }
9097 *left = newLeft;
9098 *right = newRight;
9099
9100 return hasControl;
9101}
9102
Mathias Agopian65ab4712010-07-14 17:59:35 -07009103status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9104{
9105 const size_t SIZE = 256;
9106 char buffer[SIZE];
9107 String8 result;
9108
9109 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9110 result.append(buffer);
9111
9112 bool locked = tryLock(mLock);
9113 // failed to lock - AudioFlinger is probably deadlocked
9114 if (!locked) {
9115 result.append("\tCould not lock mutex:\n");
9116 }
9117
Eric Laurentcab11242010-07-15 12:50:15 -07009118 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9119 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120 mEffects.size(),
9121 (uint32_t)mInBuffer,
9122 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009123 mActiveTrackCnt);
9124 result.append(buffer);
9125 write(fd, result.string(), result.size());
9126
9127 for (size_t i = 0; i < mEffects.size(); ++i) {
9128 sp<EffectModule> effect = mEffects[i];
9129 if (effect != 0) {
9130 effect->dump(fd, args);
9131 }
9132 }
9133
9134 if (locked) {
9135 mLock.unlock();
9136 }
9137
9138 return NO_ERROR;
9139}
9140
Eric Laurent59255e42011-07-27 19:49:51 -07009141// must be called with ThreadBase::mLock held
9142void AudioFlinger::EffectChain::setEffectSuspended_l(
9143 const effect_uuid_t *type, bool suspend)
9144{
9145 sp<SuspendedEffectDesc> desc;
9146 // use effect type UUID timelow as key as there is no real risk of identical
9147 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009148 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009149 if (suspend) {
9150 if (index >= 0) {
9151 desc = mSuspendedEffects.valueAt(index);
9152 } else {
9153 desc = new SuspendedEffectDesc();
9154 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9155 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009156 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009157 }
9158 if (desc->mRefCount++ == 0) {
9159 sp<EffectModule> effect = getEffectIfEnabled(type);
9160 if (effect != 0) {
9161 desc->mEffect = effect;
9162 effect->setSuspended(true);
9163 effect->setEnabled(false);
9164 }
9165 }
9166 } else {
9167 if (index < 0) {
9168 return;
9169 }
9170 desc = mSuspendedEffects.valueAt(index);
9171 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009172 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009173 desc->mRefCount = 1;
9174 }
9175 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009176 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009177 if (desc->mEffect != 0) {
9178 sp<EffectModule> effect = desc->mEffect.promote();
9179 if (effect != 0) {
9180 effect->setSuspended(false);
9181 sp<EffectHandle> handle = effect->controlHandle();
9182 if (handle != 0) {
9183 effect->setEnabled(handle->enabled());
9184 }
9185 }
9186 desc->mEffect.clear();
9187 }
9188 mSuspendedEffects.removeItemsAt(index);
9189 }
9190 }
9191}
9192
9193// must be called with ThreadBase::mLock held
9194void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9195{
9196 sp<SuspendedEffectDesc> desc;
9197
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009198 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009199 if (suspend) {
9200 if (index >= 0) {
9201 desc = mSuspendedEffects.valueAt(index);
9202 } else {
9203 desc = new SuspendedEffectDesc();
9204 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009205 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009206 }
9207 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009208 Vector< sp<EffectModule> > effects;
9209 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009210 for (size_t i = 0; i < effects.size(); i++) {
9211 setEffectSuspended_l(&effects[i]->desc().type, true);
9212 }
9213 }
9214 } else {
9215 if (index < 0) {
9216 return;
9217 }
9218 desc = mSuspendedEffects.valueAt(index);
9219 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009220 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009221 desc->mRefCount = 1;
9222 }
9223 if (--desc->mRefCount == 0) {
9224 Vector<const effect_uuid_t *> types;
9225 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9226 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9227 continue;
9228 }
9229 types.add(&mSuspendedEffects.valueAt(i)->mType);
9230 }
9231 for (size_t i = 0; i < types.size(); i++) {
9232 setEffectSuspended_l(types[i], false);
9233 }
Steve Block3856b092011-10-20 11:56:00 +01009234 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009235 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9236 }
9237 }
9238}
9239
Eric Laurent6bffdb82011-09-23 08:40:41 -07009240
9241// The volume effect is used for automated tests only
9242#ifndef OPENSL_ES_H_
9243static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9244 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9245const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9246#endif //OPENSL_ES_H_
9247
Eric Laurentdb7c0792011-08-10 10:37:50 -07009248bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9249{
9250 // auxiliary effects and visualizer are never suspended on output mix
9251 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9252 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009253 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9254 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009255 return false;
9256 }
9257 return true;
9258}
9259
Glenn Kastend0539712012-01-30 12:56:03 -08009260void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009261{
Glenn Kastend0539712012-01-30 12:56:03 -08009262 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009263 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009264 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9265 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009266 }
Eric Laurent59255e42011-07-27 19:49:51 -07009267 }
Eric Laurent59255e42011-07-27 19:49:51 -07009268}
9269
9270sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9271 const effect_uuid_t *type)
9272{
Glenn Kasten090f0192012-01-30 13:00:02 -08009273 sp<EffectModule> effect = getEffectFromType_l(type);
9274 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009275}
9276
9277void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9278 bool enabled)
9279{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009280 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009281 if (enabled) {
9282 if (index < 0) {
9283 // if the effect is not suspend check if all effects are suspended
9284 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9285 if (index < 0) {
9286 return;
9287 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009288 if (!isEffectEligibleForSuspend(effect->desc())) {
9289 return;
9290 }
Eric Laurent59255e42011-07-27 19:49:51 -07009291 setEffectSuspended_l(&effect->desc().type, enabled);
9292 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009293 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009294 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009295 return;
9296 }
Eric Laurent59255e42011-07-27 19:49:51 -07009297 }
Steve Block3856b092011-10-20 11:56:00 +01009298 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009299 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009300 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9301 // if effect is requested to suspended but was not yet enabled, supend it now.
9302 if (desc->mEffect == 0) {
9303 desc->mEffect = effect;
9304 effect->setEnabled(false);
9305 effect->setSuspended(true);
9306 }
9307 } else {
9308 if (index < 0) {
9309 return;
9310 }
Steve Block3856b092011-10-20 11:56:00 +01009311 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009312 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009313 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9314 desc->mEffect.clear();
9315 effect->setSuspended(false);
9316 }
9317}
9318
Mathias Agopian65ab4712010-07-14 17:59:35 -07009319#undef LOG_TAG
9320#define LOG_TAG "AudioFlinger"
9321
9322// ----------------------------------------------------------------------------
9323
9324status_t AudioFlinger::onTransact(
9325 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9326{
9327 return BnAudioFlinger::onTransact(code, data, reply, flags);
9328}
9329
Mathias Agopian65ab4712010-07-14 17:59:35 -07009330}; // namespace android