blob: 9383864363d4e68345608b8b657f34e53b6b8de0 [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])) {
Eric Laurent29864602012-05-08 18:57:51 -0700518 if (lStatus == NO_ERROR) {
519 track->setSyncEvent(mPendingSyncEvents[i]);
520 } else {
521 mPendingSyncEvents[i]->cancel();
522 }
Eric Laurenta011e352012-03-29 15:51:43 -0700523 mPendingSyncEvents.removeAt(i);
524 i--;
525 }
526 }
527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700528 }
529 if (lStatus == NO_ERROR) {
530 trackHandle = new TrackHandle(track);
531 } else {
532 // remove local strong reference to Client before deleting the Track so that the Client
533 // destructor is called by the TrackBase destructor with mLock held
534 client.clear();
535 track.clear();
536 }
537
538Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700539 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540 *status = lStatus;
541 }
542 return trackHandle;
543}
544
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800545uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546{
547 Mutex::Autolock _l(mLock);
548 PlaybackThread *thread = checkPlaybackThread_l(output);
549 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000550 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551 return 0;
552 }
553 return thread->sampleRate();
554}
555
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800556int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557{
558 Mutex::Autolock _l(mLock);
559 PlaybackThread *thread = checkPlaybackThread_l(output);
560 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000561 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 return 0;
563 }
564 return thread->channelCount();
565}
566
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800567audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568{
569 Mutex::Autolock _l(mLock);
570 PlaybackThread *thread = checkPlaybackThread_l(output);
571 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000572 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800573 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 }
575 return thread->format();
576}
577
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800578size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579{
580 Mutex::Autolock _l(mLock);
581 PlaybackThread *thread = checkPlaybackThread_l(output);
582 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000583 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 return 0;
585 }
Glenn Kasten58912562012-04-03 10:45:00 -0700586 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
587 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 return thread->frameCount();
589}
590
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800591uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592{
593 Mutex::Autolock _l(mLock);
594 PlaybackThread *thread = checkPlaybackThread_l(output);
595 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000596 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 return 0;
598 }
599 return thread->latency();
600}
601
602status_t AudioFlinger::setMasterVolume(float value)
603{
Eric Laurenta1884f92011-08-23 08:25:03 -0700604 status_t ret = initCheck();
605 if (ret != NO_ERROR) {
606 return ret;
607 }
608
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 // check calling permissions
610 if (!settingsAllowed()) {
611 return PERMISSION_DENIED;
612 }
613
John Grossman4ff14ba2012-02-08 16:37:41 -0800614 float swmv = value;
615
Eric Laurenta4c5a552012-03-29 10:12:40 -0700616 Mutex::Autolock _l(mLock);
617
Mathias Agopian65ab4712010-07-14 17:59:35 -0700618 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800619 if (MVS_NONE != mMasterVolumeSupportLvl) {
620 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
621 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700622 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800623
624 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
625 if (NULL != dev->set_master_volume) {
626 dev->set_master_volume(dev, value);
627 }
628 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800629 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800630
631 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633
John Grossman4ff14ba2012-02-08 16:37:41 -0800634 mMasterVolume = value;
635 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800636 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700637 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638
639 return NO_ERROR;
640}
641
Glenn Kastenf78aee72012-01-04 11:00:47 -0800642status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700643{
Eric Laurenta1884f92011-08-23 08:25:03 -0700644 status_t ret = initCheck();
645 if (ret != NO_ERROR) {
646 return ret;
647 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648
649 // check calling permissions
650 if (!settingsAllowed()) {
651 return PERMISSION_DENIED;
652 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800653 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000654 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655 return BAD_VALUE;
656 }
657
658 { // scope for the lock
659 AutoMutex lock(mHardwareLock);
660 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700661 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 mHardwareStatus = AUDIO_HW_IDLE;
663 }
664
665 if (NO_ERROR == ret) {
666 Mutex::Autolock _l(mLock);
667 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800668 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700669 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 }
671
672 return ret;
673}
674
675status_t AudioFlinger::setMicMute(bool state)
676{
Eric Laurenta1884f92011-08-23 08:25:03 -0700677 status_t ret = initCheck();
678 if (ret != NO_ERROR) {
679 return ret;
680 }
681
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682 // check calling permissions
683 if (!settingsAllowed()) {
684 return PERMISSION_DENIED;
685 }
686
687 AutoMutex lock(mHardwareLock);
688 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700689 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690 mHardwareStatus = AUDIO_HW_IDLE;
691 return ret;
692}
693
694bool AudioFlinger::getMicMute() const
695{
Eric Laurenta1884f92011-08-23 08:25:03 -0700696 status_t ret = initCheck();
697 if (ret != NO_ERROR) {
698 return false;
699 }
700
Dima Zavinfce7a472011-04-19 22:30:36 -0700701 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800702 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700704 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mHardwareStatus = AUDIO_HW_IDLE;
706 return state;
707}
708
709status_t AudioFlinger::setMasterMute(bool muted)
710{
711 // check calling permissions
712 if (!settingsAllowed()) {
713 return PERMISSION_DENIED;
714 }
715
Eric Laurent93575202011-01-18 18:39:02 -0800716 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800717 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800719 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700720 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721
722 return NO_ERROR;
723}
724
725float AudioFlinger::masterVolume() const
726{
Glenn Kasten98067102011-12-13 11:47:54 -0800727 Mutex::Autolock _l(mLock);
728 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729}
730
John Grossman4ff14ba2012-02-08 16:37:41 -0800731float AudioFlinger::masterVolumeSW() const
732{
733 Mutex::Autolock _l(mLock);
734 return masterVolumeSW_l();
735}
736
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737bool AudioFlinger::masterMute() const
738{
Glenn Kasten98067102011-12-13 11:47:54 -0800739 Mutex::Autolock _l(mLock);
740 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700741}
742
John Grossman4ff14ba2012-02-08 16:37:41 -0800743float AudioFlinger::masterVolume_l() const
744{
745 if (MVS_FULL == mMasterVolumeSupportLvl) {
746 float ret_val;
747 AutoMutex lock(mHardwareLock);
748
749 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800750 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
751 (NULL != mPrimaryHardwareDev->get_master_volume),
752 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800753
754 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
755 mHardwareStatus = AUDIO_HW_IDLE;
756 return ret_val;
757 }
758
759 return mMasterVolume;
760}
761
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800762status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
763 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764{
765 // check calling permissions
766 if (!settingsAllowed()) {
767 return PERMISSION_DENIED;
768 }
769
Glenn Kasten263709e2012-01-06 08:40:01 -0800770 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000771 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772 return BAD_VALUE;
773 }
774
775 AutoMutex lock(mLock);
776 PlaybackThread *thread = NULL;
777 if (output) {
778 thread = checkPlaybackThread_l(output);
779 if (thread == NULL) {
780 return BAD_VALUE;
781 }
782 }
783
784 mStreamTypes[stream].volume = value;
785
786 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800787 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700788 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789 }
790 } else {
791 thread->setStreamVolume(stream, value);
792 }
793
794 return NO_ERROR;
795}
796
Glenn Kastenfff6d712012-01-12 16:38:12 -0800797status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798{
799 // check calling permissions
800 if (!settingsAllowed()) {
801 return PERMISSION_DENIED;
802 }
803
Glenn Kasten263709e2012-01-06 08:40:01 -0800804 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700805 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000806 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 return BAD_VALUE;
808 }
809
Eric Laurent93575202011-01-18 18:39:02 -0800810 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 mStreamTypes[stream].mute = muted;
812 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700813 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814
815 return NO_ERROR;
816}
817
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800818float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819{
Glenn Kasten263709e2012-01-06 08:40:01 -0800820 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 return 0.0f;
822 }
823
824 AutoMutex lock(mLock);
825 float volume;
826 if (output) {
827 PlaybackThread *thread = checkPlaybackThread_l(output);
828 if (thread == NULL) {
829 return 0.0f;
830 }
831 volume = thread->streamVolume(stream);
832 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800833 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 }
835
836 return volume;
837}
838
Glenn Kastenfff6d712012-01-12 16:38:12 -0800839bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
Glenn Kasten263709e2012-01-06 08:40:01 -0800841 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 return true;
843 }
844
Glenn Kasten6637baa2012-01-09 09:40:36 -0800845 AutoMutex lock(mLock);
846 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847}
848
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800849status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800851 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
853 // check calling permissions
854 if (!settingsAllowed()) {
855 return PERMISSION_DENIED;
856 }
857
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 // ioHandle == 0 means the parameters are global to the audio hardware interface
859 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700860 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700861 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800862 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700863 AutoMutex lock(mHardwareLock);
864 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
865 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
866 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
867 status_t result = dev->set_parameters(dev, keyValuePairs.string());
868 final_result = result ?: final_result;
869 }
870 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800871 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700872 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
873 AudioParameter param = AudioParameter(keyValuePairs);
874 String8 value;
875 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700876 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
877 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700878 for (size_t i = 0; i < mRecordThreads.size(); i++) {
879 sp<RecordThread> thread = mRecordThreads.valueAt(i);
880 RecordThread::RecordTrack *track = thread->track();
881 if (track != NULL) {
882 audio_devices_t device = (audio_devices_t)(
883 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700884 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700885 thread->setEffectSuspended(FX_IID_AEC,
886 suspend,
887 track->sessionId());
888 thread->setEffectSuspended(FX_IID_NS,
889 suspend,
890 track->sessionId());
891 }
892 }
Eric Laurentbee53372011-08-29 12:42:48 -0700893 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700894 }
895 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700896 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 }
898
899 // hold a strong ref on thread in case closeOutput() or closeInput() is called
900 // and the thread is exited once the lock is released
901 sp<ThreadBase> thread;
902 {
903 Mutex::Autolock _l(mLock);
904 thread = checkPlaybackThread_l(ioHandle);
905 if (thread == NULL) {
906 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800907 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700908 // indicate output device change to all input threads for pre processing
909 AudioParameter param = AudioParameter(keyValuePairs);
910 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700911 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
912 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700913 for (size_t i = 0; i < mRecordThreads.size(); i++) {
914 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
915 }
916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800919 if (thread != 0) {
920 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 }
922 return BAD_VALUE;
923}
924
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800925String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800927// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
929
Eric Laurenta4c5a552012-03-29 10:12:40 -0700930 Mutex::Autolock _l(mLock);
931
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700933 String8 out_s8;
934
Dima Zavin799a70e2011-04-18 16:57:27 -0700935 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800936 char *s;
937 {
938 AutoMutex lock(mHardwareLock);
939 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700940 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800941 s = dev->get_parameters(dev, keys.string());
942 mHardwareStatus = AUDIO_HW_IDLE;
943 }
John Grossmanef7740b2012-02-09 11:28:36 -0800944 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700945 free(s);
946 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700947 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 }
949
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
951 if (playbackThread != NULL) {
952 return playbackThread->getParameters(keys);
953 }
954 RecordThread *recordThread = checkRecordThread_l(ioHandle);
955 if (recordThread != NULL) {
956 return recordThread->getParameters(keys);
957 }
958 return String8("");
959}
960
Glenn Kastenf587ba52012-01-26 16:25:10 -0800961size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962{
Eric Laurenta1884f92011-08-23 08:25:03 -0700963 status_t ret = initCheck();
964 if (ret != NO_ERROR) {
965 return 0;
966 }
967
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800968 AutoMutex lock(mHardwareLock);
969 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700970 struct audio_config config = {
971 sample_rate: sampleRate,
972 channel_mask: audio_channel_in_mask_from_count(channelCount),
973 format: format,
974 };
975 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800976 mHardwareStatus = AUDIO_HW_IDLE;
977 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978}
979
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800980unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981{
982 if (ioHandle == 0) {
983 return 0;
984 }
985
986 Mutex::Autolock _l(mLock);
987
988 RecordThread *recordThread = checkRecordThread_l(ioHandle);
989 if (recordThread != NULL) {
990 return recordThread->getInputFramesLost();
991 }
992 return 0;
993}
994
995status_t AudioFlinger::setVoiceVolume(float value)
996{
Eric Laurenta1884f92011-08-23 08:25:03 -0700997 status_t ret = initCheck();
998 if (ret != NO_ERROR) {
999 return ret;
1000 }
1001
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002 // check calling permissions
1003 if (!settingsAllowed()) {
1004 return PERMISSION_DENIED;
1005 }
1006
1007 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001008 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001009 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 mHardwareStatus = AUDIO_HW_IDLE;
1011
1012 return ret;
1013}
1014
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001015status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1016 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017{
1018 status_t status;
1019
1020 Mutex::Autolock _l(mLock);
1021
1022 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1023 if (playbackThread != NULL) {
1024 return playbackThread->getRenderPosition(halFrames, dspFrames);
1025 }
1026
1027 return BAD_VALUE;
1028}
1029
1030void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1031{
1032
1033 Mutex::Autolock _l(mLock);
1034
Glenn Kastenbb001922012-02-03 11:10:26 -08001035 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036 if (mNotificationClients.indexOfKey(pid) < 0) {
1037 sp<NotificationClient> notificationClient = new NotificationClient(this,
1038 client,
1039 pid);
Steve Block3856b092011-10-20 11:56:00 +01001040 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041
1042 mNotificationClients.add(pid, notificationClient);
1043
1044 sp<IBinder> binder = client->asBinder();
1045 binder->linkToDeath(notificationClient);
1046
1047 // the config change is always sent from playback or record threads to avoid deadlock
1048 // with AudioSystem::gLock
1049 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1050 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1051 }
1052
1053 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1054 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1055 }
1056 }
1057}
1058
1059void AudioFlinger::removeNotificationClient(pid_t pid)
1060{
1061 Mutex::Autolock _l(mLock);
1062
Glenn Kastena3b09252012-01-20 09:19:01 -08001063 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001064
Steve Block3856b092011-10-20 11:56:00 +01001065 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001066 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001068 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001069 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001070 ALOGV(" pid %d @ %d", ref->mPid, i);
1071 if (ref->mPid == pid) {
1072 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 mAudioSessionRefs.removeAt(i);
1074 delete ref;
1075 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001076 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001077 } else {
1078 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001079 }
1080 }
1081 if (removed) {
1082 purgeStaleEffects_l();
1083 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084}
1085
1086// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001087void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088{
1089 size_t size = mNotificationClients.size();
1090 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001091 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1092 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 }
1094}
1095
1096// removeClient_l() must be called with AudioFlinger::mLock held
1097void AudioFlinger::removeClient_l(pid_t pid)
1098{
Steve Block3856b092011-10-20 11:56:00 +01001099 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 mClients.removeItem(pid);
1101}
1102
1103
1104// ----------------------------------------------------------------------------
1105
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001106AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1107 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001109 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001110 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001111 // mChannelMask
1112 mChannelCount(0),
1113 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1114 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001115 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001116 mDevice(device),
1117 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118{
1119}
1120
1121AudioFlinger::ThreadBase::~ThreadBase()
1122{
1123 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001124 // do not lock the mutex in destructor
1125 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001126 if (mPowerManager != 0) {
1127 sp<IBinder> binder = mPowerManager->asBinder();
1128 binder->unlinkToDeath(mDeathRecipient);
1129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130}
1131
1132void AudioFlinger::ThreadBase::exit()
1133{
Steve Block3856b092011-10-20 11:56:00 +01001134 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001136 // This lock prevents the following race in thread (uniprocessor for illustration):
1137 // if (!exitPending()) {
1138 // // context switch from here to exit()
1139 // // exit() calls requestExit(), what exitPending() observes
1140 // // exit() calls signal(), which is dropped since no waiters
1141 // // context switch back from exit() to here
1142 // mWaitWorkCV.wait(...);
1143 // // now thread is hung
1144 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001145 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 requestExit();
1147 mWaitWorkCV.signal();
1148 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001149 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1150 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 requestExitAndWait();
1152}
1153
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1155{
1156 status_t status;
1157
Steve Block3856b092011-10-20 11:56:00 +01001158 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159 Mutex::Autolock _l(mLock);
1160
1161 mNewParameters.add(keyValuePairs);
1162 mWaitWorkCV.signal();
1163 // wait condition with timeout in case the thread loop has exited
1164 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001165 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 status = mParamStatus;
1167 mWaitWorkCV.signal();
1168 } else {
1169 status = TIMED_OUT;
1170 }
1171 return status;
1172}
1173
1174void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1175{
1176 Mutex::Autolock _l(mLock);
1177 sendConfigEvent_l(event, param);
1178}
1179
1180// sendConfigEvent_l() must be called with ThreadBase::mLock held
1181void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1182{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001183 ConfigEvent configEvent;
1184 configEvent.mEvent = event;
1185 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001187 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 mWaitWorkCV.signal();
1189}
1190
1191void AudioFlinger::ThreadBase::processConfigEvents()
1192{
1193 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001194 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001195 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001196 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 mConfigEvents.removeAt(0);
1198 // release mLock before locking AudioFlinger mLock: lock order is always
1199 // AudioFlinger then ThreadBase to avoid cross deadlock
1200 mLock.unlock();
1201 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001202 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 mLock.lock();
1205 }
1206 mLock.unlock();
1207}
1208
1209status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1210{
1211 const size_t SIZE = 256;
1212 char buffer[SIZE];
1213 String8 result;
1214
1215 bool locked = tryLock(mLock);
1216 if (!locked) {
1217 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1218 write(fd, buffer, strlen(buffer));
1219 }
1220
Eric Laurent612bbb52012-03-14 15:03:26 -07001221 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1222 result.append(buffer);
1223 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1224 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1226 result.append(buffer);
1227 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1228 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001229 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1230 result.append(buffer);
1231 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 result.append(buffer);
1233 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1234 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001235 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1236 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1238 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001239 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 result.append(buffer);
1241
1242 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1243 result.append(buffer);
1244 result.append(" Index Command");
1245 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1246 snprintf(buffer, SIZE, "\n %02d ", i);
1247 result.append(buffer);
1248 result.append(mNewParameters[i]);
1249 }
1250
1251 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1252 result.append(buffer);
1253 snprintf(buffer, SIZE, " Index event param\n");
1254 result.append(buffer);
1255 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001256 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257 result.append(buffer);
1258 }
1259 result.append("\n");
1260
1261 write(fd, result.string(), result.size());
1262
1263 if (locked) {
1264 mLock.unlock();
1265 }
1266 return NO_ERROR;
1267}
1268
Eric Laurent1d2bff02011-07-24 17:49:51 -07001269status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1270{
1271 const size_t SIZE = 256;
1272 char buffer[SIZE];
1273 String8 result;
1274
1275 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1276 write(fd, buffer, strlen(buffer));
1277
1278 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1279 sp<EffectChain> chain = mEffectChains[i];
1280 if (chain != 0) {
1281 chain->dump(fd, args);
1282 }
1283 }
1284 return NO_ERROR;
1285}
1286
Eric Laurentfeb0db62011-07-22 09:04:31 -07001287void AudioFlinger::ThreadBase::acquireWakeLock()
1288{
1289 Mutex::Autolock _l(mLock);
1290 acquireWakeLock_l();
1291}
1292
1293void AudioFlinger::ThreadBase::acquireWakeLock_l()
1294{
1295 if (mPowerManager == 0) {
1296 // use checkService() to avoid blocking if power service is not up yet
1297 sp<IBinder> binder =
1298 defaultServiceManager()->checkService(String16("power"));
1299 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001300 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001301 } else {
1302 mPowerManager = interface_cast<IPowerManager>(binder);
1303 binder->linkToDeath(mDeathRecipient);
1304 }
1305 }
1306 if (mPowerManager != 0) {
1307 sp<IBinder> binder = new BBinder();
1308 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1309 binder,
1310 String16(mName));
1311 if (status == NO_ERROR) {
1312 mWakeLockToken = binder;
1313 }
Steve Block3856b092011-10-20 11:56:00 +01001314 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001315 }
1316}
1317
1318void AudioFlinger::ThreadBase::releaseWakeLock()
1319{
1320 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001321 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001322}
1323
1324void AudioFlinger::ThreadBase::releaseWakeLock_l()
1325{
1326 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001328 if (mPowerManager != 0) {
1329 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1330 }
1331 mWakeLockToken.clear();
1332 }
1333}
1334
1335void AudioFlinger::ThreadBase::clearPowerManager()
1336{
1337 Mutex::Autolock _l(mLock);
1338 releaseWakeLock_l();
1339 mPowerManager.clear();
1340}
1341
1342void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1343{
1344 sp<ThreadBase> thread = mThread.promote();
1345 if (thread != 0) {
1346 thread->clearPowerManager();
1347 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001348 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001349}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001350
Eric Laurent59255e42011-07-27 19:49:51 -07001351void AudioFlinger::ThreadBase::setEffectSuspended(
1352 const effect_uuid_t *type, bool suspend, int sessionId)
1353{
1354 Mutex::Autolock _l(mLock);
1355 setEffectSuspended_l(type, suspend, sessionId);
1356}
1357
1358void AudioFlinger::ThreadBase::setEffectSuspended_l(
1359 const effect_uuid_t *type, bool suspend, int sessionId)
1360{
Glenn Kasten090f0192012-01-30 13:00:02 -08001361 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001362 if (chain != 0) {
1363 if (type != NULL) {
1364 chain->setEffectSuspended_l(type, suspend);
1365 } else {
1366 chain->setEffectSuspendedAll_l(suspend);
1367 }
1368 }
1369
1370 updateSuspendedSessions_l(type, suspend, sessionId);
1371}
1372
1373void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1374{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001375 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001376 if (index < 0) {
1377 return;
1378 }
1379
1380 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1381 mSuspendedSessions.editValueAt(index);
1382
1383 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001384 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001385 for (int j = 0; j < desc->mRefCount; j++) {
1386 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1387 chain->setEffectSuspendedAll_l(true);
1388 } else {
Steve Block3856b092011-10-20 11:56:00 +01001389 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001390 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001391 chain->setEffectSuspended_l(&desc->mType, true);
1392 }
1393 }
1394 }
1395}
1396
Eric Laurent59255e42011-07-27 19:49:51 -07001397void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1398 bool suspend,
1399 int sessionId)
1400{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001401 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001402
1403 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1404
1405 if (suspend) {
1406 if (index >= 0) {
1407 sessionEffects = mSuspendedSessions.editValueAt(index);
1408 } else {
1409 mSuspendedSessions.add(sessionId, sessionEffects);
1410 }
1411 } else {
1412 if (index < 0) {
1413 return;
1414 }
1415 sessionEffects = mSuspendedSessions.editValueAt(index);
1416 }
1417
1418
1419 int key = EffectChain::kKeyForSuspendAll;
1420 if (type != NULL) {
1421 key = type->timeLow;
1422 }
1423 index = sessionEffects.indexOfKey(key);
1424
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001425 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001426 if (suspend) {
1427 if (index >= 0) {
1428 desc = sessionEffects.valueAt(index);
1429 } else {
1430 desc = new SuspendedSessionDesc();
1431 if (type != NULL) {
1432 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1433 }
1434 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001435 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001436 }
1437 desc->mRefCount++;
1438 } else {
1439 if (index < 0) {
1440 return;
1441 }
1442 desc = sessionEffects.valueAt(index);
1443 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001444 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001445 sessionEffects.removeItemsAt(index);
1446 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001447 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001448 sessionId);
1449 mSuspendedSessions.removeItem(sessionId);
1450 }
1451 }
1452 }
1453 if (!sessionEffects.isEmpty()) {
1454 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1455 }
1456}
1457
1458void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1459 bool enabled,
1460 int sessionId)
1461{
1462 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001463 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1464}
Eric Laurent59255e42011-07-27 19:49:51 -07001465
Eric Laurenta85a74a2011-10-19 11:44:54 -07001466void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1467 bool enabled,
1468 int sessionId)
1469{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001470 if (mType != RECORD) {
1471 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1472 // another session. This gives the priority to well behaved effect control panels
1473 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001474 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1475 // global effects
1476 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001477 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1478 }
1479 }
Eric Laurent59255e42011-07-27 19:49:51 -07001480
1481 sp<EffectChain> chain = getEffectChain_l(sessionId);
1482 if (chain != 0) {
1483 chain->checkSuspendOnEffectEnabled(effect, enabled);
1484 }
1485}
1486
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487// ----------------------------------------------------------------------------
1488
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001489AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1490 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001491 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001492 uint32_t device,
1493 type_t type)
1494 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001495 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1496 // Assumes constructor is called by AudioFlinger with it's mLock held,
1497 // but it would be safer to explicitly pass initial masterMute as parameter
1498 mMasterMute(audioFlinger->masterMute_l()),
1499 // mStreamTypes[] initialized in constructor body
1500 mOutput(output),
1501 // Assumes constructor is called by AudioFlinger with it's mLock held,
1502 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001503 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001504 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001505 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001506 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001507 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten288ed212012-04-25 17:52:27 -07001508 // index 0 is reserved for normal mixer's submix
1509 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510{
Glenn Kasten480b4682012-02-28 12:30:08 -08001511 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001512
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 readOutputParameters();
1514
Glenn Kasten263709e2012-01-06 08:40:01 -08001515 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001516 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1517 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1518 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001519 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1520 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001522 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1523 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524}
1525
1526AudioFlinger::PlaybackThread::~PlaybackThread()
1527{
1528 delete [] mMixBuffer;
1529}
1530
1531status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1532{
1533 dumpInternals(fd, args);
1534 dumpTracks(fd, args);
1535 dumpEffectChains(fd, args);
1536 return NO_ERROR;
1537}
1538
1539status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1540{
1541 const size_t SIZE = 256;
1542 char buffer[SIZE];
1543 String8 result;
1544
Glenn Kasten58912562012-04-03 10:45:00 -07001545 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1546 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1547 const stream_type_t *st = &mStreamTypes[i];
1548 if (i > 0) {
1549 result.appendFormat(", ");
1550 }
1551 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1552 if (st->mute) {
1553 result.append("M");
1554 }
1555 }
1556 result.append("\n");
1557 write(fd, result.string(), result.length());
1558 result.clear();
1559
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1561 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001562 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563 for (size_t i = 0; i < mTracks.size(); ++i) {
1564 sp<Track> track = mTracks[i];
1565 if (track != 0) {
1566 track->dump(buffer, SIZE);
1567 result.append(buffer);
1568 }
1569 }
1570
1571 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1572 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001573 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001575 sp<Track> track = mActiveTracks[i].promote();
1576 if (track != 0) {
1577 track->dump(buffer, SIZE);
1578 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 }
1580 }
1581 write(fd, result.string(), result.size());
1582 return NO_ERROR;
1583}
1584
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1586{
1587 const size_t SIZE = 256;
1588 char buffer[SIZE];
1589 String8 result;
1590
1591 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1592 result.append(buffer);
1593 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1596 result.append(buffer);
1597 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1598 result.append(buffer);
1599 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1600 result.append(buffer);
1601 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1602 result.append(buffer);
1603 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1604 result.append(buffer);
1605 write(fd, result.string(), result.size());
1606
1607 dumpBase(fd, args);
1608
1609 return NO_ERROR;
1610}
1611
1612// Thread virtuals
1613status_t AudioFlinger::PlaybackThread::readyToRun()
1614{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001615 status_t status = initCheck();
1616 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001617 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001618 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001619 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001621 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622}
1623
1624void AudioFlinger::PlaybackThread::onFirstRef()
1625{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001626 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627}
1628
1629// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001630sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001632 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001634 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001635 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 int frameCount,
1637 const sp<IMemory>& sharedBuffer,
1638 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001639 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001640 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 status_t *status)
1642{
1643 sp<Track> track;
1644 status_t lStatus;
1645
Glenn Kasten73d22752012-03-19 13:38:30 -07001646 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1647
1648 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001649 if (flags & IAudioFlinger::TRACK_FAST) {
1650 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001651 // not timed
1652 (!isTimed) &&
1653 // either of these use cases:
1654 (
1655 // use case 1: shared buffer with any frame count
1656 (
1657 (sharedBuffer != 0)
1658 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001659 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001660 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001661 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001662 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001663 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001664 )
1665 ) &&
1666 // PCM data
1667 audio_is_linear_pcm(format) &&
1668 // mono or stereo
1669 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1670 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001671#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001672 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001673 (sampleRate == mSampleRate) &&
1674#endif
1675 // normal mixer has an associated fast mixer
1676 hasFastMixer() &&
1677 // there are sufficient fast track slots available
1678 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001679 // FIXME test that MixerThread for this fast track has a capable output HAL
1680 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001681 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1683 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001684 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001685 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001686 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001687 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001688 } else {
1689 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001690 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1691 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1692 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1693 audio_is_linear_pcm(format),
1694 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001695 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001696 // For compatibility with AudioTrack calculation, buffer depth is forced
1697 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1698 // This is probably too conservative, but legacy application code may depend on it.
1699 // If you change this calculation, also review the start threshold which is related.
1700 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1701 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1702 if (minBufCount < 2) {
1703 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001704 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001705 int minFrameCount = mNormalFrameCount * minBufCount;
1706 if (frameCount < minFrameCount) {
1707 frameCount = minFrameCount;
1708 }
1709 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001710 }
1711
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001713 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1714 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001715 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001716 "for output %p with format %d",
1717 sampleRate, format, channelMask, mOutput, mFormat);
1718 lStatus = BAD_VALUE;
1719 goto Exit;
1720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 }
1722 } else {
1723 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1724 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001725 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 lStatus = BAD_VALUE;
1727 goto Exit;
1728 }
1729 }
1730
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001731 lStatus = initCheck();
1732 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001733 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 goto Exit;
1735 }
1736
1737 { // scope for mLock
1738 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001739
1740 // all tracks in same audio session must share the same routing strategy otherwise
1741 // conflicts will happen when tracks are moved from one output to another by audio policy
1742 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001743 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001744 for (size_t i = 0; i < mTracks.size(); ++i) {
1745 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001746 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001747 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001748 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001749 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001750 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001751 lStatus = BAD_VALUE;
1752 goto Exit;
1753 }
1754 }
1755 }
1756
John Grossman4ff14ba2012-02-08 16:37:41 -08001757 if (!isTimed) {
1758 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001759 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001760 } else {
1761 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1762 channelMask, frameCount, sharedBuffer, sessionId);
1763 }
1764 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765 lStatus = NO_MEMORY;
1766 goto Exit;
1767 }
1768 mTracks.add(track);
1769
1770 sp<EffectChain> chain = getEffectChain_l(sessionId);
1771 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001772 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001774 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001775 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 }
1777 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001778
1779#ifdef HAVE_REQUEST_PRIORITY
1780 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1781 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1782 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1783 // so ask activity manager to do this on our behalf
1784 int err = requestPriority(callingPid, tid, 1);
1785 if (err != 0) {
1786 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1787 1, callingPid, tid, err);
1788 }
1789 }
1790#endif
1791
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 lStatus = NO_ERROR;
1793
1794Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001795 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 *status = lStatus;
1797 }
1798 return track;
1799}
1800
1801uint32_t AudioFlinger::PlaybackThread::latency() const
1802{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001803 Mutex::Autolock _l(mLock);
1804 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001805 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001806 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 return 0;
1808 }
1809}
1810
Glenn Kasten6637baa2012-01-09 09:40:36 -08001811void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001813 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815}
1816
Glenn Kasten6637baa2012-01-09 09:40:36 -08001817void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001819 Mutex::Autolock _l(mLock);
1820 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821}
1822
Glenn Kasten6637baa2012-01-09 09:40:36 -08001823void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001825 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827}
1828
Glenn Kasten6637baa2012-01-09 09:40:36 -08001829void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001831 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833}
1834
Glenn Kastenfff6d712012-01-12 16:38:12 -08001835float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001837 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 return mStreamTypes[stream].volume;
1839}
1840
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841// addTrack_l() must be called with ThreadBase::mLock held
1842status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1843{
1844 status_t status = ALREADY_EXISTS;
1845
1846 // set retry count for buffer fill
1847 track->mRetryCount = kMaxTrackStartupRetries;
1848 if (mActiveTracks.indexOf(track) < 0) {
1849 // the track is newly added, make sure it fills up all its
1850 // buffers before playing. This is to ensure the client will
1851 // effectively get the latency it requested.
1852 track->mFillingUpStatus = Track::FS_FILLING;
1853 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001854 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 mActiveTracks.add(track);
1856 if (track->mainBuffer() != mMixBuffer) {
1857 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1858 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001859 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001860 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 }
1862 }
1863
1864 status = NO_ERROR;
1865 }
1866
Steve Block3856b092011-10-20 11:56:00 +01001867 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 mWaitWorkCV.broadcast();
1869
1870 return status;
1871}
1872
1873// destroyTrack_l() must be called with ThreadBase::mLock held
1874void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1875{
1876 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001877 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001879 removeTrack_l(track);
1880 }
1881}
1882
1883void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1884{
Eric Laurent29864602012-05-08 18:57:51 -07001885 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001886 mTracks.remove(track);
1887 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001888 // redundant as track is about to be destroyed, for dumpsys only
1889 track->mName = -1;
1890 if (track->isFastTrack()) {
1891 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001892 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001893 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1894 mFastTrackAvailMask |= 1 << index;
1895 // redundant as track is about to be destroyed, for dumpsys only
1896 track->mFastIndex = -1;
1897 }
Eric Laurentb469b942011-05-09 12:09:06 -07001898 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1899 if (chain != 0) {
1900 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 }
1902}
1903
1904String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1905{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001906 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001907 char *s;
1908
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001909 Mutex::Autolock _l(mLock);
1910 if (initCheck() != NO_ERROR) {
1911 return out_s8;
1912 }
1913
Dima Zavin799a70e2011-04-18 16:57:27 -07001914 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001915 out_s8 = String8(s);
1916 free(s);
1917 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918}
1919
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001920// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1922 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001923 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924
Steve Block3856b092011-10-20 11:56:00 +01001925 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926
1927 switch (event) {
1928 case AudioSystem::OUTPUT_OPENED:
1929 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001930 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 desc.samplingRate = mSampleRate;
1932 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001933 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 desc.latency = latency();
1935 param2 = &desc;
1936 break;
1937
1938 case AudioSystem::STREAM_CONFIG_CHANGED:
1939 param2 = &param;
1940 case AudioSystem::OUTPUT_CLOSED:
1941 default:
1942 break;
1943 }
1944 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1945}
1946
1947void AudioFlinger::PlaybackThread::readOutputParameters()
1948{
Dima Zavin799a70e2011-04-18 16:57:27 -07001949 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001950 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1951 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001952 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001953 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001954 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001955 if (mFrameCount & 15) {
1956 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1957 mFrameCount);
1958 }
1959
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001960 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001961 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001962 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001963 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001964 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1965 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1966 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1967 maxNormalFrameCount = maxNormalFrameCount & ~15;
1968 if (maxNormalFrameCount < minNormalFrameCount) {
1969 maxNormalFrameCount = minNormalFrameCount;
1970 }
1971 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1972 if (multiplier <= 1.0) {
1973 multiplier = 1.0;
1974 } else if (multiplier <= 2.0) {
1975 if (2 * mFrameCount <= maxNormalFrameCount) {
1976 multiplier = 2.0;
1977 } else {
1978 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1979 }
1980 } else {
1981 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
1982 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
1983 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
1984 // FIXME this rounding up should not be done if no HAL SRC
1985 uint32_t truncMult = (uint32_t) multiplier;
1986 if ((truncMult & 1)) {
1987 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1988 ++truncMult;
1989 }
1990 }
1991 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07001992 }
Glenn Kasten58912562012-04-03 10:45:00 -07001993 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07001994 mNormalFrameCount = multiplier * mFrameCount;
1995 // round up to nearest 16 frames to satisfy AudioMixer
1996 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07001997 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998
1999 // FIXME - Current mixer implementation only supports stereo output: Always
2000 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08002001 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07002002 mMixBuffer = new int16_t[mNormalFrameCount * 2];
2003 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004
Eric Laurentde070132010-07-13 04:45:46 -07002005 // force reconfiguration of effect chains and engines to take new buffer size and audio
2006 // parameters into account
2007 // Note that mLock is not held when readOutputParameters() is called from the constructor
2008 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2009 // matter.
2010 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2011 Vector< sp<EffectChain> > effectChains = mEffectChains;
2012 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002013 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015}
2016
2017status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2018{
Glenn Kastena0d68332012-01-27 16:47:15 -08002019 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 return BAD_VALUE;
2021 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002022 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002023 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 return INVALID_OPERATION;
2025 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002026 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027
Dima Zavin799a70e2011-04-18 16:57:27 -07002028 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029}
2030
Eric Laurent39e94f82010-07-28 01:32:47 -07002031uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032{
2033 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002034 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002036 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 }
2038
2039 for (size_t i = 0; i < mTracks.size(); ++i) {
2040 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002041 if (sessionId == track->sessionId() &&
2042 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002043 result |= TRACK_SESSION;
2044 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 }
2046 }
2047
Eric Laurent39e94f82010-07-28 01:32:47 -07002048 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049}
2050
Eric Laurentde070132010-07-13 04:45:46 -07002051uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2052{
Dima Zavinfce7a472011-04-19 22:30:36 -07002053 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002054 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002055 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2056 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002057 }
2058 for (size_t i = 0; i < mTracks.size(); i++) {
2059 sp<Track> track = mTracks[i];
2060 if (sessionId == track->sessionId() &&
2061 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002062 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002063 }
2064 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002065 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002066}
2067
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068
Glenn Kastenaed850d2012-01-26 09:46:34 -08002069AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002070{
2071 Mutex::Autolock _l(mLock);
2072 return mOutput;
2073}
2074
2075AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2076{
2077 Mutex::Autolock _l(mLock);
2078 AudioStreamOut *output = mOutput;
2079 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002080 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2081 // must push a NULL and wait for ack
2082 mOutputSink.clear();
2083 mPipeSink.clear();
2084 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002085 return output;
2086}
2087
2088// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002089audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002090{
2091 if (mOutput == NULL) {
2092 return NULL;
2093 }
2094 return &mOutput->stream->common;
2095}
2096
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002097uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002098{
2099 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2100 // decoding and transfer time. So sleeping for half of the latency would likely cause
2101 // underruns
2102 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002103 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002104 } else {
2105 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2106 }
2107}
2108
Eric Laurenta011e352012-03-29 15:51:43 -07002109status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2110{
2111 if (!isValidSyncEvent(event)) {
2112 return BAD_VALUE;
2113 }
2114
2115 Mutex::Autolock _l(mLock);
2116
2117 for (size_t i = 0; i < mTracks.size(); ++i) {
2118 sp<Track> track = mTracks[i];
2119 if (event->triggerSession() == track->sessionId()) {
2120 track->setSyncEvent(event);
2121 return NO_ERROR;
2122 }
2123 }
2124
2125 return NAME_NOT_FOUND;
2126}
2127
2128bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2129{
2130 switch (event->type()) {
2131 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2132 return true;
2133 default:
2134 break;
2135 }
2136 return false;
2137}
2138
Eric Laurent44a957f2012-05-15 15:26:05 -07002139void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2140{
2141 size_t count = tracksToRemove.size();
2142 if (CC_UNLIKELY(count)) {
2143 for (size_t i = 0 ; i < count ; i++) {
2144 const sp<Track>& track = tracksToRemove.itemAt(i);
2145 if ((track->sharedBuffer() != 0) &&
2146 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2147 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2148 }
2149 }
2150 }
2151
2152}
2153
Mathias Agopian65ab4712010-07-14 17:59:35 -07002154// ----------------------------------------------------------------------------
2155
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002156AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002157 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002158 : PlaybackThread(audioFlinger, output, id, device, type),
2159 // mAudioMixer below
2160#ifdef SOAKER
2161 mSoaker(NULL),
2162#endif
2163 // mFastMixer below
2164 mFastMixerFutex(0)
2165 // mOutputSink below
2166 // mPipeSink below
2167 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168{
Glenn Kasten58912562012-04-03 10:45:00 -07002169 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2170 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2171 "mFrameCount=%d, mNormalFrameCount=%d",
2172 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2173 mNormalFrameCount);
2174 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2175
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 // FIXME - Current mixer implementation only supports stereo output
2177 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002178 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 }
Glenn Kasten58912562012-04-03 10:45:00 -07002180
2181 // create an NBAIO sink for the HAL output stream, and negotiate
2182 mOutputSink = new AudioStreamOutSink(output->stream);
2183 size_t numCounterOffers = 0;
2184 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2185 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2186 ALOG_ASSERT(index == 0);
2187
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002188 // initialize fast mixer depending on configuration
2189 bool initFastMixer;
2190 switch (kUseFastMixer) {
2191 case FastMixer_Never:
2192 initFastMixer = false;
2193 break;
2194 case FastMixer_Always:
2195 initFastMixer = true;
2196 break;
2197 case FastMixer_Static:
2198 case FastMixer_Dynamic:
2199 initFastMixer = mFrameCount < mNormalFrameCount;
2200 break;
2201 }
2202 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002203
2204 // create a MonoPipe to connect our submix to FastMixer
2205 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002206 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2207 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2208 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2209 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002210 const NBAIO_Format offers[1] = {format};
2211 size_t numCounterOffers = 0;
2212 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2213 ALOG_ASSERT(index == 0);
2214 mPipeSink = monoPipe;
2215
2216#ifdef SOAKER
2217 // create a soaker as workaround for governor issues
2218 mSoaker = new Soaker();
2219 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2220 mSoaker->run("Soaker", PRIORITY_LOWEST);
2221#endif
2222
2223 // create fast mixer and configure it initially with just one fast track for our submix
2224 mFastMixer = new FastMixer();
2225 FastMixerStateQueue *sq = mFastMixer->sq();
2226 FastMixerState *state = sq->begin();
2227 FastTrack *fastTrack = &state->mFastTracks[0];
2228 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2229 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2230 fastTrack->mVolumeProvider = NULL;
2231 fastTrack->mGeneration++;
2232 state->mFastTracksGen++;
2233 state->mTrackMask = 1;
2234 // fast mixer will use the HAL output sink
2235 state->mOutputSink = mOutputSink.get();
2236 state->mOutputSinkGen++;
2237 state->mFrameCount = mFrameCount;
2238 state->mCommand = FastMixerState::COLD_IDLE;
2239 // already done in constructor initialization list
2240 //mFastMixerFutex = 0;
2241 state->mColdFutexAddr = &mFastMixerFutex;
2242 state->mColdGen++;
2243 state->mDumpState = &mFastMixerDumpState;
2244 sq->end();
2245 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2246
2247 // start the fast mixer
2248 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2249#ifdef HAVE_REQUEST_PRIORITY
2250 pid_t tid = mFastMixer->getTid();
2251 int err = requestPriority(getpid_cached, tid, 2);
2252 if (err != 0) {
2253 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2254 2, getpid_cached, tid, err);
2255 }
2256#endif
2257
2258 } else {
2259 mFastMixer = NULL;
2260 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002261
2262 switch (kUseFastMixer) {
2263 case FastMixer_Never:
2264 case FastMixer_Dynamic:
2265 mNormalSink = mOutputSink;
2266 break;
2267 case FastMixer_Always:
2268 mNormalSink = mPipeSink;
2269 break;
2270 case FastMixer_Static:
2271 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2272 break;
2273 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274}
2275
2276AudioFlinger::MixerThread::~MixerThread()
2277{
Glenn Kasten58912562012-04-03 10:45:00 -07002278 if (mFastMixer != NULL) {
2279 FastMixerStateQueue *sq = mFastMixer->sq();
2280 FastMixerState *state = sq->begin();
2281 if (state->mCommand == FastMixerState::COLD_IDLE) {
2282 int32_t old = android_atomic_inc(&mFastMixerFutex);
2283 if (old == -1) {
2284 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2285 }
2286 }
2287 state->mCommand = FastMixerState::EXIT;
2288 sq->end();
2289 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2290 mFastMixer->join();
2291 // Though the fast mixer thread has exited, it's state queue is still valid.
2292 // We'll use that extract the final state which contains one remaining fast track
2293 // corresponding to our sub-mix.
2294 state = sq->begin();
2295 ALOG_ASSERT(state->mTrackMask == 1);
2296 FastTrack *fastTrack = &state->mFastTracks[0];
2297 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2298 delete fastTrack->mBufferProvider;
2299 sq->end(false /*didModify*/);
2300 delete mFastMixer;
2301#ifdef SOAKER
2302 if (mSoaker != NULL) {
2303 mSoaker->requestExitAndWait();
2304 }
2305 delete mSoaker;
2306#endif
2307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308 delete mAudioMixer;
2309}
2310
Glenn Kasten83efdd02012-02-24 07:21:32 -08002311class CpuStats {
2312public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002313 CpuStats();
2314 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002315#ifdef DEBUG_CPU_USAGE
2316private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002317 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2318 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2319
2320 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2321
2322 int mCpuNum; // thread's current CPU number
2323 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002324#endif
2325};
2326
Glenn Kasten190a46f2012-03-06 11:27:10 -08002327CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002328#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002329 : mCpuNum(-1), mCpukHz(-1)
2330#endif
2331{
2332}
2333
2334void CpuStats::sample(const String8 &title) {
2335#ifdef DEBUG_CPU_USAGE
2336 // get current thread's delta CPU time in wall clock ns
2337 double wcNs;
2338 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2339
2340 // record sample for wall clock statistics
2341 if (valid) {
2342 mWcStats.sample(wcNs);
2343 }
2344
2345 // get the current CPU number
2346 int cpuNum = sched_getcpu();
2347
2348 // get the current CPU frequency in kHz
2349 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2350
2351 // check if either CPU number or frequency changed
2352 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2353 mCpuNum = cpuNum;
2354 mCpukHz = cpukHz;
2355 // ignore sample for purposes of cycles
2356 valid = false;
2357 }
2358
2359 // if no change in CPU number or frequency, then record sample for cycle statistics
2360 if (valid && mCpukHz > 0) {
2361 double cycles = wcNs * cpukHz * 0.000001;
2362 mHzStats.sample(cycles);
2363 }
2364
2365 unsigned n = mWcStats.n();
2366 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002367 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002368 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002369 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2370 double perLoop = elapsed / (double) n;
2371 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002372 double perLoop1k = perLoop * 0.001;
2373 double mean = mWcStats.mean();
2374 double stddev = mWcStats.stddev();
2375 double minimum = mWcStats.minimum();
2376 double maximum = mWcStats.maximum();
2377 double meanCycles = mHzStats.mean();
2378 double stddevCycles = mHzStats.stddev();
2379 double minCycles = mHzStats.minimum();
2380 double maxCycles = mHzStats.maximum();
2381 mCpuUsage.resetElapsed();
2382 mWcStats.reset();
2383 mHzStats.reset();
2384 ALOGD("CPU usage for %s over past %.1f secs\n"
2385 " (%u mixer loops at %.1f mean ms per loop):\n"
2386 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2387 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2388 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2389 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002390 elapsed * .000000001, n, perLoop * .000001,
2391 mean * .001,
2392 stddev * .001,
2393 minimum * .001,
2394 maximum * .001,
2395 mean / perLoop100,
2396 stddev / perLoop100,
2397 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002398 maximum / perLoop100,
2399 meanCycles / perLoop1k,
2400 stddevCycles / perLoop1k,
2401 minCycles / perLoop1k,
2402 maxCycles / perLoop1k);
2403
Glenn Kasten83efdd02012-02-24 07:21:32 -08002404 }
2405 }
2406#endif
2407};
2408
Glenn Kasten37d825e2012-02-24 07:21:48 -08002409void AudioFlinger::PlaybackThread::checkSilentMode_l()
2410{
2411 if (!mMasterMute) {
2412 char value[PROPERTY_VALUE_MAX];
2413 if (property_get("ro.audio.silent", value, "0") > 0) {
2414 char *endptr;
2415 unsigned long ul = strtoul(value, &endptr, 0);
2416 if (*endptr == '\0' && ul != 0) {
2417 ALOGD("Silence is golden");
2418 // The setprop command will not allow a property to be changed after
2419 // the first time it is set, so we don't have to worry about un-muting.
2420 setMasterMute_l(true);
2421 }
2422 }
2423 }
2424}
2425
Glenn Kasten000f0e32012-03-01 17:10:56 -08002426bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427{
2428 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002429
Glenn Kasten000f0e32012-03-01 17:10:56 -08002430 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002431
2432 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002434if (mType == MIXER) {
2435 longStandbyExit = false;
2436}
Glenn Kasten688a6402012-02-29 07:57:06 -08002437
Glenn Kasten000f0e32012-03-01 17:10:56 -08002438 // DUPLICATING
2439 // FIXME could this be made local to while loop?
2440 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002441
Glenn Kasten66fcab92012-02-24 14:59:21 -08002442 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002443 sleepTime = idleSleepTime;
2444
2445if (mType == MIXER) {
2446 sleepTimeShift = 0;
2447}
2448
Glenn Kasten83efdd02012-02-24 07:21:32 -08002449 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002450 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451
Eric Laurentfeb0db62011-07-22 09:04:31 -07002452 acquireWakeLock();
2453
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 while (!exitPending())
2455 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002456 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002457
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002458 Vector< sp<EffectChain> > effectChains;
2459
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 processConfigEvents();
2461
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 { // scope for mLock
2463
2464 Mutex::Autolock _l(mLock);
2465
2466 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002467 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 }
2469
Glenn Kastenfa26a852012-03-06 11:28:04 -08002470 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002471
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002473 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002474 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002476
2477 threadLoop_standby();
2478
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479 mStandby = true;
2480 mBytesWritten = 0;
2481 }
2482
Glenn Kasten3e074702012-02-28 18:40:35 -08002483 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 // we're about to wait, flush the binder command buffer
2485 IPCThreadState::self()->flushCommands();
2486
Glenn Kastenfa26a852012-03-06 11:28:04 -08002487 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002488
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489 if (exitPending()) break;
2490
Eric Laurentfeb0db62011-07-22 09:04:31 -07002491 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002493 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002495 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002496 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497
Eric Laurentda747442012-04-25 18:53:13 -07002498 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002499 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002500
Glenn Kasten37d825e2012-02-24 07:21:48 -08002501 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502
Glenn Kasten000f0e32012-03-01 17:10:56 -08002503 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002505 if (mType == MIXER) {
2506 sleepTimeShift = 0;
2507 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 continue;
2510 }
2511 }
2512
Glenn Kasten81028042012-04-30 18:15:12 -07002513 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002514 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515
2516 // prevent any changes in effect chain list and in each effect chain
2517 // during mixing and effect process as the audio buffers could be deleted
2518 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002519 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521
Glenn Kastenfec279f2012-03-08 07:47:15 -08002522 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002523 threadLoop_mix();
2524 } else {
2525 threadLoop_sleepTime();
2526 }
2527
2528 if (mSuspended > 0) {
2529 sleepTime = suspendSleepTimeUs();
2530 }
2531
2532 // only process effects if we're going to write
2533 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534 for (size_t i = 0; i < effectChains.size(); i ++) {
2535 effectChains[i]->process_l();
2536 }
2537 }
2538
2539 // enable changes in effect chain
2540 unlockEffectChains(effectChains);
2541
2542 // sleepTime == 0 means we must write to audio hardware
2543 if (sleepTime == 0) {
2544
2545 threadLoop_write();
2546
2547if (mType == MIXER) {
2548 // write blocked detection
2549 nsecs_t now = systemTime();
2550 nsecs_t delta = now - mLastWriteTime;
2551 if (!mStandby && delta > maxPeriod) {
2552 mNumDelayedWrites++;
2553 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002554 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten000f0e32012-03-01 17:10:56 -08002555 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2556 ns2ms(delta), mNumDelayedWrites, this);
2557 lastWarning = now;
2558 }
2559 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2560 // a different threshold. Or completely removed for what it is worth anyway...
2561 if (mStandby) {
2562 longStandbyExit = true;
2563 }
2564 }
2565}
2566
2567 mStandby = false;
2568 } else {
2569 usleep(sleepTime);
2570 }
2571
Glenn Kasten58912562012-04-03 10:45:00 -07002572 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002573 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002574 // same lock. This will also mutate and push a new fast mixer state.
2575 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002576 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002577
Glenn Kastenfa26a852012-03-06 11:28:04 -08002578 // FIXME I don't understand the need for this here;
2579 // it was in the original code but maybe the
2580 // assignment in saveOutputTracks() makes this unnecessary?
2581 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002582
2583 // Effect chains will be actually deleted here if they were removed from
2584 // mEffectChains list during mixing or effects processing
2585 effectChains.clear();
2586
2587 // FIXME Note that the above .clear() is no longer necessary since effectChains
2588 // is now local to this block, but will keep it for now (at least until merge done).
2589 }
2590
2591if (mType == MIXER || mType == DIRECT) {
2592 // put output stream into standby mode
2593 if (!mStandby) {
2594 mOutput->stream->common.standby(&mOutput->stream->common);
2595 }
2596}
2597if (mType == DUPLICATING) {
2598 // for DuplicatingThread, standby mode is handled by the outputTracks
2599}
2600
2601 releaseWakeLock();
2602
2603 ALOGV("Thread %p type %d exiting", this, mType);
2604 return false;
2605}
2606
Glenn Kasten58912562012-04-03 10:45:00 -07002607void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2608{
Glenn Kasten58912562012-04-03 10:45:00 -07002609 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2610}
2611
2612void AudioFlinger::MixerThread::threadLoop_write()
2613{
2614 // FIXME we should only do one push per cycle; confirm this is true
2615 // Start the fast mixer if it's not already running
2616 if (mFastMixer != NULL) {
2617 FastMixerStateQueue *sq = mFastMixer->sq();
2618 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002619 if (state->mCommand != FastMixerState::MIX_WRITE &&
2620 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002621 if (state->mCommand == FastMixerState::COLD_IDLE) {
2622 int32_t old = android_atomic_inc(&mFastMixerFutex);
2623 if (old == -1) {
2624 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2625 }
2626 }
2627 state->mCommand = FastMixerState::MIX_WRITE;
2628 sq->end();
2629 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002630 if (kUseFastMixer == FastMixer_Dynamic) {
2631 mNormalSink = mPipeSink;
2632 }
Glenn Kasten58912562012-04-03 10:45:00 -07002633 } else {
2634 sq->end(false /*didModify*/);
2635 }
2636 }
2637 PlaybackThread::threadLoop_write();
2638}
2639
Glenn Kasten000f0e32012-03-01 17:10:56 -08002640// shared by MIXER and DIRECT, overridden by DUPLICATING
2641void AudioFlinger::PlaybackThread::threadLoop_write()
2642{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002643 // FIXME rewrite to reduce number of system calls
2644 mLastWriteTime = systemTime();
2645 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002646
Glenn Kasten58912562012-04-03 10:45:00 -07002647#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002648 size_t count = mixBufferSize >> mBitShift;
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002649 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002650 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002651 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002652 if (framesWritten > 0) {
2653 size_t bytesWritten = framesWritten << mBitShift;
2654 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002655 }
2656
Glenn Kasten952eeb22012-03-06 11:30:57 -08002657 mNumWrites++;
2658 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002659}
2660
Glenn Kasten58912562012-04-03 10:45:00 -07002661void AudioFlinger::MixerThread::threadLoop_standby()
2662{
2663 // Idle the fast mixer if it's currently running
2664 if (mFastMixer != NULL) {
2665 FastMixerStateQueue *sq = mFastMixer->sq();
2666 FastMixerState *state = sq->begin();
2667 if (!(state->mCommand & FastMixerState::IDLE)) {
2668 state->mCommand = FastMixerState::COLD_IDLE;
2669 state->mColdFutexAddr = &mFastMixerFutex;
2670 state->mColdGen++;
2671 mFastMixerFutex = 0;
2672 sq->end();
2673 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2674 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002675 if (kUseFastMixer == FastMixer_Dynamic) {
2676 mNormalSink = mOutputSink;
2677 }
Glenn Kasten58912562012-04-03 10:45:00 -07002678 } else {
2679 sq->end(false /*didModify*/);
2680 }
2681 }
2682 PlaybackThread::threadLoop_standby();
2683}
2684
Glenn Kasten000f0e32012-03-01 17:10:56 -08002685// shared by MIXER and DIRECT, overridden by DUPLICATING
2686void AudioFlinger::PlaybackThread::threadLoop_standby()
2687{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002688 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2689 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002690}
2691
2692void AudioFlinger::MixerThread::threadLoop_mix()
2693{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002694 // obtain the presentation timestamp of the next output buffer
2695 int64_t pts;
2696 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002697
Glenn Kasten952eeb22012-03-06 11:30:57 -08002698 if (NULL != mOutput->stream->get_next_write_timestamp) {
2699 status = mOutput->stream->get_next_write_timestamp(
2700 mOutput->stream, &pts);
2701 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002702
Glenn Kasten952eeb22012-03-06 11:30:57 -08002703 if (status != NO_ERROR) {
2704 pts = AudioBufferProvider::kInvalidPTS;
2705 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002706
Glenn Kasten952eeb22012-03-06 11:30:57 -08002707 // mix buffers...
2708 mAudioMixer->process(pts);
2709 // increase sleep time progressively when application underrun condition clears.
2710 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2711 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2712 // such that we would underrun the audio HAL.
2713 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2714 sleepTimeShift--;
2715 }
2716 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002717 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002718 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002719}
2720
2721void AudioFlinger::MixerThread::threadLoop_sleepTime()
2722{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002723 // If no tracks are ready, sleep once for the duration of an output
2724 // buffer size, then write 0s to the output
2725 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002726 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002727 sleepTime = activeSleepTime >> sleepTimeShift;
2728 if (sleepTime < kMinThreadSleepTimeUs) {
2729 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002731 // reduce sleep time in case of consecutive application underruns to avoid
2732 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2733 // duration we would end up writing less data than needed by the audio HAL if
2734 // the condition persists.
2735 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2736 sleepTimeShift++;
2737 }
2738 } else {
2739 sleepTime = idleSleepTime;
2740 }
2741 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002742 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002743 memset (mMixBuffer, 0, mixBufferSize);
2744 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002745 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002746 }
2747 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748}
2749
2750// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002751AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002752 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753{
2754
Glenn Kasten29c23c32012-01-26 13:37:52 -08002755 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002757 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758 size_t mixedTracks = 0;
2759 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002760 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002761 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002762 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763
2764 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002765 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766
Eric Laurent571d49c2010-08-11 05:20:11 -07002767 if (masterMute) {
2768 masterVolume = 0;
2769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002771 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002773 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002774 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 masterVolume = (float)((v + (1 << 23)) >> 24);
2776 chain.clear();
2777 }
2778
Glenn Kasten288ed212012-04-25 17:52:27 -07002779 // prepare a new state to push
2780 FastMixerStateQueue *sq = NULL;
2781 FastMixerState *state = NULL;
2782 bool didModify = false;
2783 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2784 if (mFastMixer != NULL) {
2785 sq = mFastMixer->sq();
2786 state = sq->begin();
2787 }
2788
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002790 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 if (t == 0) continue;
2792
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002793 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002795
Glenn Kasten288ed212012-04-25 17:52:27 -07002796 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002797 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002798
2799 // It's theoretically possible (though unlikely) for a fast track to be created
2800 // and then removed within the same normal mix cycle. This is not a problem, as
2801 // the track never becomes active so it's fast mixer slot is never touched.
2802 // The converse, of removing an (active) track and then creating a new track
2803 // at the identical fast mixer slot within the same normal mix cycle,
2804 // is impossible because the slot isn't marked available until the end of each cycle.
2805 int j = track->mFastIndex;
2806 FastTrack *fastTrack = &state->mFastTracks[j];
2807
2808 // Determine whether the track is currently in underrun condition,
2809 // and whether it had a recent underrun.
Glenn Kasten09474df2012-05-10 14:48:07 -07002810 FastTrackUnderruns underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2811 uint32_t recentFull = (underruns.mBitFields.mFull -
2812 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2813 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2814 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2815 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2816 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2817 uint32_t recentUnderruns = recentPartial + recentEmpty;
2818 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002819 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002820 // or stopped which can occur when flush() is called while active
2821 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002822 track->mUnderrunCount += recentUnderruns;
2823 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002824
Glenn Kastend08f48c2012-05-01 18:14:02 -07002825 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002826 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002827 bool isActive = true;
2828 switch (track->mState) {
2829 case TrackBase::STOPPING_1:
2830 // track stays active in STOPPING_1 state until first underrun
2831 if (recentUnderruns > 0) {
2832 track->mState = TrackBase::STOPPING_2;
2833 }
2834 break;
2835 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002836 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002837 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002838 break;
2839 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002840 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002841 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002842 break;
2843 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002844 if (recentFull > 0 || recentPartial > 0) {
2845 // track has provided at least some frames recently: reset retry count
2846 track->mRetryCount = kMaxTrackRetries;
2847 }
2848 if (recentUnderruns == 0) {
2849 // no recent underruns: stay active
2850 break;
2851 }
2852 // there has recently been an underrun of some kind
2853 if (track->sharedBuffer() == 0) {
2854 // were any of the recent underruns "empty" (no frames available)?
2855 if (recentEmpty == 0) {
2856 // no, then ignore the partial underruns as they are allowed indefinitely
2857 break;
2858 }
2859 // there has recently been an "empty" underrun: decrement the retry counter
2860 if (--(track->mRetryCount) > 0) {
2861 break;
2862 }
2863 // indicate to client process that the track was disabled because of underrun;
2864 // it will then automatically call start() when data is available
2865 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2866 // remove from active list, but state remains ACTIVE [confusing but true]
2867 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002868 break;
2869 }
2870 // fall through
2871 case TrackBase::STOPPING_2:
2872 case TrackBase::PAUSED:
2873 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002874 case TrackBase::STOPPED:
2875 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002876 // Check for presentation complete if track is inactive
2877 // We have consumed all the buffers of this track.
2878 // This would be incomplete if we auto-paused on underrun
2879 {
2880 size_t audioHALFrames =
2881 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2882 size_t framesWritten =
2883 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2884 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2885 // track stays in active list until presentation is complete
2886 break;
2887 }
2888 }
2889 if (track->isStopping_2()) {
2890 track->mState = TrackBase::STOPPED;
2891 }
2892 if (track->isStopped()) {
2893 // Can't reset directly, as fast mixer is still polling this track
2894 // track->reset();
2895 // So instead mark this track as needing to be reset after push with ack
2896 resetMask |= 1 << i;
2897 }
2898 isActive = false;
2899 break;
2900 case TrackBase::IDLE:
2901 default:
2902 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002903 }
2904
2905 if (isActive) {
2906 // was it previously inactive?
2907 if (!(state->mTrackMask & (1 << j))) {
2908 ExtendedAudioBufferProvider *eabp = track;
2909 VolumeProvider *vp = track;
2910 fastTrack->mBufferProvider = eabp;
2911 fastTrack->mVolumeProvider = vp;
2912 fastTrack->mSampleRate = track->mSampleRate;
2913 fastTrack->mChannelMask = track->mChannelMask;
2914 fastTrack->mGeneration++;
2915 state->mTrackMask |= 1 << j;
2916 didModify = true;
2917 // no acknowledgement required for newly active tracks
2918 }
2919 // cache the combined master volume and stream type volume for fast mixer; this
2920 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2921 track->mCachedVolume = track->isMuted() ?
2922 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2923 ++fastTracks;
2924 } else {
2925 // was it previously active?
2926 if (state->mTrackMask & (1 << j)) {
2927 fastTrack->mBufferProvider = NULL;
2928 fastTrack->mGeneration++;
2929 state->mTrackMask &= ~(1 << j);
2930 didModify = true;
2931 // If any fast tracks were removed, we must wait for acknowledgement
2932 // because we're about to decrement the last sp<> on those tracks.
2933 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002934 } else {
2935 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002936 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002937 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002938 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07002939 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002940 }
2941 continue;
2942 }
2943
2944 { // local variable scope to avoid goto warning
2945
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946 audio_track_cblk_t* cblk = track->cblk();
2947
2948 // The first time a track is added we wait
2949 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002950 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002951 // make sure that we have enough frames to mix one full buffer.
2952 // enforce this condition only once to enable draining the buffer in case the client
2953 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002954 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002955 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002956 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002957 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002958 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002959 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002960 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002961 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002962 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002963 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002964 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002965 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002966 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2967 // the minimum track buffer size is normally twice the number of frames necessary
2968 // to fill one buffer and the resampler should not leave more than one buffer worth
2969 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002970 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002971 }
2972 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002973 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 !track->isPaused() && !track->isTerminated())
2975 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002976 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977
2978 mixedTracks++;
2979
2980 // track->mainBuffer() != mMixBuffer means there is an effect chain
2981 // connected to the track
2982 chain.clear();
2983 if (track->mainBuffer() != mMixBuffer) {
2984 chain = getEffectChain_l(track->sessionId());
2985 // Delegate volume control to effect in track effect chain if needed
2986 if (chain != 0) {
2987 tracksWithEffect++;
2988 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002989 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002990 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991 }
2992 }
2993
2994
2995 int param = AudioMixer::VOLUME;
2996 if (track->mFillingUpStatus == Track::FS_FILLED) {
2997 // no ramp for the first volume setting
2998 track->mFillingUpStatus = Track::FS_ACTIVE;
2999 if (track->mState == TrackBase::RESUMING) {
3000 track->mState = TrackBase::ACTIVE;
3001 param = AudioMixer::RAMP_VOLUME;
3002 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003003 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004 } else if (cblk->server != 0) {
3005 // If the track is stopped before the first frame was mixed,
3006 // do not apply ramp
3007 param = AudioMixer::RAMP_VOLUME;
3008 }
3009
3010 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003011 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003012 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003013 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003014 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 if (track->isPausing()) {
3016 track->setPaused();
3017 }
3018 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003019
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003021 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003023 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003024 vl = vlr & 0xFFFF;
3025 vr = vlr >> 16;
3026 // track volumes come from shared memory, so can't be trusted and must be clamped
3027 if (vl > MAX_GAIN_INT) {
3028 ALOGV("Track left volume out of range: %04X", vl);
3029 vl = MAX_GAIN_INT;
3030 }
3031 if (vr > MAX_GAIN_INT) {
3032 ALOGV("Track right volume out of range: %04X", vr);
3033 vr = MAX_GAIN_INT;
3034 }
3035 // now apply the master volume and stream type volume
3036 vl = (uint32_t)(v * vl) << 12;
3037 vr = (uint32_t)(v * vr) << 12;
3038 // assuming master volume and stream type volume each go up to 1.0,
3039 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040
Glenn Kasten05632a52012-01-03 14:22:33 -08003041 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3042 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003043 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003044 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003045 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003046 }
3047 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003049 // Delegate volume control to effect in track effect chain if needed
3050 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3051 // Do not ramp volume if volume is controlled by effect
3052 param = AudioMixer::VOLUME;
3053 track->mHasVolumeController = true;
3054 } else {
3055 // force no volume ramp when volume controller was just disabled or removed
3056 // from effect chain to avoid volume spike
3057 if (track->mHasVolumeController) {
3058 param = AudioMixer::VOLUME;
3059 }
3060 track->mHasVolumeController = false;
3061 }
3062
3063 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003064 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003065 vl = (vl + (1 << 11)) >> 12;
3066 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3067 vr = (vr + (1 << 11)) >> 12;
3068 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003069
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003070 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 -07003071
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003073 mAudioMixer->setBufferProvider(name, track);
3074 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003076 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3077 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3078 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003079 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003080 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 AudioMixer::TRACK,
3082 AudioMixer::FORMAT, (void *)track->format());
3083 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003084 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003086 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003088 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 AudioMixer::RESAMPLE,
3090 AudioMixer::SAMPLE_RATE,
3091 (void *)(cblk->sampleRate));
3092 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003093 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 AudioMixer::TRACK,
3095 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3096 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003097 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 AudioMixer::TRACK,
3099 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3100
3101 // reset retry count
3102 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003103
Eric Laurent27741442012-01-17 19:20:12 -08003104 // If one track is ready, set the mixer ready if:
3105 // - the mixer was not ready during previous round OR
3106 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003107 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003108 mixerStatus != MIXER_TRACKS_ENABLED) {
3109 mixerStatus = MIXER_TRACKS_READY;
3110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003112 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurent83faee02012-04-27 18:24:29 -07003113 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3114 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 // We have consumed all the buffers of this track.
3116 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003117 // TODO: use actual buffer filling status instead of latency when available from
3118 // audio HAL
3119 size_t audioHALFrames =
3120 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3121 size_t framesWritten =
3122 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3123 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003124 if (track->isStopped()) {
3125 track->reset();
3126 }
Eric Laurenta011e352012-03-29 15:51:43 -07003127 tracksToRemove->add(track);
3128 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 } else {
3130 // No buffers for this track. Give it a few chances to
3131 // fill a buffer, then remove it from active list.
3132 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003133 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003135 // indicate to client process that the track was disabled because of underrun;
3136 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003137 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003138 // If one track is not ready, mark the mixer also not ready if:
3139 // - the mixer was ready during previous round OR
3140 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003141 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003142 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 mixerStatus = MIXER_TRACKS_ENABLED;
3144 }
3145 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003146 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 }
Glenn Kasten58912562012-04-03 10:45:00 -07003148
3149 } // local variable scope to avoid goto warning
3150track_is_ready: ;
3151
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 }
3153
Glenn Kasten288ed212012-04-25 17:52:27 -07003154 // Push the new FastMixer state if necessary
3155 if (didModify) {
3156 state->mFastTracksGen++;
3157 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3158 if (kUseFastMixer == FastMixer_Dynamic &&
3159 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3160 state->mCommand = FastMixerState::COLD_IDLE;
3161 state->mColdFutexAddr = &mFastMixerFutex;
3162 state->mColdGen++;
3163 mFastMixerFutex = 0;
3164 if (kUseFastMixer == FastMixer_Dynamic) {
3165 mNormalSink = mOutputSink;
3166 }
3167 // If we go into cold idle, need to wait for acknowledgement
3168 // so that fast mixer stops doing I/O.
3169 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3170 }
3171 sq->end();
3172 }
3173 if (sq != NULL) {
3174 sq->end(didModify);
3175 sq->push(block);
3176 }
3177
3178 // Now perform the deferred reset on fast tracks that have stopped
3179 while (resetMask != 0) {
3180 size_t i = __builtin_ctz(resetMask);
3181 ALOG_ASSERT(i < count);
3182 resetMask &= ~(1 << i);
3183 sp<Track> t = mActiveTracks[i].promote();
3184 if (t == 0) continue;
3185 Track* track = t.get();
3186 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3187 track->reset();
3188 }
Glenn Kasten58912562012-04-03 10:45:00 -07003189
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 // remove all the tracks that need to be...
3191 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003192 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 for (size_t i=0 ; i<count ; i++) {
3194 const sp<Track>& track = tracksToRemove->itemAt(i);
3195 mActiveTracks.remove(track);
3196 if (track->mainBuffer() != mMixBuffer) {
3197 chain = getEffectChain_l(track->sessionId());
3198 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003199 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003200 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 }
3202 }
3203 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003204 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 }
3206 }
3207 }
3208
3209 // mix buffer must be cleared if all tracks are connected to an
3210 // effect chain as in this case the mixer will not write to
3211 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003212 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3213 // FIXME as a performance optimization, should remember previous zero status
3214 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 }
3216
Glenn Kasten58912562012-04-03 10:45:00 -07003217 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003218 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003219 if (fastTracks > 0) {
3220 mixerStatus = MIXER_TRACKS_READY;
3221 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 return mixerStatus;
3223}
3224
Glenn Kasten66fcab92012-02-24 14:59:21 -08003225/*
3226The derived values that are cached:
3227 - mixBufferSize from frame count * frame size
3228 - activeSleepTime from activeSleepTimeUs()
3229 - idleSleepTime from idleSleepTimeUs()
3230 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3231 - maxPeriod from frame count and sample rate (MIXER only)
3232
3233The parameters that affect these derived values are:
3234 - frame count
3235 - frame size
3236 - sample rate
3237 - device type: A2DP or not
3238 - device latency
3239 - format: PCM or not
3240 - active sleep time
3241 - idle sleep time
3242*/
3243
3244void AudioFlinger::PlaybackThread::cacheParameters_l()
3245{
Glenn Kasten58912562012-04-03 10:45:00 -07003246 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003247 activeSleepTime = activeSleepTimeUs();
3248 idleSleepTime = idleSleepTimeUs();
3249}
3250
Glenn Kastenfff6d712012-01-12 16:38:12 -08003251void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252{
Steve Block3856b092011-10-20 11:56:00 +01003253 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003254 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003256
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 size_t size = mTracks.size();
3258 for (size_t i = 0; i < size; i++) {
3259 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003260 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003261 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 }
3264 }
3265}
3266
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003268int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003270 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271}
3272
3273// deleteTrackName_l() must be called with ThreadBase::mLock held
3274void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3275{
Steve Block3856b092011-10-20 11:56:00 +01003276 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 mAudioMixer->deleteTrackName(name);
3278}
3279
3280// checkForNewParameters_l() must be called with ThreadBase::mLock held
3281bool AudioFlinger::MixerThread::checkForNewParameters_l()
3282{
Glenn Kasten58912562012-04-03 10:45:00 -07003283 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3284 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 bool reconfig = false;
3286
3287 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003288
3289 if (mFastMixer != NULL) {
3290 FastMixerStateQueue *sq = mFastMixer->sq();
3291 FastMixerState *state = sq->begin();
3292 if (!(state->mCommand & FastMixerState::IDLE)) {
3293 previousCommand = state->mCommand;
3294 state->mCommand = FastMixerState::HOT_IDLE;
3295 sq->end();
3296 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3297 } else {
3298 sq->end(false /*didModify*/);
3299 }
3300 }
3301
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 status_t status = NO_ERROR;
3303 String8 keyValuePair = mNewParameters[0];
3304 AudioParameter param = AudioParameter(keyValuePair);
3305 int value;
3306
3307 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3308 reconfig = true;
3309 }
3310 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003311 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 status = BAD_VALUE;
3313 } else {
3314 reconfig = true;
3315 }
3316 }
3317 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003318 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 status = BAD_VALUE;
3320 } else {
3321 reconfig = true;
3322 }
3323 }
3324 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3325 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003326 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 // if frame count is changed after track creation
3328 if (!mTracks.isEmpty()) {
3329 status = INVALID_OPERATION;
3330 } else {
3331 reconfig = true;
3332 }
3333 }
3334 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003335#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003336 // when changing the audio output device, call addBatteryData to notify
3337 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003338 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003339 uint32_t params = 0;
3340 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003341 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003342 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3343 }
3344
3345 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003346 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003347 // check if any other device (except speaker) is on
3348 if (value & deviceWithoutSpeaker ) {
3349 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3350 }
3351
3352 if (params != 0) {
3353 addBatteryData(params);
3354 }
3355 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003356#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003357
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 // forward device change to effects that have requested to be
3359 // aware of attached audio device.
3360 mDevice = (uint32_t)value;
3361 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003362 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 }
3364 }
3365
3366 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003367 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003368 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003370 mOutput->stream->common.standby(&mOutput->stream->common);
3371 mStandby = true;
3372 mBytesWritten = 0;
3373 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003374 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375 }
3376 if (status == NO_ERROR && reconfig) {
3377 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003378 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3379 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003381 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003383 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 if (name < 0) break;
3385 mTracks[i]->mName = name;
3386 // limit track sample rate to 2 x new output sample rate
3387 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3388 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3389 }
3390 }
3391 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3392 }
3393 }
3394
3395 mNewParameters.removeAt(0);
3396
3397 mParamStatus = status;
3398 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003399 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3400 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003401 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 }
Glenn Kasten58912562012-04-03 10:45:00 -07003403
3404 if (!(previousCommand & FastMixerState::IDLE)) {
3405 ALOG_ASSERT(mFastMixer != NULL);
3406 FastMixerStateQueue *sq = mFastMixer->sq();
3407 FastMixerState *state = sq->begin();
3408 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3409 state->mCommand = previousCommand;
3410 sq->end();
3411 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3412 }
3413
Mathias Agopian65ab4712010-07-14 17:59:35 -07003414 return reconfig;
3415}
3416
3417status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3418{
3419 const size_t SIZE = 256;
3420 char buffer[SIZE];
3421 String8 result;
3422
3423 PlaybackThread::dumpInternals(fd, args);
3424
3425 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3426 result.append(buffer);
3427 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003428
3429 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3430 FastMixerDumpState copy = mFastMixerDumpState;
3431 copy.dump(fd);
3432
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 return NO_ERROR;
3434}
3435
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003436uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437{
Glenn Kasten58912562012-04-03 10:45:00 -07003438 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439}
3440
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003441uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003442{
Glenn Kasten58912562012-04-03 10:45:00 -07003443 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003444}
3445
Glenn Kasten66fcab92012-02-24 14:59:21 -08003446void AudioFlinger::MixerThread::cacheParameters_l()
3447{
3448 PlaybackThread::cacheParameters_l();
3449
3450 // FIXME: Relaxed timing because of a certain device that can't meet latency
3451 // Should be reduced to 2x after the vendor fixes the driver issue
3452 // increase threshold again due to low power audio mode. The way this warning
3453 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003454 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003455}
3456
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003458AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3459 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003460 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003461 // mLeftVolFloat, mRightVolFloat
3462 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464}
3465
3466AudioFlinger::DirectOutputThread::~DirectOutputThread()
3467{
3468}
3469
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003470AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3471 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003472)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003474 sp<Track> trackToRemove;
3475
Glenn Kastenfec279f2012-03-08 07:47:15 -08003476 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477
Glenn Kasten952eeb22012-03-06 11:30:57 -08003478 // find out which tracks need to be processed
3479 if (mActiveTracks.size() != 0) {
3480 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003481 // The track died recently
3482 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483
Glenn Kasten952eeb22012-03-06 11:30:57 -08003484 Track* const track = t.get();
3485 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486
Glenn Kasten952eeb22012-03-06 11:30:57 -08003487 // The first time a track is added we wait
3488 // for all its buffers to be filled before processing it
3489 if (cblk->framesReady() && track->isReady() &&
3490 !track->isPaused() && !track->isTerminated())
3491 {
3492 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493
Glenn Kasten952eeb22012-03-06 11:30:57 -08003494 if (track->mFillingUpStatus == Track::FS_FILLED) {
3495 track->mFillingUpStatus = Track::FS_ACTIVE;
3496 mLeftVolFloat = mRightVolFloat = 0;
3497 mLeftVolShort = mRightVolShort = 0;
3498 if (track->mState == TrackBase::RESUMING) {
3499 track->mState = TrackBase::ACTIVE;
3500 rampVolume = true;
3501 }
3502 } else if (cblk->server != 0) {
3503 // If the track is stopped before the first frame was mixed,
3504 // do not apply ramp
3505 rampVolume = true;
3506 }
3507 // compute volume for this track
3508 float left, right;
3509 if (track->isMuted() || mMasterMute || track->isPausing() ||
3510 mStreamTypes[track->streamType()].mute) {
3511 left = right = 0;
3512 if (track->isPausing()) {
3513 track->setPaused();
3514 }
3515 } else {
3516 float typeVolume = mStreamTypes[track->streamType()].volume;
3517 float v = mMasterVolume * typeVolume;
3518 uint32_t vlr = cblk->getVolumeLR();
3519 float v_clamped = v * (vlr & 0xFFFF);
3520 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3521 left = v_clamped/MAX_GAIN;
3522 v_clamped = v * (vlr >> 16);
3523 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3524 right = v_clamped/MAX_GAIN;
3525 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526
Glenn Kasten952eeb22012-03-06 11:30:57 -08003527 if (left != mLeftVolFloat || right != mRightVolFloat) {
3528 mLeftVolFloat = left;
3529 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530
Glenn Kasten952eeb22012-03-06 11:30:57 -08003531 // If audio HAL implements volume control,
3532 // force software volume to nominal value
3533 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3534 left = 1.0f;
3535 right = 1.0f;
3536 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537
Glenn Kasten952eeb22012-03-06 11:30:57 -08003538 // Convert volumes from float to 8.24
3539 uint32_t vl = (uint32_t)(left * (1 << 24));
3540 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541
Glenn Kasten952eeb22012-03-06 11:30:57 -08003542 // Delegate volume control to effect in track effect chain if needed
3543 // only one effect chain can be present on DirectOutputThread, so if
3544 // there is one, the track is connected to it
3545 if (!mEffectChains.isEmpty()) {
3546 // Do not ramp volume if volume is controlled by effect
3547 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 rampVolume = false;
3549 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551
Glenn Kasten952eeb22012-03-06 11:30:57 -08003552 // Convert volumes from 8.24 to 4.12 format
3553 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3554 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3555 leftVol = (uint16_t)v_clamped;
3556 v_clamped = (vr + (1 << 11)) >> 12;
3557 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3558 rightVol = (uint16_t)v_clamped;
3559 } else {
3560 leftVol = mLeftVolShort;
3561 rightVol = mRightVolShort;
3562 rampVolume = false;
3563 }
3564
3565 // reset retry count
3566 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003567 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003568 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003569 } else {
3570 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003571 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3572 // We have consumed all the buffers of this track.
3573 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003574 // TODO: implement behavior for compressed audio
3575 size_t audioHALFrames =
3576 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3577 size_t framesWritten =
3578 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3579 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003580 if (track->isStopped()) {
3581 track->reset();
3582 }
Eric Laurenta011e352012-03-29 15:51:43 -07003583 trackToRemove = track;
3584 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003585 } else {
3586 // No buffers for this track. Give it a few chances to
3587 // fill a buffer, then remove it from active list.
3588 if (--(track->mRetryCount) <= 0) {
3589 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3590 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003592 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 }
3594 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003595 }
3596 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003598 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003599 // remove all the tracks that need to be...
3600 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003601 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003602 mActiveTracks.remove(trackToRemove);
3603 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003604 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003605 trackToRemove->sessionId());
3606 mEffectChains[0]->decActiveTrackCnt();
3607 }
3608 if (trackToRemove->isTerminated()) {
3609 removeTrack_l(trackToRemove);
3610 }
3611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612
Glenn Kastenfec279f2012-03-08 07:47:15 -08003613 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003614}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615
Glenn Kasten000f0e32012-03-01 17:10:56 -08003616void AudioFlinger::DirectOutputThread::threadLoop_mix()
3617{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003618 AudioBufferProvider::Buffer buffer;
3619 size_t frameCount = mFrameCount;
3620 int8_t *curBuf = (int8_t *)mMixBuffer;
3621 // output audio to hardware
3622 while (frameCount) {
3623 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003624 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003625 if (CC_UNLIKELY(buffer.raw == NULL)) {
3626 memset(curBuf, 0, frameCount * mFrameSize);
3627 break;
3628 }
3629 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3630 frameCount -= buffer.frameCount;
3631 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003632 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003633 }
3634 sleepTime = 0;
3635 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003636 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003637
3638 // apply volume
3639
3640 // Do not apply volume on compressed audio
3641 if (!audio_is_linear_pcm(mFormat)) {
3642 return;
3643 }
3644
3645 // convert to signed 16 bit before volume calculation
3646 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3647 size_t count = mFrameCount * mChannelCount;
3648 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3649 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003650 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003651 *dst-- = (int16_t)(*src--^0x80) << 8;
3652 }
3653 }
3654
3655 frameCount = mFrameCount;
3656 int16_t *out = mMixBuffer;
3657 if (rampVolume) {
3658 if (mChannelCount == 1) {
3659 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3660 int32_t vlInc = d / (int32_t)frameCount;
3661 int32_t vl = ((int32_t)mLeftVolShort << 16);
3662 do {
3663 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3664 out++;
3665 vl += vlInc;
3666 } while (--frameCount);
3667
3668 } else {
3669 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3670 int32_t vlInc = d / (int32_t)frameCount;
3671 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3672 int32_t vrInc = d / (int32_t)frameCount;
3673 int32_t vl = ((int32_t)mLeftVolShort << 16);
3674 int32_t vr = ((int32_t)mRightVolShort << 16);
3675 do {
3676 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3677 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3678 out += 2;
3679 vl += vlInc;
3680 vr += vrInc;
3681 } while (--frameCount);
3682 }
3683 } else {
3684 if (mChannelCount == 1) {
3685 do {
3686 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3687 out++;
3688 } while (--frameCount);
3689 } else {
3690 do {
3691 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3692 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3693 out += 2;
3694 } while (--frameCount);
3695 }
3696 }
3697
3698 // convert back to unsigned 8 bit after volume calculation
3699 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3700 size_t count = mFrameCount * mChannelCount;
3701 int16_t *src = mMixBuffer;
3702 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003703 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003704 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3705 }
3706 }
3707
3708 mLeftVolShort = leftVol;
3709 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003710}
3711
3712void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3713{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003714 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003715 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003716 sleepTime = activeSleepTime;
3717 } else {
3718 sleepTime = idleSleepTime;
3719 }
3720 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003721 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 sleepTime = 0;
3723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724}
3725
3726// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003727int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728{
3729 return 0;
3730}
3731
3732// deleteTrackName_l() must be called with ThreadBase::mLock held
3733void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3734{
3735}
3736
3737// checkForNewParameters_l() must be called with ThreadBase::mLock held
3738bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3739{
3740 bool reconfig = false;
3741
3742 while (!mNewParameters.isEmpty()) {
3743 status_t status = NO_ERROR;
3744 String8 keyValuePair = mNewParameters[0];
3745 AudioParameter param = AudioParameter(keyValuePair);
3746 int value;
3747
3748 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3749 // do not accept frame count changes if tracks are open as the track buffer
3750 // size depends on frame count and correct behavior would not be garantied
3751 // if frame count is changed after track creation
3752 if (!mTracks.isEmpty()) {
3753 status = INVALID_OPERATION;
3754 } else {
3755 reconfig = true;
3756 }
3757 }
3758 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003759 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003760 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003762 mOutput->stream->common.standby(&mOutput->stream->common);
3763 mStandby = true;
3764 mBytesWritten = 0;
3765 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003766 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 }
3768 if (status == NO_ERROR && reconfig) {
3769 readOutputParameters();
3770 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3771 }
3772 }
3773
3774 mNewParameters.removeAt(0);
3775
3776 mParamStatus = status;
3777 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003778 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3779 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003780 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781 }
3782 return reconfig;
3783}
3784
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003785uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786{
3787 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003788 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003789 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790 } else {
3791 time = 10000;
3792 }
3793 return time;
3794}
3795
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003796uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797{
3798 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003799 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003800 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801 } else {
3802 time = 10000;
3803 }
3804 return time;
3805}
3806
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003807uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003808{
3809 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003810 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003811 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3812 } else {
3813 time = 10000;
3814 }
3815 return time;
3816}
3817
Glenn Kasten66fcab92012-02-24 14:59:21 -08003818void AudioFlinger::DirectOutputThread::cacheParameters_l()
3819{
3820 PlaybackThread::cacheParameters_l();
3821
3822 // use shorter standby delay as on normal output to release
3823 // hardware resources as soon as possible
3824 standbyDelay = microseconds(activeSleepTime*2);
3825}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003826
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827// ----------------------------------------------------------------------------
3828
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003829AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003830 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003831 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3832 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003834 addOutputTrack(mainThread);
3835}
3836
3837AudioFlinger::DuplicatingThread::~DuplicatingThread()
3838{
3839 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3840 mOutputTracks[i]->destroy();
3841 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003842}
3843
Glenn Kasten000f0e32012-03-01 17:10:56 -08003844void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003845{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003846 // mix buffers...
3847 if (outputsReady(outputTracks)) {
3848 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3849 } else {
3850 memset(mMixBuffer, 0, mixBufferSize);
3851 }
3852 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003853 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003854}
3855
3856void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3857{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003858 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003859 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003860 sleepTime = activeSleepTime;
3861 } else {
3862 sleepTime = idleSleepTime;
3863 }
3864 } else if (mBytesWritten != 0) {
3865 // flush remaining overflow buffers in output tracks
3866 for (size_t i = 0; i < outputTracks.size(); i++) {
3867 if (outputTracks[i]->isActive()) {
3868 sleepTime = 0;
3869 writeFrames = 0;
3870 memset(mMixBuffer, 0, mixBufferSize);
3871 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003873 }
3874 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003875}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003876
Glenn Kasten000f0e32012-03-01 17:10:56 -08003877void AudioFlinger::DuplicatingThread::threadLoop_write()
3878{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003879 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003880 for (size_t i = 0; i < outputTracks.size(); i++) {
3881 outputTracks[i]->write(mMixBuffer, writeFrames);
3882 }
3883 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003884}
Glenn Kasten688a6402012-02-29 07:57:06 -08003885
Glenn Kasten000f0e32012-03-01 17:10:56 -08003886void AudioFlinger::DuplicatingThread::threadLoop_standby()
3887{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003888 // DuplicatingThread implements standby by stopping all tracks
3889 for (size_t i = 0; i < outputTracks.size(); i++) {
3890 outputTracks[i]->stop();
3891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892}
3893
Glenn Kastenfa26a852012-03-06 11:28:04 -08003894void AudioFlinger::DuplicatingThread::saveOutputTracks()
3895{
3896 outputTracks = mOutputTracks;
3897}
3898
3899void AudioFlinger::DuplicatingThread::clearOutputTracks()
3900{
3901 outputTracks.clear();
3902}
3903
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3905{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003906 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003907 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003908 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003909 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910 this,
3911 mSampleRate,
3912 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003913 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 frameCount);
3915 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003916 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003918 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003919 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920 }
3921}
3922
3923void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3924{
3925 Mutex::Autolock _l(mLock);
3926 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003927 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928 mOutputTracks[i]->destroy();
3929 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003930 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931 return;
3932 }
3933 }
Steve Block3856b092011-10-20 11:56:00 +01003934 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935}
3936
Glenn Kasten438b0362012-03-06 11:24:48 -08003937// caller must hold mLock
3938void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939{
3940 mWaitTimeMs = UINT_MAX;
3941 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3942 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003943 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3945 if (waitTimeMs < mWaitTimeMs) {
3946 mWaitTimeMs = waitTimeMs;
3947 }
3948 }
3949 }
3950}
3951
3952
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003953bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954{
3955 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003956 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003958 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003959 return false;
3960 }
3961 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3962 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003963 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 return false;
3965 }
3966 }
3967 return true;
3968}
3969
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003970uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971{
3972 return (mWaitTimeMs * 1000) / 2;
3973}
3974
Glenn Kasten66fcab92012-02-24 14:59:21 -08003975void AudioFlinger::DuplicatingThread::cacheParameters_l()
3976{
3977 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3978 updateWaitTime_l();
3979
3980 MixerThread::cacheParameters_l();
3981}
3982
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983// ----------------------------------------------------------------------------
3984
3985// TrackBase constructor must be called with AudioFlinger::mLock held
3986AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003987 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 const sp<Client>& client,
3989 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003990 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003991 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993 const sp<IMemory>& sharedBuffer,
3994 int sessionId)
3995 : RefBase(),
3996 mThread(thread),
3997 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003998 mCblk(NULL),
3999 // mBuffer
4000 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 mFrameCount(0),
4002 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004003 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004005 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004007 // mChannelCount
4008 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009{
Steve Block3856b092011-10-20 11:56:00 +01004010 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011
Steve Blockb8a80522011-12-20 16:23:08 +00004012 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004013 size_t size = sizeof(audio_track_cblk_t);
4014 uint8_t channelCount = popcount(channelMask);
4015 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4016 if (sharedBuffer == 0) {
4017 size += bufferSize;
4018 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004020 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 mCblkMemory = client->heap()->allocate(size);
4022 if (mCblkMemory != 0) {
4023 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004024 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025 new(mCblk) audio_track_cblk_t();
4026 // clear all buffers
4027 mCblk->frameCount = frameCount;
4028 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004029// uncomment the following lines to quickly test 32-bit wraparound
4030// mCblk->user = 0xffff0000;
4031// mCblk->server = 0xffff0000;
4032// mCblk->userBase = 0xffff0000;
4033// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004034 mChannelCount = channelCount;
4035 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036 if (sharedBuffer == 0) {
4037 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4038 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4039 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004040 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041 mCblk->flags = CBLK_UNDERRUN_ON;
4042 } else {
4043 mBuffer = sharedBuffer->pointer();
4044 }
4045 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4046 }
4047 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004048 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004049 client->heap()->dump("AudioTrack");
4050 return;
4051 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004052 } else {
4053 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004054 // construct the shared structure in-place.
4055 new(mCblk) audio_track_cblk_t();
4056 // clear all buffers
4057 mCblk->frameCount = frameCount;
4058 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004059// uncomment the following lines to quickly test 32-bit wraparound
4060// mCblk->user = 0xffff0000;
4061// mCblk->server = 0xffff0000;
4062// mCblk->userBase = 0xffff0000;
4063// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004064 mChannelCount = channelCount;
4065 mChannelMask = channelMask;
4066 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4067 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4068 // Force underrun condition to avoid false underrun callback until first data is
4069 // written to buffer (other flags are cleared)
4070 mCblk->flags = CBLK_UNDERRUN_ON;
4071 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004072 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073}
4074
4075AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4076{
Glenn Kastena0d68332012-01-27 16:47:15 -08004077 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004078 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004080 } else {
4081 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082 }
4083 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004084 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004085 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004086 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004088 // If the client's reference count drops to zero, the associated destructor
4089 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4090 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091 mClient.clear();
4092 }
4093}
4094
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004095// AudioBufferProvider interface
4096// getNextBuffer() = 0;
4097// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4099{
Glenn Kastene0feee32011-12-13 11:53:26 -08004100 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004102 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004103 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 buffer->frameCount = 0;
4105}
4106
4107bool AudioFlinger::ThreadBase::TrackBase::step() {
4108 bool result;
4109 audio_track_cblk_t* cblk = this->cblk();
4110
4111 result = cblk->stepServer(mFrameCount);
4112 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004113 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004114 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 }
4116 return result;
4117}
4118
4119void AudioFlinger::ThreadBase::TrackBase::reset() {
4120 audio_track_cblk_t* cblk = this->cblk();
4121
4122 cblk->user = 0;
4123 cblk->server = 0;
4124 cblk->userBase = 0;
4125 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004126 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004127 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128}
4129
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4131 return (int)mCblk->sampleRate;
4132}
4133
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4135 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004136 size_t frameSize = cblk->frameSize;
4137 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4138 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139
4140 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004141 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4142 "TrackBase::getBuffer buffer out of range:\n"
4143 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4144 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004146 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147
4148 return bufferStart;
4149}
4150
Eric Laurenta011e352012-03-29 15:51:43 -07004151status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4152{
4153 mSyncEvents.add(event);
4154 return NO_ERROR;
4155}
4156
Mathias Agopian65ab4712010-07-14 17:59:35 -07004157// ----------------------------------------------------------------------------
4158
4159// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4160AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004161 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004163 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004165 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004166 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167 int frameCount,
4168 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004169 int sessionId,
4170 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004171 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004172 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004173 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004174 // mRetryCount initialized later when needed
4175 mSharedBuffer(sharedBuffer),
4176 mStreamType(streamType),
4177 mName(-1), // see note below
4178 mMainBuffer(thread->mixBuffer()),
4179 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004180 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004181 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004182 mFlags(flags),
4183 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004184 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004185 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186{
4187 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4189 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004190 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004191 if (flags & IAudioFlinger::TRACK_FAST) {
4192 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4193 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4194 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004195 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004196 // FIXME This is too eager. We allocate a fast track index before the
4197 // fast track becomes active. Since fast tracks are a scarce resource,
4198 // this means we are potentially denying other more important fast tracks from
4199 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004200 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004201 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004202 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004203 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004204 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004205 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004206 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004207 if (mName < 0) {
4208 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004209 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4210 // then we leak a fast track index. Should swap these two sections, or better yet
4211 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004214 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215}
4216
4217AudioFlinger::PlaybackThread::Track::~Track()
4218{
Steve Block3856b092011-10-20 11:56:00 +01004219 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220 sp<ThreadBase> thread = mThread.promote();
4221 if (thread != 0) {
4222 Mutex::Autolock _l(thread->mLock);
4223 mState = TERMINATED;
4224 }
4225}
4226
4227void AudioFlinger::PlaybackThread::Track::destroy()
4228{
4229 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4230 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004231 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232 // we must acquire a strong reference on this Track before locking mLock
4233 // here so that the destructor is called only when exiting this function.
4234 // On the other hand, as long as Track::destroy() is only called by
4235 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4236 // this Track with its member mTrack.
4237 sp<Track> keep(this);
4238 { // scope for mLock
4239 sp<ThreadBase> thread = mThread.promote();
4240 if (thread != 0) {
4241 if (!isOutputTrack()) {
4242 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004243 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004244
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004245#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004246 // to track the speaker usage
4247 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004248#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 }
4250 AudioSystem::releaseOutput(thread->id());
4251 }
4252 Mutex::Autolock _l(thread->mLock);
4253 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4254 playbackThread->destroyTrack_l(this);
4255 }
4256 }
4257}
4258
Glenn Kasten288ed212012-04-25 17:52:27 -07004259/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4260{
Glenn Kastene213c862012-04-25 13:46:15 -07004261 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4262 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004263}
4264
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4266{
Glenn Kasten83d86532012-01-17 14:39:34 -08004267 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004268 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004269 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004270 } else {
4271 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4272 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004273 track_state state = mState;
4274 char stateChar;
4275 switch (state) {
4276 case IDLE:
4277 stateChar = 'I';
4278 break;
4279 case TERMINATED:
4280 stateChar = 'T';
4281 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004282 case STOPPING_1:
4283 stateChar = 's';
4284 break;
4285 case STOPPING_2:
4286 stateChar = '5';
4287 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004288 case STOPPED:
4289 stateChar = 'S';
4290 break;
4291 case RESUMING:
4292 stateChar = 'R';
4293 break;
4294 case ACTIVE:
4295 stateChar = 'A';
4296 break;
4297 case PAUSING:
4298 stateChar = 'p';
4299 break;
4300 case PAUSED:
4301 stateChar = 'P';
4302 break;
Eric Laurent29864602012-05-08 18:57:51 -07004303 case FLUSHED:
4304 stateChar = 'F';
4305 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004306 default:
4307 stateChar = '?';
4308 break;
4309 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004310 char nowInUnderrun;
4311 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4312 case UNDERRUN_FULL:
4313 nowInUnderrun = ' ';
4314 break;
4315 case UNDERRUN_PARTIAL:
4316 nowInUnderrun = '<';
4317 break;
4318 case UNDERRUN_EMPTY:
4319 nowInUnderrun = '*';
4320 break;
4321 default:
4322 nowInUnderrun = '?';
4323 break;
4324 }
Glenn Kastene213c862012-04-25 13:46:15 -07004325 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4326 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004327 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 mStreamType,
4329 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004330 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 mSessionId,
4332 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004333 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004334 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 mMute,
4336 mFillingUpStatus,
4337 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004338 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4339 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004340 mCblk->server,
4341 mCblk->user,
4342 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004343 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004344 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004345 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004346 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347}
4348
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004349// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004350status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004351 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004353 audio_track_cblk_t* cblk = this->cblk();
4354 uint32_t framesReady;
4355 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004357 // Check if last stepServer failed, try to step now
4358 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004359 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4360 // Since the fast mixer is higher priority than client callback thread,
4361 // it does not result in priority inversion for client.
4362 // But a non-blocking solution would be preferable to avoid
4363 // fast mixer being unable to tryLock(), and
4364 // to avoid the extra context switches if the client wakes up,
4365 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004366 if (!step()) goto getNextBuffer_exit;
4367 ALOGV("stepServer recovered");
4368 mStepServerFailed = false;
4369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370
Glenn Kasten288ed212012-04-25 17:52:27 -07004371 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004372 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004374 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 uint32_t s = cblk->server;
4376 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4377
4378 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4379 if (framesReq > framesReady) {
4380 framesReq = framesReady;
4381 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004382 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383 framesReq = bufferEnd - s;
4384 }
4385
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004386 buffer->raw = getBuffer(s, framesReq);
4387 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004389 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004391 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392
4393getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004394 buffer->raw = NULL;
4395 buffer->frameCount = 0;
4396 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4397 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398}
4399
Glenn Kasten288ed212012-04-25 17:52:27 -07004400// Note that framesReady() takes a mutex on the control block using tryLock().
4401// This could result in priority inversion if framesReady() is called by the normal mixer,
4402// as the normal mixer thread runs at lower
4403// priority than the client's callback thread: there is a short window within framesReady()
4404// during which the normal mixer could be preempted, and the client callback would block.
4405// Another problem can occur if framesReady() is called by the fast mixer:
4406// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4407// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4408size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004409 return mCblk->framesReady();
4410}
4411
Glenn Kasten288ed212012-04-25 17:52:27 -07004412// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004414 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415
John Grossman4ff14ba2012-02-08 16:37:41 -08004416 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4418 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004419 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 return true;
4421 }
4422 return false;
4423}
4424
Glenn Kasten3acbd052012-02-28 10:39:56 -08004425status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004426 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427{
4428 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004429 ALOGV("start(%d), calling pid %d session %d",
4430 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004431
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 sp<ThreadBase> thread = mThread.promote();
4433 if (thread != 0) {
4434 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004435 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 // here the track could be either new, or restarted
4437 // in both cases "unstop" the track
4438 if (mState == PAUSED) {
4439 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004440 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 } else {
4442 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004443 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 }
4445
4446 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4447 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004448 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004450
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004451#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004452 // to track the speaker usage
4453 if (status == NO_ERROR) {
4454 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4455 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004456#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 }
4458 if (status == NO_ERROR) {
4459 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4460 playbackThread->addTrack_l(this);
4461 } else {
4462 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004463 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 }
4465 } else {
4466 status = BAD_VALUE;
4467 }
4468 return status;
4469}
4470
4471void AudioFlinger::PlaybackThread::Track::stop()
4472{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004473 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 sp<ThreadBase> thread = mThread.promote();
4475 if (thread != 0) {
4476 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004477 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004478 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 // If the track is not active (PAUSED and buffers full), flush buffers
4480 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4481 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4482 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004483 mState = STOPPED;
4484 } else if (!isFastTrack()) {
4485 mState = STOPPED;
4486 } else {
4487 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4488 // and then to STOPPED and reset() when presentation is complete
4489 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004491 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492 }
4493 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4494 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004495 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004497
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004498#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004499 // to track the speaker usage
4500 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004501#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 }
4503 }
4504}
4505
4506void AudioFlinger::PlaybackThread::Track::pause()
4507{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004508 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 sp<ThreadBase> thread = mThread.promote();
4510 if (thread != 0) {
4511 Mutex::Autolock _l(thread->mLock);
4512 if (mState == ACTIVE || mState == RESUMING) {
4513 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004514 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 if (!isOutputTrack()) {
4516 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004517 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004518 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004519
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004520#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004521 // to track the speaker usage
4522 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004523#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 }
4525 }
4526 }
4527}
4528
4529void AudioFlinger::PlaybackThread::Track::flush()
4530{
Steve Block3856b092011-10-20 11:56:00 +01004531 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 sp<ThreadBase> thread = mThread.promote();
4533 if (thread != 0) {
4534 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004535 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4536 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 return;
4538 }
4539 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004540 // FLUSHED state
4541 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004542 // do not reset the track if it is still in the process of being stopped or paused.
4543 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004544 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004545 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004546 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4547 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4548 reset();
4549 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 }
4551}
4552
4553void AudioFlinger::PlaybackThread::Track::reset()
4554{
4555 // Do not reset twice to avoid discarding data written just after a flush and before
4556 // the audioflinger thread detects the track is stopped.
4557 if (!mResetDone) {
4558 TrackBase::reset();
4559 // Force underrun condition to avoid false underrun callback until first data is
4560 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004561 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4562 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563 mFillingUpStatus = FS_FILLING;
4564 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004565 if (mState == FLUSHED) {
4566 mState = IDLE;
4567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 }
4569}
4570
4571void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4572{
4573 mMute = muted;
4574}
4575
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4577{
4578 status_t status = DEAD_OBJECT;
4579 sp<ThreadBase> thread = mThread.promote();
4580 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004581 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4582 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 }
4584 return status;
4585}
4586
4587void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4588{
4589 mAuxEffectId = EffectId;
4590 mAuxBuffer = buffer;
4591}
4592
Eric Laurenta011e352012-03-29 15:51:43 -07004593bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4594 size_t audioHalFrames)
4595{
4596 // a track is considered presented when the total number of frames written to audio HAL
4597 // corresponds to the number of frames written when presentationComplete() is called for the
4598 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4599 if (mPresentationCompleteFrames == 0) {
4600 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4601 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4602 mPresentationCompleteFrames, audioHalFrames);
4603 }
4604 if (framesWritten >= mPresentationCompleteFrames) {
4605 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4606 mSessionId, framesWritten);
4607 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004608 return true;
4609 }
4610 return false;
4611}
4612
4613void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4614{
4615 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4616 if (mSyncEvents[i]->type() == type) {
4617 mSyncEvents[i]->trigger();
4618 mSyncEvents.removeAt(i);
4619 i--;
4620 }
4621 }
4622}
4623
Glenn Kasten58912562012-04-03 10:45:00 -07004624// implement VolumeBufferProvider interface
4625
4626uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4627{
4628 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4629 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4630 uint32_t vlr = mCblk->getVolumeLR();
4631 uint32_t vl = vlr & 0xFFFF;
4632 uint32_t vr = vlr >> 16;
4633 // track volumes come from shared memory, so can't be trusted and must be clamped
4634 if (vl > MAX_GAIN_INT) {
4635 vl = MAX_GAIN_INT;
4636 }
4637 if (vr > MAX_GAIN_INT) {
4638 vr = MAX_GAIN_INT;
4639 }
4640 // now apply the cached master volume and stream type volume;
4641 // this is trusted but lacks any synchronization or barrier so may be stale
4642 float v = mCachedVolume;
4643 vl *= v;
4644 vr *= v;
4645 // re-combine into U4.16
4646 vlr = (vr << 16) | (vl & 0xFFFF);
4647 // FIXME look at mute, pause, and stop flags
4648 return vlr;
4649}
Eric Laurenta011e352012-03-29 15:51:43 -07004650
Eric Laurent29864602012-05-08 18:57:51 -07004651status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4652{
4653 if (mState == TERMINATED || mState == PAUSED ||
4654 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4655 (mState == STOPPED)))) {
4656 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4657 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4658 event->cancel();
4659 return INVALID_OPERATION;
4660 }
4661 TrackBase::setSyncEvent(event);
4662 return NO_ERROR;
4663}
4664
John Grossman4ff14ba2012-02-08 16:37:41 -08004665// timed audio tracks
4666
4667sp<AudioFlinger::PlaybackThread::TimedTrack>
4668AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004669 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004670 const sp<Client>& client,
4671 audio_stream_type_t streamType,
4672 uint32_t sampleRate,
4673 audio_format_t format,
4674 uint32_t channelMask,
4675 int frameCount,
4676 const sp<IMemory>& sharedBuffer,
4677 int sessionId) {
4678 if (!client->reserveTimedTrack())
4679 return NULL;
4680
Glenn Kastena0356762012-03-19 10:38:51 -07004681 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004682 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4683 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004684}
4685
4686AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004687 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004688 const sp<Client>& client,
4689 audio_stream_type_t streamType,
4690 uint32_t sampleRate,
4691 audio_format_t format,
4692 uint32_t channelMask,
4693 int frameCount,
4694 const sp<IMemory>& sharedBuffer,
4695 int sessionId)
4696 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004697 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004698 mQueueHeadInFlight(false),
4699 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004700 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004701 mTimedSilenceBuffer(NULL),
4702 mTimedSilenceBufferSize(0),
4703 mTimedAudioOutputOnTime(false),
4704 mMediaTimeTransformValid(false)
4705{
4706 LocalClock lc;
4707 mLocalTimeFreq = lc.getLocalFreq();
4708
4709 mLocalTimeToSampleTransform.a_zero = 0;
4710 mLocalTimeToSampleTransform.b_zero = 0;
4711 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4712 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4713 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4714 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004715
4716 mMediaTimeToSampleTransform.a_zero = 0;
4717 mMediaTimeToSampleTransform.b_zero = 0;
4718 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4719 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4720 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4721 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004722}
4723
4724AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4725 mClient->releaseTimedTrack();
4726 delete [] mTimedSilenceBuffer;
4727}
4728
4729status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4730 size_t size, sp<IMemory>* buffer) {
4731
4732 Mutex::Autolock _l(mTimedBufferQueueLock);
4733
4734 trimTimedBufferQueue_l();
4735
4736 // lazily initialize the shared memory heap for timed buffers
4737 if (mTimedMemoryDealer == NULL) {
4738 const int kTimedBufferHeapSize = 512 << 10;
4739
4740 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4741 "AudioFlingerTimed");
4742 if (mTimedMemoryDealer == NULL)
4743 return NO_MEMORY;
4744 }
4745
4746 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4747 if (newBuffer == NULL) {
4748 newBuffer = mTimedMemoryDealer->allocate(size);
4749 if (newBuffer == NULL)
4750 return NO_MEMORY;
4751 }
4752
4753 *buffer = newBuffer;
4754 return NO_ERROR;
4755}
4756
4757// caller must hold mTimedBufferQueueLock
4758void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4759 int64_t mediaTimeNow;
4760 {
4761 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4762 if (!mMediaTimeTransformValid)
4763 return;
4764
4765 int64_t targetTimeNow;
4766 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4767 ? mCCHelper.getCommonTime(&targetTimeNow)
4768 : mCCHelper.getLocalTime(&targetTimeNow);
4769
4770 if (OK != res)
4771 return;
4772
4773 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4774 &mediaTimeNow)) {
4775 return;
4776 }
4777 }
4778
John Grossman1c345192012-03-27 14:00:17 -07004779 size_t trimEnd;
4780 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004781 int64_t bufEnd;
4782
John Grossmanc95cfbb2012-04-12 11:53:11 -07004783 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4784 // We have a next buffer. Just use its PTS as the PTS of the frame
4785 // following the last frame in this buffer. If the stream is sparse
4786 // (ie, there are deliberate gaps left in the stream which should be
4787 // filled with silence by the TimedAudioTrack), then this can result
4788 // in one extra buffer being left un-trimmed when it could have
4789 // been. In general, this is not typical, and we would rather
4790 // optimized away the TS calculation below for the more common case
4791 // where PTSes are contiguous.
4792 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4793 } else {
4794 // We have no next buffer. Compute the PTS of the frame following
4795 // the last frame in this buffer by computing the duration of of
4796 // this frame in media time units and adding it to the PTS of the
4797 // buffer.
4798 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4799 / mCblk->frameSize;
4800
4801 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4802 &bufEnd)) {
4803 ALOGE("Failed to convert frame count of %lld to media time"
4804 " duration" " (scale factor %d/%u) in %s",
4805 frameCount,
4806 mMediaTimeToSampleTransform.a_to_b_numer,
4807 mMediaTimeToSampleTransform.a_to_b_denom,
4808 __PRETTY_FUNCTION__);
4809 break;
4810 }
4811 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004812 }
John Grossman9fbdee12012-03-26 17:51:46 -07004813
4814 if (bufEnd > mediaTimeNow)
4815 break;
4816
4817 // Is the buffer we want to use in the middle of a mix operation right
4818 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4819 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004820 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004821 mTrimQueueHeadOnRelease = true;
4822 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004823 }
4824
John Grossman9fbdee12012-03-26 17:51:46 -07004825 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004826 if (trimStart < trimEnd) {
4827 // Update the bookkeeping for framesReady()
4828 for (size_t i = trimStart; i < trimEnd; ++i) {
4829 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4830 }
4831
4832 // Now actually remove the buffers from the queue.
4833 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004834 }
4835}
4836
John Grossman1c345192012-03-27 14:00:17 -07004837void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4838 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004839 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4840 "%s called (reason \"%s\"), but timed buffer queue has no"
4841 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004842
4843 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4844 mTimedBufferQueue.removeAt(0);
4845}
4846
4847void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4848 const TimedBuffer& buf,
4849 const char* logTag) {
4850 uint32_t bufBytes = buf.buffer()->size();
4851 uint32_t consumedAlready = buf.position();
4852
Eric Laurentb388e532012-04-14 13:32:48 -07004853 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004854 "Bad bookkeeping while updating frames pending. Timed buffer is"
4855 " only %u bytes long, but claims to have consumed %u"
4856 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004857 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004858
4859 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004860 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4861 "Bad bookkeeping while updating frames pending. Should have at"
4862 " least %u queued frames, but we think we have only %u. (update"
4863 " reason: \"%s\")",
4864 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004865
4866 mFramesPendingInQueue -= bufFrames;
4867}
4868
John Grossman4ff14ba2012-02-08 16:37:41 -08004869status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4870 const sp<IMemory>& buffer, int64_t pts) {
4871
4872 {
4873 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4874 if (!mMediaTimeTransformValid)
4875 return INVALID_OPERATION;
4876 }
4877
4878 Mutex::Autolock _l(mTimedBufferQueueLock);
4879
John Grossman1c345192012-03-27 14:00:17 -07004880 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4881 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004882 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4883
4884 return NO_ERROR;
4885}
4886
4887status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4888 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4889
John Grossman1c345192012-03-27 14:00:17 -07004890 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4891 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4892 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004893
4894 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4895 target == TimedAudioTrack::COMMON_TIME)) {
4896 return BAD_VALUE;
4897 }
4898
4899 Mutex::Autolock lock(mMediaTimeTransformLock);
4900 mMediaTimeTransform = xform;
4901 mMediaTimeTransformTarget = target;
4902 mMediaTimeTransformValid = true;
4903
4904 return NO_ERROR;
4905}
4906
4907#define min(a, b) ((a) < (b) ? (a) : (b))
4908
4909// implementation of getNextBuffer for tracks whose buffers have timestamps
4910status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4911 AudioBufferProvider::Buffer* buffer, int64_t pts)
4912{
4913 if (pts == AudioBufferProvider::kInvalidPTS) {
4914 buffer->raw = 0;
4915 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004916 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004917 return INVALID_OPERATION;
4918 }
4919
John Grossman4ff14ba2012-02-08 16:37:41 -08004920 Mutex::Autolock _l(mTimedBufferQueueLock);
4921
John Grossman9fbdee12012-03-26 17:51:46 -07004922 ALOG_ASSERT(!mQueueHeadInFlight,
4923 "getNextBuffer called without releaseBuffer!");
4924
John Grossman4ff14ba2012-02-08 16:37:41 -08004925 while (true) {
4926
4927 // if we have no timed buffers, then fail
4928 if (mTimedBufferQueue.isEmpty()) {
4929 buffer->raw = 0;
4930 buffer->frameCount = 0;
4931 return NOT_ENOUGH_DATA;
4932 }
4933
4934 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4935
4936 // calculate the PTS of the head of the timed buffer queue expressed in
4937 // local time
4938 int64_t headLocalPTS;
4939 {
4940 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4941
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004942 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004943
4944 if (mMediaTimeTransform.a_to_b_denom == 0) {
4945 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004946 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004947 return NO_ERROR;
4948 }
4949
4950 int64_t transformedPTS;
4951 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4952 &transformedPTS)) {
4953 // the transform failed. this shouldn't happen, but if it does
4954 // then just drop this buffer
4955 ALOGW("timedGetNextBuffer transform failed");
4956 buffer->raw = 0;
4957 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004958 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004959 return NO_ERROR;
4960 }
4961
4962 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4963 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4964 &headLocalPTS)) {
4965 buffer->raw = 0;
4966 buffer->frameCount = 0;
4967 return INVALID_OPERATION;
4968 }
4969 } else {
4970 headLocalPTS = transformedPTS;
4971 }
4972 }
4973
4974 // adjust the head buffer's PTS to reflect the portion of the head buffer
4975 // that has already been consumed
4976 int64_t effectivePTS = headLocalPTS +
4977 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4978
4979 // Calculate the delta in samples between the head of the input buffer
4980 // queue and the start of the next output buffer that will be written.
4981 // If the transformation fails because of over or underflow, it means
4982 // that the sample's position in the output stream is so far out of
4983 // whack that it should just be dropped.
4984 int64_t sampleDelta;
4985 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4986 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004987 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4988 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004989 continue;
4990 }
4991 if (!mLocalTimeToSampleTransform.doForwardTransform(
4992 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004993 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004994 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004995 continue;
4996 }
4997
John Grossman1c345192012-03-27 14:00:17 -07004998 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4999 " sampleDelta=[%d.%08x]",
5000 head.pts(), head.position(), pts,
5001 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5002 + (sampleDelta >> 32)),
5003 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005004
5005 // if the delta between the ideal placement for the next input sample and
5006 // the current output position is within this threshold, then we will
5007 // concatenate the next input samples to the previous output
5008 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005009 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005010
5011 // if this is the first buffer of audio that we're emitting from this track
5012 // then it should be almost exactly on time.
5013 const int64_t kSampleStartupThreshold = 1LL << 32;
5014
5015 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005016 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005017 // the next input is close enough to being on time, so concatenate it
5018 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005019 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005020
John Grossman1c345192012-03-27 14:00:17 -07005021 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5022 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005023 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005024 }
5025
5026 // Looks like our output is not on time. Reset our on timed status.
5027 // Next time we mix samples from our input queue, then should be within
5028 // the StartupThreshold.
5029 mTimedAudioOutputOnTime = false;
5030 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005031 // the gap between the current output position and the proper start of
5032 // the next input sample is too big, so fill it with silence
5033 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5034
John Grossman9fbdee12012-03-26 17:51:46 -07005035 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005036 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5037 return NO_ERROR;
5038 } else {
5039 // the next input sample is late
5040 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5041 size_t onTimeSamplePosition =
5042 head.position() + lateFrames * mCblk->frameSize;
5043
5044 if (onTimeSamplePosition > head.buffer()->size()) {
5045 // all the remaining samples in the head are too late, so
5046 // drop it and move on
5047 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005048 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005049 continue;
5050 } else {
5051 // skip over the late samples
5052 head.setPosition(onTimeSamplePosition);
5053
5054 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005055 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005056
5057 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5058 return NO_ERROR;
5059 }
5060 }
5061 }
5062}
5063
5064// Yield samples from the timed buffer queue head up to the given output
5065// buffer's capacity.
5066//
5067// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005068void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005069 AudioBufferProvider::Buffer* buffer) {
5070
5071 const TimedBuffer& head = mTimedBufferQueue[0];
5072
5073 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5074 head.position());
5075
5076 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5077 mCblk->frameSize);
5078 size_t framesRequested = buffer->frameCount;
5079 buffer->frameCount = min(framesLeftInHead, framesRequested);
5080
John Grossman9fbdee12012-03-26 17:51:46 -07005081 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005082 mTimedAudioOutputOnTime = true;
5083}
5084
5085// Yield samples of silence up to the given output buffer's capacity
5086//
5087// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005088void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005089 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5090
5091 // lazily allocate a buffer filled with silence
5092 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5093 delete [] mTimedSilenceBuffer;
5094 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5095 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5096 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5097 }
5098
5099 buffer->raw = mTimedSilenceBuffer;
5100 size_t framesRequested = buffer->frameCount;
5101 buffer->frameCount = min(numFrames, framesRequested);
5102
5103 mTimedAudioOutputOnTime = false;
5104}
5105
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005106// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005107void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5108 AudioBufferProvider::Buffer* buffer) {
5109
5110 Mutex::Autolock _l(mTimedBufferQueueLock);
5111
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005112 // If the buffer which was just released is part of the buffer at the head
5113 // of the queue, be sure to update the amt of the buffer which has been
5114 // consumed. If the buffer being returned is not part of the head of the
5115 // queue, its either because the buffer is part of the silence buffer, or
5116 // because the head of the timed queue was trimmed after the mixer called
5117 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005118 if (buffer->raw == mTimedSilenceBuffer) {
5119 ALOG_ASSERT(!mQueueHeadInFlight,
5120 "Queue head in flight during release of silence buffer!");
5121 goto done;
5122 }
5123
5124 ALOG_ASSERT(mQueueHeadInFlight,
5125 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5126 " head in flight.");
5127
5128 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005129 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005130
5131 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005132 void* end = reinterpret_cast<void*>(
5133 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5134 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005135
John Grossman9fbdee12012-03-26 17:51:46 -07005136 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5137 "released buffer not within the head of the timed buffer"
5138 " queue; qHead = [%p, %p], released buffer = %p",
5139 start, end, buffer->raw);
5140
5141 head.setPosition(head.position() +
5142 (buffer->frameCount * mCblk->frameSize));
5143 mQueueHeadInFlight = false;
5144
John Grossman1c345192012-03-27 14:00:17 -07005145 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5146 "Bad bookkeeping during releaseBuffer! Should have at"
5147 " least %u queued frames, but we think we have only %u",
5148 buffer->frameCount, mFramesPendingInQueue);
5149
5150 mFramesPendingInQueue -= buffer->frameCount;
5151
John Grossman9fbdee12012-03-26 17:51:46 -07005152 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5153 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005154 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005155 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005156 }
John Grossman9fbdee12012-03-26 17:51:46 -07005157 } else {
5158 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5159 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005160 }
5161
John Grossman9fbdee12012-03-26 17:51:46 -07005162done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005163 buffer->raw = 0;
5164 buffer->frameCount = 0;
5165}
5166
Glenn Kasten288ed212012-04-25 17:52:27 -07005167size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005168 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005169 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005170}
5171
5172AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5173 : mPTS(0), mPosition(0) {}
5174
5175AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5176 const sp<IMemory>& buffer, int64_t pts)
5177 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5178
Mathias Agopian65ab4712010-07-14 17:59:35 -07005179// ----------------------------------------------------------------------------
5180
5181// RecordTrack constructor must be called with AudioFlinger::mLock held
5182AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005183 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005184 const sp<Client>& client,
5185 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005186 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005187 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005189 int sessionId)
5190 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005191 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005192 mOverflow(false)
5193{
5194 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005195 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5196 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5197 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5198 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5199 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5200 } else {
5201 mCblk->frameSize = sizeof(int8_t);
5202 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 }
5204}
5205
5206AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5207{
5208 sp<ThreadBase> thread = mThread.promote();
5209 if (thread != 0) {
5210 AudioSystem::releaseInput(thread->id());
5211 }
5212}
5213
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005214// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005215status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216{
5217 audio_track_cblk_t* cblk = this->cblk();
5218 uint32_t framesAvail;
5219 uint32_t framesReq = buffer->frameCount;
5220
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005221 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005222 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005223 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005224 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005225 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005226 }
5227
5228 framesAvail = cblk->framesAvailable_l();
5229
Glenn Kastenf6b16782011-12-15 09:51:17 -08005230 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005231 uint32_t s = cblk->server;
5232 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5233
5234 if (framesReq > framesAvail) {
5235 framesReq = framesAvail;
5236 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005237 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005238 framesReq = bufferEnd - s;
5239 }
5240
5241 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005242 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005243
5244 buffer->frameCount = framesReq;
5245 return NO_ERROR;
5246 }
5247
5248getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005249 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005250 buffer->frameCount = 0;
5251 return NOT_ENOUGH_DATA;
5252}
5253
Glenn Kasten3acbd052012-02-28 10:39:56 -08005254status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005255 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005256{
5257 sp<ThreadBase> thread = mThread.promote();
5258 if (thread != 0) {
5259 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005260 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261 } else {
5262 return BAD_VALUE;
5263 }
5264}
5265
5266void AudioFlinger::RecordThread::RecordTrack::stop()
5267{
5268 sp<ThreadBase> thread = mThread.promote();
5269 if (thread != 0) {
5270 RecordThread *recordThread = (RecordThread *)thread.get();
5271 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005272 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005273 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005274 // read from buffer
5275 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276 }
5277}
5278
5279void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5280{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005281 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005282 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005283 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005284 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005285 mSessionId,
5286 mFrameCount,
5287 mState,
5288 mCblk->sampleRate,
5289 mCblk->server,
5290 mCblk->user);
5291}
5292
5293
5294// ----------------------------------------------------------------------------
5295
5296AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005297 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005298 DuplicatingThread *sourceThread,
5299 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005300 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005301 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005303 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5304 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005305 mActive(false), mSourceThread(sourceThread)
5306{
5307
Mathias Agopian65ab4712010-07-14 17:59:35 -07005308 if (mCblk != NULL) {
5309 mCblk->flags |= CBLK_DIRECTION_OUT;
5310 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311 mOutBuffer.frameCount = 0;
5312 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005313 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005314 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5315 mCblk, mBuffer, mCblk->buffers,
5316 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005318 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005319 }
5320}
5321
5322AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5323{
5324 clearBufferQueue();
5325}
5326
Glenn Kasten3acbd052012-02-28 10:39:56 -08005327status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005328 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005330 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 if (status != NO_ERROR) {
5332 return status;
5333 }
5334
5335 mActive = true;
5336 mRetryCount = 127;
5337 return status;
5338}
5339
5340void AudioFlinger::PlaybackThread::OutputTrack::stop()
5341{
5342 Track::stop();
5343 clearBufferQueue();
5344 mOutBuffer.frameCount = 0;
5345 mActive = false;
5346}
5347
5348bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5349{
5350 Buffer *pInBuffer;
5351 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005352 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353 bool outputBufferFull = false;
5354 inBuffer.frameCount = frames;
5355 inBuffer.i16 = data;
5356
5357 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5358
5359 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005360 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361 sp<ThreadBase> thread = mThread.promote();
5362 if (thread != 0) {
5363 MixerThread *mixerThread = (MixerThread *)thread.get();
5364 if (mCblk->frameCount > frames){
5365 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5366 uint32_t startFrames = (mCblk->frameCount - frames);
5367 pInBuffer = new Buffer;
5368 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5369 pInBuffer->frameCount = startFrames;
5370 pInBuffer->i16 = pInBuffer->mBuffer;
5371 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5372 mBufferQueue.add(pInBuffer);
5373 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005374 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375 }
5376 }
5377 }
5378 }
5379
5380 while (waitTimeLeftMs) {
5381 // First write pending buffers, then new data
5382 if (mBufferQueue.size()) {
5383 pInBuffer = mBufferQueue.itemAt(0);
5384 } else {
5385 pInBuffer = &inBuffer;
5386 }
5387
5388 if (pInBuffer->frameCount == 0) {
5389 break;
5390 }
5391
5392 if (mOutBuffer.frameCount == 0) {
5393 mOutBuffer.frameCount = pInBuffer->frameCount;
5394 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005395 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005396 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397 outputBufferFull = true;
5398 break;
5399 }
5400 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5401 if (waitTimeLeftMs >= waitTimeMs) {
5402 waitTimeLeftMs -= waitTimeMs;
5403 } else {
5404 waitTimeLeftMs = 0;
5405 }
5406 }
5407
5408 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5409 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5410 mCblk->stepUser(outFrames);
5411 pInBuffer->frameCount -= outFrames;
5412 pInBuffer->i16 += outFrames * channelCount;
5413 mOutBuffer.frameCount -= outFrames;
5414 mOutBuffer.i16 += outFrames * channelCount;
5415
5416 if (pInBuffer->frameCount == 0) {
5417 if (mBufferQueue.size()) {
5418 mBufferQueue.removeAt(0);
5419 delete [] pInBuffer->mBuffer;
5420 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005421 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 } else {
5423 break;
5424 }
5425 }
5426 }
5427
5428 // If we could not write all frames, allocate a buffer and queue it for next time.
5429 if (inBuffer.frameCount) {
5430 sp<ThreadBase> thread = mThread.promote();
5431 if (thread != 0 && !thread->standby()) {
5432 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5433 pInBuffer = new Buffer;
5434 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5435 pInBuffer->frameCount = inBuffer.frameCount;
5436 pInBuffer->i16 = pInBuffer->mBuffer;
5437 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5438 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005439 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005441 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 }
5443 }
5444 }
5445
5446 // Calling write() with a 0 length buffer, means that no more data will be written:
5447 // If no more buffers are pending, fill output track buffer to make sure it is started
5448 // by output mixer.
5449 if (frames == 0 && mBufferQueue.size() == 0) {
5450 if (mCblk->user < mCblk->frameCount) {
5451 frames = mCblk->frameCount - mCblk->user;
5452 pInBuffer = new Buffer;
5453 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5454 pInBuffer->frameCount = frames;
5455 pInBuffer->i16 = pInBuffer->mBuffer;
5456 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5457 mBufferQueue.add(pInBuffer);
5458 } else if (mActive) {
5459 stop();
5460 }
5461 }
5462
5463 return outputBufferFull;
5464}
5465
5466status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5467{
5468 int active;
5469 status_t result;
5470 audio_track_cblk_t* cblk = mCblk;
5471 uint32_t framesReq = buffer->frameCount;
5472
Steve Block3856b092011-10-20 11:56:00 +01005473// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474 buffer->frameCount = 0;
5475
5476 uint32_t framesAvail = cblk->framesAvailable();
5477
5478
5479 if (framesAvail == 0) {
5480 Mutex::Autolock _l(cblk->lock);
5481 goto start_loop_here;
5482 while (framesAvail == 0) {
5483 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005484 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005485 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005486 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 }
5488 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5489 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005490 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 }
5492 // read the server count again
5493 start_loop_here:
5494 framesAvail = cblk->framesAvailable_l();
5495 }
5496 }
5497
5498// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005499// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500// }
5501
5502 if (framesReq > framesAvail) {
5503 framesReq = framesAvail;
5504 }
5505
5506 uint32_t u = cblk->user;
5507 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5508
Marco Nelissena1472d92012-03-30 14:36:54 -07005509 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 framesReq = bufferEnd - u;
5511 }
5512
5513 buffer->frameCount = framesReq;
5514 buffer->raw = (void *)cblk->buffer(u);
5515 return NO_ERROR;
5516}
5517
5518
5519void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5520{
5521 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005522
5523 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005524 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 delete [] pBuffer->mBuffer;
5526 delete pBuffer;
5527 }
5528 mBufferQueue.clear();
5529}
5530
5531// ----------------------------------------------------------------------------
5532
5533AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5534 : RefBase(),
5535 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005536 // 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 -07005537 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005538 mPid(pid),
5539 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540{
5541 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5542}
5543
5544// Client destructor must be called with AudioFlinger::mLock held
5545AudioFlinger::Client::~Client()
5546{
5547 mAudioFlinger->removeClient_l(mPid);
5548}
5549
Glenn Kasten435dbe62012-01-30 10:15:48 -08005550sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551{
5552 return mMemoryDealer;
5553}
5554
John Grossman4ff14ba2012-02-08 16:37:41 -08005555// Reserve one of the limited slots for a timed audio track associated
5556// with this client
5557bool AudioFlinger::Client::reserveTimedTrack()
5558{
5559 const int kMaxTimedTracksPerClient = 4;
5560
5561 Mutex::Autolock _l(mTimedTrackLock);
5562
5563 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5564 ALOGW("can not create timed track - pid %d has exceeded the limit",
5565 mPid);
5566 return false;
5567 }
5568
5569 mTimedTrackCount++;
5570 return true;
5571}
5572
5573// Release a slot for a timed audio track
5574void AudioFlinger::Client::releaseTimedTrack()
5575{
5576 Mutex::Autolock _l(mTimedTrackLock);
5577 mTimedTrackCount--;
5578}
5579
Mathias Agopian65ab4712010-07-14 17:59:35 -07005580// ----------------------------------------------------------------------------
5581
5582AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5583 const sp<IAudioFlingerClient>& client,
5584 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005585 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586{
5587}
5588
5589AudioFlinger::NotificationClient::~NotificationClient()
5590{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591}
5592
5593void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5594{
5595 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005596 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597}
5598
5599// ----------------------------------------------------------------------------
5600
5601AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5602 : BnAudioTrack(),
5603 mTrack(track)
5604{
5605}
5606
5607AudioFlinger::TrackHandle::~TrackHandle() {
5608 // just stop the track on deletion, associated resources
5609 // will be freed from the main thread once all pending buffers have
5610 // been played. Unless it's not in the active track list, in which
5611 // case we free everything now...
5612 mTrack->destroy();
5613}
5614
Glenn Kasten90716c52012-01-26 13:40:12 -08005615sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5616 return mTrack->getCblk();
5617}
5618
Glenn Kasten3acbd052012-02-28 10:39:56 -08005619status_t AudioFlinger::TrackHandle::start() {
5620 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005621}
5622
5623void AudioFlinger::TrackHandle::stop() {
5624 mTrack->stop();
5625}
5626
5627void AudioFlinger::TrackHandle::flush() {
5628 mTrack->flush();
5629}
5630
5631void AudioFlinger::TrackHandle::mute(bool e) {
5632 mTrack->mute(e);
5633}
5634
5635void AudioFlinger::TrackHandle::pause() {
5636 mTrack->pause();
5637}
5638
Mathias Agopian65ab4712010-07-14 17:59:35 -07005639status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5640{
5641 return mTrack->attachAuxEffect(EffectId);
5642}
5643
John Grossman4ff14ba2012-02-08 16:37:41 -08005644status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5645 sp<IMemory>* buffer) {
5646 if (!mTrack->isTimedTrack())
5647 return INVALID_OPERATION;
5648
5649 PlaybackThread::TimedTrack* tt =
5650 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5651 return tt->allocateTimedBuffer(size, buffer);
5652}
5653
5654status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5655 int64_t pts) {
5656 if (!mTrack->isTimedTrack())
5657 return INVALID_OPERATION;
5658
5659 PlaybackThread::TimedTrack* tt =
5660 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5661 return tt->queueTimedBuffer(buffer, pts);
5662}
5663
5664status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5665 const LinearTransform& xform, int target) {
5666
5667 if (!mTrack->isTimedTrack())
5668 return INVALID_OPERATION;
5669
5670 PlaybackThread::TimedTrack* tt =
5671 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5672 return tt->setMediaTimeTransform(
5673 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5674}
5675
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676status_t AudioFlinger::TrackHandle::onTransact(
5677 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5678{
5679 return BnAudioTrack::onTransact(code, data, reply, flags);
5680}
5681
5682// ----------------------------------------------------------------------------
5683
5684sp<IAudioRecord> AudioFlinger::openRecord(
5685 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005686 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005688 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005689 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005691 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692 int *sessionId,
5693 status_t *status)
5694{
5695 sp<RecordThread::RecordTrack> recordTrack;
5696 sp<RecordHandle> recordHandle;
5697 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 status_t lStatus;
5699 RecordThread *thread;
5700 size_t inFrameCount;
5701 int lSessionId;
5702
5703 // check calling permissions
5704 if (!recordingAllowed()) {
5705 lStatus = PERMISSION_DENIED;
5706 goto Exit;
5707 }
5708
5709 // add client to list
5710 { // scope for mLock
5711 Mutex::Autolock _l(mLock);
5712 thread = checkRecordThread_l(input);
5713 if (thread == NULL) {
5714 lStatus = BAD_VALUE;
5715 goto Exit;
5716 }
5717
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005718 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719
5720 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005721 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722 lSessionId = *sessionId;
5723 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005724 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725 if (sessionId != NULL) {
5726 *sessionId = lSessionId;
5727 }
5728 }
5729 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005730 recordTrack = thread->createRecordTrack_l(client,
5731 sampleRate,
5732 format,
5733 channelMask,
5734 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005735 lSessionId,
5736 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005738 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5740 // destructor is called by the TrackBase destructor with mLock held
5741 client.clear();
5742 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 goto Exit;
5744 }
5745
5746 // return to handle to client
5747 recordHandle = new RecordHandle(recordTrack);
5748 lStatus = NO_ERROR;
5749
5750Exit:
5751 if (status) {
5752 *status = lStatus;
5753 }
5754 return recordHandle;
5755}
5756
5757// ----------------------------------------------------------------------------
5758
5759AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5760 : BnAudioRecord(),
5761 mRecordTrack(recordTrack)
5762{
5763}
5764
5765AudioFlinger::RecordHandle::~RecordHandle() {
5766 stop();
5767}
5768
Glenn Kasten90716c52012-01-26 13:40:12 -08005769sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5770 return mRecordTrack->getCblk();
5771}
5772
Glenn Kasten3acbd052012-02-28 10:39:56 -08005773status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005774 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005775 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776}
5777
5778void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005779 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780 mRecordTrack->stop();
5781}
5782
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783status_t AudioFlinger::RecordHandle::onTransact(
5784 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5785{
5786 return BnAudioRecord::onTransact(code, data, reply, flags);
5787}
5788
5789// ----------------------------------------------------------------------------
5790
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005791AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5792 AudioStreamIn *input,
5793 uint32_t sampleRate,
5794 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005795 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005796 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005797 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005798 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5799 // mRsmpInIndex and mInputBytes set by readInputParameters()
5800 mReqChannelCount(popcount(channels)),
5801 mReqSampleRate(sampleRate)
5802 // mBytesRead is only meaningful while active, and so is cleared in start()
5803 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005804{
Glenn Kasten480b4682012-02-28 12:30:08 -08005805 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005806
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 readInputParameters();
5808}
5809
5810
5811AudioFlinger::RecordThread::~RecordThread()
5812{
5813 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005814 delete mResampler;
5815 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816}
5817
5818void AudioFlinger::RecordThread::onFirstRef()
5819{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005820 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821}
5822
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005823status_t AudioFlinger::RecordThread::readyToRun()
5824{
5825 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005826 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005827 return status;
5828}
5829
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830bool AudioFlinger::RecordThread::threadLoop()
5831{
5832 AudioBufferProvider::Buffer buffer;
5833 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005834 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835
Eric Laurent44d98482010-09-30 16:12:31 -07005836 nsecs_t lastWarning = 0;
5837
Eric Laurentfeb0db62011-07-22 09:04:31 -07005838 acquireWakeLock();
5839
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 // start recording
5841 while (!exitPending()) {
5842
5843 processConfigEvents();
5844
5845 { // scope for mLock
5846 Mutex::Autolock _l(mLock);
5847 checkForNewParameters_l();
5848 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5849 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005850 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 mStandby = true;
5852 }
5853
5854 if (exitPending()) break;
5855
Eric Laurentfeb0db62011-07-22 09:04:31 -07005856 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005857 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858 // go to sleep
5859 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005860 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005861 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 continue;
5863 }
5864 if (mActiveTrack != 0) {
5865 if (mActiveTrack->mState == TrackBase::PAUSING) {
5866 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005867 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 mStandby = true;
5869 }
5870 mActiveTrack.clear();
5871 mStartStopCond.broadcast();
5872 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5873 if (mReqChannelCount != mActiveTrack->channelCount()) {
5874 mActiveTrack.clear();
5875 mStartStopCond.broadcast();
5876 } else if (mBytesRead != 0) {
5877 // record start succeeds only if first read from audio input
5878 // succeeds
5879 if (mBytesRead > 0) {
5880 mActiveTrack->mState = TrackBase::ACTIVE;
5881 } else {
5882 mActiveTrack.clear();
5883 }
5884 mStartStopCond.broadcast();
5885 }
5886 mStandby = false;
5887 }
5888 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005889 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 }
5891
5892 if (mActiveTrack != 0) {
5893 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5894 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005895 unlockEffectChains(effectChains);
5896 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 continue;
5898 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005899 for (size_t i = 0; i < effectChains.size(); i ++) {
5900 effectChains[i]->process_l();
5901 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005902
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005904 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005905 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005906 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 // no resampling
5908 while (framesOut) {
5909 size_t framesIn = mFrameCount - mRsmpInIndex;
5910 if (framesIn) {
5911 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5912 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5913 if (framesIn > framesOut)
5914 framesIn = framesOut;
5915 mRsmpInIndex += framesIn;
5916 framesOut -= framesIn;
5917 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005918 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919 memcpy(dst, src, framesIn * mFrameSize);
5920 } else {
5921 int16_t *src16 = (int16_t *)src;
5922 int16_t *dst16 = (int16_t *)dst;
5923 if (mChannelCount == 1) {
5924 while (framesIn--) {
5925 *dst16++ = *src16;
5926 *dst16++ = *src16++;
5927 }
5928 } else {
5929 while (framesIn--) {
5930 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5931 src16 += 2;
5932 }
5933 }
5934 }
5935 }
5936 if (framesOut && mFrameCount == mRsmpInIndex) {
5937 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005938 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005939 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 framesOut = 0;
5941 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005942 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 mRsmpInIndex = 0;
5944 }
5945 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005946 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5948 // Force input into standby so that it tries to
5949 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005950 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005951 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 }
5953 mRsmpInIndex = mFrameCount;
5954 framesOut = 0;
5955 buffer.frameCount = 0;
5956 }
5957 }
5958 }
5959 } else {
5960 // resampling
5961
5962 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5963 // alter output frame count as if we were expecting stereo samples
5964 if (mChannelCount == 1 && mReqChannelCount == 1) {
5965 framesOut >>= 1;
5966 }
5967 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5968 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5969 // are 32 bit aligned which should be always true.
5970 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005971 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972 // the resampler always outputs stereo samples: do post stereo to mono conversion
5973 int16_t *src = (int16_t *)mRsmpOutBuffer;
5974 int16_t *dst = buffer.i16;
5975 while (framesOut--) {
5976 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5977 src += 2;
5978 }
5979 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005980 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 }
5982
5983 }
Eric Laurenta011e352012-03-29 15:51:43 -07005984 if (mFramestoDrop == 0) {
5985 mActiveTrack->releaseBuffer(&buffer);
5986 } else {
5987 if (mFramestoDrop > 0) {
5988 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07005989 if (mFramestoDrop <= 0) {
5990 clearSyncStartEvent();
5991 }
5992 } else {
5993 mFramestoDrop += buffer.frameCount;
5994 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
5995 mSyncStartEvent->isCancelled()) {
5996 ALOGW("Synced record %s, session %d, trigger session %d",
5997 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
5998 mActiveTrack->sessionId(),
5999 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6000 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006001 }
6002 }
6003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 mActiveTrack->overflow();
6005 }
6006 // client isn't retrieving buffers fast enough
6007 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006008 if (!mActiveTrack->setOverflow()) {
6009 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006010 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006011 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006012 lastWarning = now;
6013 }
6014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 // Release the processor for a while before asking for a new buffer.
6016 // This will give the application more chance to read from the buffer and
6017 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006018 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019 }
6020 }
Eric Laurentec437d82011-07-26 20:54:46 -07006021 // enable changes in effect chain
6022 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006023 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024 }
6025
6026 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006027 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028 }
6029 mActiveTrack.clear();
6030
6031 mStartStopCond.broadcast();
6032
Eric Laurentfeb0db62011-07-22 09:04:31 -07006033 releaseWakeLock();
6034
Steve Block3856b092011-10-20 11:56:00 +01006035 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 return false;
6037}
6038
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006039
6040sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6041 const sp<AudioFlinger::Client>& client,
6042 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006043 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006044 int channelMask,
6045 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006046 int sessionId,
6047 status_t *status)
6048{
6049 sp<RecordTrack> track;
6050 status_t lStatus;
6051
6052 lStatus = initCheck();
6053 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006054 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006055 goto Exit;
6056 }
6057
6058 { // scope for mLock
6059 Mutex::Autolock _l(mLock);
6060
6061 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006062 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006063
Glenn Kasten7378ca52012-01-20 13:44:40 -08006064 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006065 lStatus = NO_MEMORY;
6066 goto Exit;
6067 }
6068
6069 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006070 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6071 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006072 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006073 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6074 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006075 }
6076 lStatus = NO_ERROR;
6077
6078Exit:
6079 if (status) {
6080 *status = lStatus;
6081 }
6082 return track;
6083}
6084
Eric Laurenta011e352012-03-29 15:51:43 -07006085status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006086 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006087 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088{
Glenn Kasten58912562012-04-03 10:45:00 -07006089 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006090 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006092
6093 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006094 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006095 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6096 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6097 triggerSession,
6098 recordTrack->sessionId(),
6099 syncStartEventCallback,
6100 this);
Eric Laurent29864602012-05-08 18:57:51 -07006101 // Sync event can be cancelled by the trigger session if the track is not in a
6102 // compatible state in which case we start record immediately
6103 if (mSyncStartEvent->isCancelled()) {
6104 clearSyncStartEvent();
6105 } else {
6106 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6107 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6108 }
Eric Laurenta011e352012-03-29 15:51:43 -07006109 }
6110
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006112 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 if (mActiveTrack != 0) {
6114 if (recordTrack != mActiveTrack.get()) {
6115 status = -EBUSY;
6116 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6117 mActiveTrack->mState = TrackBase::ACTIVE;
6118 }
6119 return status;
6120 }
6121
6122 recordTrack->mState = TrackBase::IDLE;
6123 mActiveTrack = recordTrack;
6124 mLock.unlock();
6125 status_t status = AudioSystem::startInput(mId);
6126 mLock.lock();
6127 if (status != NO_ERROR) {
6128 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006129 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 return status;
6131 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 mRsmpInIndex = mFrameCount;
6133 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006134 if (mResampler != NULL) {
6135 mResampler->reset();
6136 }
6137 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006139 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 mWaitWorkCV.signal();
6141 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006142 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 mActiveTrack.clear();
6144 status = INVALID_OPERATION;
6145 goto startError;
6146 }
6147 mStartStopCond.wait(mLock);
6148 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006149 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 status = BAD_VALUE;
6151 goto startError;
6152 }
Steve Block3856b092011-10-20 11:56:00 +01006153 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 return status;
6155 }
6156startError:
6157 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006158 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159 return status;
6160}
6161
Eric Laurenta011e352012-03-29 15:51:43 -07006162void AudioFlinger::RecordThread::clearSyncStartEvent()
6163{
6164 if (mSyncStartEvent != 0) {
6165 mSyncStartEvent->cancel();
6166 }
6167 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006168 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006169}
6170
6171void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6172{
6173 sp<SyncEvent> strongEvent = event.promote();
6174
6175 if (strongEvent != 0) {
6176 RecordThread *me = (RecordThread *)strongEvent->cookie();
6177 me->handleSyncStartEvent(strongEvent);
6178 }
6179}
6180
6181void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6182{
Eric Laurent29864602012-05-08 18:57:51 -07006183 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006184 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6185 // from audio HAL
6186 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006187 }
6188}
6189
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006191 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006192 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006194 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6196 mActiveTrack->mState = TrackBase::PAUSING;
6197 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006198 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 return;
6200 }
6201 mStartStopCond.wait(mLock);
6202 // if we have been restarted, recordTrack == mActiveTrack.get() here
6203 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6204 mLock.unlock();
6205 AudioSystem::stopInput(mId);
6206 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006207 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 }
6209 }
6210 }
6211}
6212
Eric Laurenta011e352012-03-29 15:51:43 -07006213bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6214{
6215 return false;
6216}
6217
6218status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6219{
6220 if (!isValidSyncEvent(event)) {
6221 return BAD_VALUE;
6222 }
6223
6224 Mutex::Autolock _l(mLock);
6225
6226 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6227 mTrack->setSyncEvent(event);
6228 return NO_ERROR;
6229 }
6230 return NAME_NOT_FOUND;
6231}
6232
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6234{
6235 const size_t SIZE = 256;
6236 char buffer[SIZE];
6237 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238
6239 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6240 result.append(buffer);
6241
6242 if (mActiveTrack != 0) {
6243 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006244 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 mActiveTrack->dump(buffer, SIZE);
6246 result.append(buffer);
6247
6248 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6249 result.append(buffer);
6250 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6251 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006252 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 result.append(buffer);
6254 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6255 result.append(buffer);
6256 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6257 result.append(buffer);
6258
6259
6260 } else {
6261 result.append("No record client\n");
6262 }
6263 write(fd, result.string(), result.size());
6264
6265 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006266 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267
6268 return NO_ERROR;
6269}
6270
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006271// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006272status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273{
6274 size_t framesReq = buffer->frameCount;
6275 size_t framesReady = mFrameCount - mRsmpInIndex;
6276 int channelCount;
6277
6278 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006279 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006281 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6283 // Force input into standby so that it tries to
6284 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006285 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006286 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006288 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 buffer->frameCount = 0;
6290 return NOT_ENOUGH_DATA;
6291 }
6292 mRsmpInIndex = 0;
6293 framesReady = mFrameCount;
6294 }
6295
6296 if (framesReq > framesReady) {
6297 framesReq = framesReady;
6298 }
6299
6300 if (mChannelCount == 1 && mReqChannelCount == 2) {
6301 channelCount = 1;
6302 } else {
6303 channelCount = 2;
6304 }
6305 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6306 buffer->frameCount = framesReq;
6307 return NO_ERROR;
6308}
6309
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006310// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6312{
6313 mRsmpInIndex += buffer->frameCount;
6314 buffer->frameCount = 0;
6315}
6316
6317bool AudioFlinger::RecordThread::checkForNewParameters_l()
6318{
6319 bool reconfig = false;
6320
6321 while (!mNewParameters.isEmpty()) {
6322 status_t status = NO_ERROR;
6323 String8 keyValuePair = mNewParameters[0];
6324 AudioParameter param = AudioParameter(keyValuePair);
6325 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006326 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 int reqSamplingRate = mReqSampleRate;
6328 int reqChannelCount = mReqChannelCount;
6329
6330 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6331 reqSamplingRate = value;
6332 reconfig = true;
6333 }
6334 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006335 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006336 reconfig = true;
6337 }
6338 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006339 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 reconfig = true;
6341 }
6342 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6343 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006344 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 // if frame count is changed after track creation
6346 if (mActiveTrack != 0) {
6347 status = INVALID_OPERATION;
6348 } else {
6349 reconfig = true;
6350 }
6351 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006352 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6353 // forward device change to effects that have requested to be
6354 // aware of attached audio device.
6355 for (size_t i = 0; i < mEffectChains.size(); i++) {
6356 mEffectChains[i]->setDevice_l(value);
6357 }
6358 // store input device and output device but do not forward output device to audio HAL.
6359 // Note that status is ignored by the caller for output device
6360 // (see AudioFlinger::setParameters()
6361 if (value & AUDIO_DEVICE_OUT_ALL) {
6362 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6363 status = BAD_VALUE;
6364 } else {
6365 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006366 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6367 if (mTrack != NULL) {
6368 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006369 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006370 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6371 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6372 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006373 }
6374 mDevice |= (uint32_t)value;
6375 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006377 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006379 mInput->stream->common.standby(&mInput->stream->common);
6380 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6381 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382 }
6383 if (reconfig) {
6384 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006385 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006386 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006387 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006388 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6389 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390 status = NO_ERROR;
6391 }
6392 if (status == NO_ERROR) {
6393 readInputParameters();
6394 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6395 }
6396 }
6397 }
6398
6399 mNewParameters.removeAt(0);
6400
6401 mParamStatus = status;
6402 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006403 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6404 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006405 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 }
6407 return reconfig;
6408}
6409
6410String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6411{
Dima Zavinfce7a472011-04-19 22:30:36 -07006412 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006413 String8 out_s8 = String8();
6414
6415 Mutex::Autolock _l(mLock);
6416 if (initCheck() != NO_ERROR) {
6417 return out_s8;
6418 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006419
Dima Zavin799a70e2011-04-18 16:57:27 -07006420 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006421 out_s8 = String8(s);
6422 free(s);
6423 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424}
6425
6426void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6427 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006428 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429
6430 switch (event) {
6431 case AudioSystem::INPUT_OPENED:
6432 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006433 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006434 desc.samplingRate = mSampleRate;
6435 desc.format = mFormat;
6436 desc.frameCount = mFrameCount;
6437 desc.latency = 0;
6438 param2 = &desc;
6439 break;
6440
6441 case AudioSystem::INPUT_CLOSED:
6442 default:
6443 break;
6444 }
6445 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6446}
6447
6448void AudioFlinger::RecordThread::readInputParameters()
6449{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006450 delete mRsmpInBuffer;
6451 // mRsmpInBuffer is always assigned a new[] below
6452 delete mRsmpOutBuffer;
6453 mRsmpOutBuffer = NULL;
6454 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006455 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456
Dima Zavin799a70e2011-04-18 16:57:27 -07006457 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006458 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6459 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006460 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006461 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006462 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006464 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006465 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6466
Glenn Kasten53d76db2012-03-08 12:32:47 -08006467 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 {
6469 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006470 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6471 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 if (mChannelCount == 1 && mReqChannelCount == 2) {
6473 channelCount = 1;
6474 } else {
6475 channelCount = 2;
6476 }
6477 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6478 mResampler->setSampleRate(mSampleRate);
6479 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6480 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6481
6482 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6483 if (mChannelCount == 1 && mReqChannelCount == 1) {
6484 mFrameCount >>= 1;
6485 }
6486
6487 }
6488 mRsmpInIndex = mFrameCount;
6489}
6490
6491unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6492{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006493 Mutex::Autolock _l(mLock);
6494 if (initCheck() != NO_ERROR) {
6495 return 0;
6496 }
6497
Dima Zavin799a70e2011-04-18 16:57:27 -07006498 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499}
6500
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006501uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6502{
6503 Mutex::Autolock _l(mLock);
6504 uint32_t result = 0;
6505 if (getEffectChain_l(sessionId) != 0) {
6506 result = EFFECT_SESSION;
6507 }
6508
6509 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6510 result |= TRACK_SESSION;
6511 }
6512
6513 return result;
6514}
6515
Eric Laurent59bd0da2011-08-01 09:52:20 -07006516AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6517{
6518 Mutex::Autolock _l(mLock);
6519 return mTrack;
6520}
6521
Glenn Kastenaed850d2012-01-26 09:46:34 -08006522AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006523{
6524 Mutex::Autolock _l(mLock);
6525 return mInput;
6526}
6527
6528AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6529{
6530 Mutex::Autolock _l(mLock);
6531 AudioStreamIn *input = mInput;
6532 mInput = NULL;
6533 return input;
6534}
6535
6536// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006537audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006538{
6539 if (mInput == NULL) {
6540 return NULL;
6541 }
6542 return &mInput->stream->common;
6543}
6544
6545
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546// ----------------------------------------------------------------------------
6547
Eric Laurenta4c5a552012-03-29 10:12:40 -07006548audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6549{
6550 if (!settingsAllowed()) {
6551 return 0;
6552 }
6553 Mutex::Autolock _l(mLock);
6554 return loadHwModule_l(name);
6555}
6556
6557// loadHwModule_l() must be called with AudioFlinger::mLock held
6558audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6559{
6560 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6561 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6562 ALOGW("loadHwModule() module %s already loaded", name);
6563 return mAudioHwDevs.keyAt(i);
6564 }
6565 }
6566
Eric Laurenta4c5a552012-03-29 10:12:40 -07006567 audio_hw_device_t *dev;
6568
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006569 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006570 if (rc) {
6571 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6572 return 0;
6573 }
6574
6575 mHardwareStatus = AUDIO_HW_INIT;
6576 rc = dev->init_check(dev);
6577 mHardwareStatus = AUDIO_HW_IDLE;
6578 if (rc) {
6579 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6580 return 0;
6581 }
6582
6583 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6584 (NULL != dev->set_master_volume)) {
6585 AutoMutex lock(mHardwareLock);
6586 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6587 dev->set_master_volume(dev, mMasterVolume);
6588 mHardwareStatus = AUDIO_HW_IDLE;
6589 }
6590
6591 audio_module_handle_t handle = nextUniqueId();
6592 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6593
6594 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006595 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006596
6597 return handle;
6598
6599}
6600
6601audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6602 audio_devices_t *pDevices,
6603 uint32_t *pSamplingRate,
6604 audio_format_t *pFormat,
6605 audio_channel_mask_t *pChannelMask,
6606 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006607 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608{
6609 status_t status;
6610 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006611 struct audio_config config = {
6612 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6613 channel_mask: pChannelMask ? *pChannelMask : 0,
6614 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6615 };
6616 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006617 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618
Eric Laurenta4c5a552012-03-29 10:12:40 -07006619 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6620 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006621 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006622 config.sample_rate,
6623 config.format,
6624 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006625 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626
6627 if (pDevices == NULL || *pDevices == 0) {
6628 return 0;
6629 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006630
Mathias Agopian65ab4712010-07-14 17:59:35 -07006631 Mutex::Autolock _l(mLock);
6632
Eric Laurenta4c5a552012-03-29 10:12:40 -07006633 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006634 if (outHwDev == NULL)
6635 return 0;
6636
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006637 audio_io_handle_t id = nextUniqueId();
6638
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006639 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006640
6641 status = outHwDev->open_output_stream(outHwDev,
6642 id,
6643 *pDevices,
6644 (audio_output_flags_t)flags,
6645 &config,
6646 &outStream);
6647
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006648 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006649 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006650 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006651 config.sample_rate,
6652 config.format,
6653 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654 status);
6655
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006656 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006657 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006658
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006659 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006660 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6661 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006662 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006663 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664 } else {
6665 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006666 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 }
6668 mPlaybackThreads.add(id, thread);
6669
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006670 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6671 if (pFormat != NULL) *pFormat = config.format;
6672 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006673 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006674
6675 // notify client processes of the new output creation
6676 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006677
6678 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006679 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006680 ALOGI("Using module %d has the primary audio interface", module);
6681 mPrimaryHardwareDev = outHwDev;
6682
6683 AutoMutex lock(mHardwareLock);
6684 mHardwareStatus = AUDIO_HW_SET_MODE;
6685 outHwDev->set_mode(outHwDev, mMode);
6686
6687 // Determine the level of master volume support the primary audio HAL has,
6688 // and set the initial master volume at the same time.
6689 float initialVolume = 1.0;
6690 mMasterVolumeSupportLvl = MVS_NONE;
6691
6692 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6693 if ((NULL != outHwDev->get_master_volume) &&
6694 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6695 mMasterVolumeSupportLvl = MVS_FULL;
6696 } else {
6697 mMasterVolumeSupportLvl = MVS_SETONLY;
6698 initialVolume = 1.0;
6699 }
6700
6701 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6702 if ((NULL == outHwDev->set_master_volume) ||
6703 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6704 mMasterVolumeSupportLvl = MVS_NONE;
6705 }
6706 // now that we have a primary device, initialize master volume on other devices
6707 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6708 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6709
6710 if ((dev != mPrimaryHardwareDev) &&
6711 (NULL != dev->set_master_volume)) {
6712 dev->set_master_volume(dev, initialVolume);
6713 }
6714 }
6715 mHardwareStatus = AUDIO_HW_IDLE;
6716 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6717 ? initialVolume
6718 : 1.0;
6719 mMasterVolume = initialVolume;
6720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721 return id;
6722 }
6723
6724 return 0;
6725}
6726
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006727audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6728 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729{
6730 Mutex::Autolock _l(mLock);
6731 MixerThread *thread1 = checkMixerThread_l(output1);
6732 MixerThread *thread2 = checkMixerThread_l(output2);
6733
6734 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006735 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 return 0;
6737 }
6738
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006739 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6741 thread->addOutputTrack(thread2);
6742 mPlaybackThreads.add(id, thread);
6743 // notify client processes of the new output creation
6744 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6745 return id;
6746}
6747
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006748status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749{
6750 // keep strong reference on the playback thread so that
6751 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006752 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006753 {
6754 Mutex::Autolock _l(mLock);
6755 thread = checkPlaybackThread_l(output);
6756 if (thread == NULL) {
6757 return BAD_VALUE;
6758 }
6759
Steve Block3856b092011-10-20 11:56:00 +01006760 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006762 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006764 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6766 dupThread->removeOutputTrack((MixerThread *)thread.get());
6767 }
6768 }
6769 }
Glenn Kastena1117922012-01-26 10:53:32 -08006770 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771 mPlaybackThreads.removeItem(output);
6772 }
6773 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006774 // The thread entity (active unit of execution) is no longer running here,
6775 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006776
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006777 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006778 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006779 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006780 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006781 out->hwDev->close_output_stream(out->hwDev, out->stream);
6782 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006783 }
6784 return NO_ERROR;
6785}
6786
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006787status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788{
6789 Mutex::Autolock _l(mLock);
6790 PlaybackThread *thread = checkPlaybackThread_l(output);
6791
6792 if (thread == NULL) {
6793 return BAD_VALUE;
6794 }
6795
Steve Block3856b092011-10-20 11:56:00 +01006796 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 thread->suspend();
6798
6799 return NO_ERROR;
6800}
6801
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006802status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803{
6804 Mutex::Autolock _l(mLock);
6805 PlaybackThread *thread = checkPlaybackThread_l(output);
6806
6807 if (thread == NULL) {
6808 return BAD_VALUE;
6809 }
6810
Steve Block3856b092011-10-20 11:56:00 +01006811 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812
6813 thread->restore();
6814
6815 return NO_ERROR;
6816}
6817
Eric Laurenta4c5a552012-03-29 10:12:40 -07006818audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6819 audio_devices_t *pDevices,
6820 uint32_t *pSamplingRate,
6821 audio_format_t *pFormat,
6822 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823{
6824 status_t status;
6825 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006826 struct audio_config config = {
6827 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6828 channel_mask: pChannelMask ? *pChannelMask : 0,
6829 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6830 };
6831 uint32_t reqSamplingRate = config.sample_rate;
6832 audio_format_t reqFormat = config.format;
6833 audio_channel_mask_t reqChannels = config.channel_mask;
6834 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006835 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836
6837 if (pDevices == NULL || *pDevices == 0) {
6838 return 0;
6839 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006840
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 Mutex::Autolock _l(mLock);
6842
Eric Laurenta4c5a552012-03-29 10:12:40 -07006843 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006844 if (inHwDev == NULL)
6845 return 0;
6846
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006847 audio_io_handle_t id = nextUniqueId();
6848
6849 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006850 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006851 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006852 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006853 config.sample_rate,
6854 config.format,
6855 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856 status);
6857
6858 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6859 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6860 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006861 if (status == BAD_VALUE &&
6862 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6863 (config.sample_rate <= 2 * reqSamplingRate) &&
6864 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006865 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006866 inStream = NULL;
6867 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868 }
6869
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006870 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006871 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6872
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006873 // Start record thread
6874 // RecorThread require both input and output device indication to forward to audio
6875 // pre processing modules
6876 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6877 thread = new RecordThread(this,
6878 input,
6879 reqSamplingRate,
6880 reqChannels,
6881 id,
6882 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006884 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006885 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006886 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006887 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888
Dima Zavin799a70e2011-04-18 16:57:27 -07006889 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890
6891 // notify client processes of the new input creation
6892 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6893 return id;
6894 }
6895
6896 return 0;
6897}
6898
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006899status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900{
6901 // keep strong reference on the record thread so that
6902 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006903 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 {
6905 Mutex::Autolock _l(mLock);
6906 thread = checkRecordThread_l(input);
6907 if (thread == NULL) {
6908 return BAD_VALUE;
6909 }
6910
Steve Block3856b092011-10-20 11:56:00 +01006911 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006912 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 mRecordThreads.removeItem(input);
6914 }
6915 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006916 // The thread entity (active unit of execution) is no longer running here,
6917 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006919 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006920 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006921 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006922 in->hwDev->close_input_stream(in->hwDev, in->stream);
6923 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924
6925 return NO_ERROR;
6926}
6927
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006928status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006929{
6930 Mutex::Autolock _l(mLock);
6931 MixerThread *dstThread = checkMixerThread_l(output);
6932 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006933 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 return BAD_VALUE;
6935 }
6936
Steve Block3856b092011-10-20 11:56:00 +01006937 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6939
6940 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6941 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006942 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943 MixerThread *srcThread = (MixerThread *)thread;
6944 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945 }
Eric Laurentde070132010-07-13 04:45:46 -07006946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947
6948 return NO_ERROR;
6949}
6950
6951
6952int AudioFlinger::newAudioSessionId()
6953{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006954 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006955}
6956
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006957void AudioFlinger::acquireAudioSessionId(int audioSession)
6958{
6959 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006960 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006961 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006962 size_t num = mAudioSessionRefs.size();
6963 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006964 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006965 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6966 ref->mCnt++;
6967 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006968 return;
6969 }
6970 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006971 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6972 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006973}
6974
6975void AudioFlinger::releaseAudioSessionId(int audioSession)
6976{
6977 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006978 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006979 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006980 size_t num = mAudioSessionRefs.size();
6981 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006982 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006983 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6984 ref->mCnt--;
6985 ALOGV(" decremented refcount to %d", ref->mCnt);
6986 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006987 mAudioSessionRefs.removeAt(i);
6988 delete ref;
6989 purgeStaleEffects_l();
6990 }
6991 return;
6992 }
6993 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006994 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006995}
6996
6997void AudioFlinger::purgeStaleEffects_l() {
6998
Steve Block3856b092011-10-20 11:56:00 +01006999 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007000
7001 Vector< sp<EffectChain> > chains;
7002
7003 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7004 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7005 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7006 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007007 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7008 chains.push(ec);
7009 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007010 }
7011 }
7012 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7013 sp<RecordThread> t = mRecordThreads.valueAt(i);
7014 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7015 sp<EffectChain> ec = t->mEffectChains[j];
7016 chains.push(ec);
7017 }
7018 }
7019
7020 for (size_t i = 0; i < chains.size(); i++) {
7021 sp<EffectChain> ec = chains[i];
7022 int sessionid = ec->sessionId();
7023 sp<ThreadBase> t = ec->mThread.promote();
7024 if (t == 0) {
7025 continue;
7026 }
7027 size_t numsessionrefs = mAudioSessionRefs.size();
7028 bool found = false;
7029 for (size_t k = 0; k < numsessionrefs; k++) {
7030 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007031 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007032 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007033 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007034 found = true;
7035 break;
7036 }
7037 }
7038 if (!found) {
7039 // remove all effects from the chain
7040 while (ec->mEffects.size()) {
7041 sp<EffectModule> effect = ec->mEffects[0];
7042 effect->unPin();
7043 Mutex::Autolock _l (t->mLock);
7044 t->removeEffect_l(effect);
7045 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7046 sp<EffectHandle> handle = effect->mHandles[j].promote();
7047 if (handle != 0) {
7048 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007049 if (handle->mHasControl && handle->mEnabled) {
7050 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7051 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007052 }
7053 }
7054 AudioSystem::unregisterEffect(effect->id());
7055 }
7056 }
7057 }
7058 return;
7059}
7060
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007062AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063{
Glenn Kastena1117922012-01-26 10:53:32 -08007064 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065}
7066
7067// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007068AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069{
7070 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007071 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072}
7073
7074// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007075AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076{
Glenn Kastena1117922012-01-26 10:53:32 -08007077 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078}
7079
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007080uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007082 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007083}
7084
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007085AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007086{
7087 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7088 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007089 AudioStreamOut *output = thread->getOutput();
7090 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007091 return thread;
7092 }
7093 }
7094 return NULL;
7095}
7096
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007097uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007098{
7099 PlaybackThread *thread = primaryPlaybackThread_l();
7100
7101 if (thread == NULL) {
7102 return 0;
7103 }
7104
7105 return thread->device();
7106}
7107
Eric Laurenta011e352012-03-29 15:51:43 -07007108sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7109 int triggerSession,
7110 int listenerSession,
7111 sync_event_callback_t callBack,
7112 void *cookie)
7113{
7114 Mutex::Autolock _l(mLock);
7115
7116 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7117 status_t playStatus = NAME_NOT_FOUND;
7118 status_t recStatus = NAME_NOT_FOUND;
7119 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7120 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7121 if (playStatus == NO_ERROR) {
7122 return event;
7123 }
7124 }
7125 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7126 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7127 if (recStatus == NO_ERROR) {
7128 return event;
7129 }
7130 }
7131 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7132 mPendingSyncEvents.add(event);
7133 } else {
7134 ALOGV("createSyncEvent() invalid event %d", event->type());
7135 event.clear();
7136 }
7137 return event;
7138}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007139
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140// ----------------------------------------------------------------------------
7141// Effect management
7142// ----------------------------------------------------------------------------
7143
7144
Glenn Kastenf587ba52012-01-26 16:25:10 -08007145status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007146{
7147 Mutex::Autolock _l(mLock);
7148 return EffectQueryNumberEffects(numEffects);
7149}
7150
Glenn Kastenf587ba52012-01-26 16:25:10 -08007151status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152{
7153 Mutex::Autolock _l(mLock);
7154 return EffectQueryEffect(index, descriptor);
7155}
7156
Glenn Kasten5e92a782012-01-30 07:40:52 -08007157status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007158 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159{
7160 Mutex::Autolock _l(mLock);
7161 return EffectGetDescriptor(pUuid, descriptor);
7162}
7163
7164
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7166 effect_descriptor_t *pDesc,
7167 const sp<IEffectClient>& effectClient,
7168 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007169 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170 int sessionId,
7171 status_t *status,
7172 int *id,
7173 int *enabled)
7174{
7175 status_t lStatus = NO_ERROR;
7176 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007179 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181
7182 if (pDesc == NULL) {
7183 lStatus = BAD_VALUE;
7184 goto Exit;
7185 }
7186
Eric Laurent84e9a102010-09-23 16:10:16 -07007187 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007188 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007189 lStatus = PERMISSION_DENIED;
7190 goto Exit;
7191 }
7192
Dima Zavinfce7a472011-04-19 22:30:36 -07007193 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007194 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007195 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007196 lStatus = PERMISSION_DENIED;
7197 goto Exit;
7198 }
7199
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007200 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007201 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007202 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007203 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007204 lStatus = BAD_VALUE;
7205 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007206 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007207 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007208 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007209 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007210 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007211 }
7212 }
7213
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214 {
7215 Mutex::Autolock _l(mLock);
7216
Mathias Agopian65ab4712010-07-14 17:59:35 -07007217
7218 if (!EffectIsNullUuid(&pDesc->uuid)) {
7219 // if uuid is specified, request effect descriptor
7220 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7221 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007222 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007223 goto Exit;
7224 }
7225 } else {
7226 // if uuid is not specified, look for an available implementation
7227 // of the required type in effect factory
7228 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007229 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007230 lStatus = BAD_VALUE;
7231 goto Exit;
7232 }
7233 uint32_t numEffects = 0;
7234 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007235 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236 bool found = false;
7237
7238 lStatus = EffectQueryNumberEffects(&numEffects);
7239 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007240 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241 goto Exit;
7242 }
7243 for (uint32_t i = 0; i < numEffects; i++) {
7244 lStatus = EffectQueryEffect(i, &desc);
7245 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007246 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007247 continue;
7248 }
7249 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7250 // If matching type found save effect descriptor. If the session is
7251 // 0 and the effect is not auxiliary, continue enumeration in case
7252 // an auxiliary version of this effect type is available
7253 found = true;
7254 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007255 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7257 break;
7258 }
7259 }
7260 }
7261 if (!found) {
7262 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007263 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264 goto Exit;
7265 }
7266 // For same effect type, chose auxiliary version over insert version if
7267 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007268 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007269 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7270 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7271 }
7272 }
7273
7274 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007275 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007276 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7277 lStatus = INVALID_OPERATION;
7278 goto Exit;
7279 }
7280
Eric Laurent59255e42011-07-27 19:49:51 -07007281 // check recording permission for visualizer
7282 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7283 !recordingAllowed()) {
7284 lStatus = PERMISSION_DENIED;
7285 goto Exit;
7286 }
7287
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 // return effect descriptor
7289 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7290
7291 // If output is not specified try to find a matching audio session ID in one of the
7292 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007293 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7294 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007295 // Note: io is never 0 when creating an effect on an input
7296 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007297 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007298 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7299 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007300 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007301 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007302 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007303 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007305 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7306 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7307 io = mRecordThreads.keyAt(i);
7308 break;
7309 }
7310 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007311 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007312 // If no output thread contains the requested session ID, default to
7313 // first output. The effect chain will be moved to the correct output
7314 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007315 if (io == 0 && mPlaybackThreads.size()) {
7316 io = mPlaybackThreads.keyAt(0);
7317 }
Steve Block3856b092011-10-20 11:56:00 +01007318 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007319 }
7320 ThreadBase *thread = checkRecordThread_l(io);
7321 if (thread == NULL) {
7322 thread = checkPlaybackThread_l(io);
7323 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007324 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007325 lStatus = BAD_VALUE;
7326 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007329
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007330 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007332 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007333 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7334 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335 if (handle != 0 && id != NULL) {
7336 *id = handle->id();
7337 }
7338 }
7339
7340Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007341 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342 *status = lStatus;
7343 }
7344 return handle;
7345}
7346
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007347status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7348 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007349{
Steve Block3856b092011-10-20 11:56:00 +01007350 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007351 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007352 Mutex::Autolock _l(mLock);
7353 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007354 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007355 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356 }
Eric Laurentde070132010-07-13 04:45:46 -07007357 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7358 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007359 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007360 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361 }
Eric Laurentde070132010-07-13 04:45:46 -07007362 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7363 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007364 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007365 return BAD_VALUE;
7366 }
7367
7368 Mutex::Autolock _dl(dstThread->mLock);
7369 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007370 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007371
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 return NO_ERROR;
7373}
7374
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007375// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007376status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007377 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007378 AudioFlinger::PlaybackThread *dstThread,
7379 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007380{
Steve Block3856b092011-10-20 11:56:00 +01007381 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007382 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007383
Eric Laurent59255e42011-07-27 19:49:51 -07007384 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007385 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007386 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007387 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007388 return INVALID_OPERATION;
7389 }
7390
Eric Laurent39e94f82010-07-28 01:32:47 -07007391 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007392 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007393 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007394 // removed.
7395 srcThread->removeEffectChain_l(chain);
7396
7397 // transfer all effects one by one so that new effect chain is created on new thread with
7398 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007399 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007400 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007401 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007402 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7403 while (effect != 0) {
7404 srcThread->removeEffect_l(effect);
7405 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007406 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7407 if (effect->state() == EffectModule::ACTIVE ||
7408 effect->state() == EffectModule::STOPPING) {
7409 effect->start();
7410 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007411 // if the move request is not received from audio policy manager, the effect must be
7412 // re-registered with the new strategy and output
7413 if (dstChain == 0) {
7414 dstChain = effect->chain().promote();
7415 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007416 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007417 srcThread->addEffect_l(effect);
7418 return NO_INIT;
7419 }
7420 strategy = dstChain->strategy();
7421 }
7422 if (reRegister) {
7423 AudioSystem::unregisterEffect(effect->id());
7424 AudioSystem::registerEffect(&effect->desc(),
7425 dstOutput,
7426 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007427 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007428 effect->id());
7429 }
Eric Laurentde070132010-07-13 04:45:46 -07007430 effect = chain->getEffectFromId_l(0);
7431 }
7432
7433 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434}
7435
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007436
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007438sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439 const sp<AudioFlinger::Client>& client,
7440 const sp<IEffectClient>& effectClient,
7441 int32_t priority,
7442 int sessionId,
7443 effect_descriptor_t *desc,
7444 int *enabled,
7445 status_t *status
7446 )
7447{
7448 sp<EffectModule> effect;
7449 sp<EffectHandle> handle;
7450 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007452 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453 bool effectCreated = false;
7454 bool effectRegistered = false;
7455
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007456 lStatus = initCheck();
7457 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007458 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007459 goto Exit;
7460 }
7461
7462 // Do not allow effects with session ID 0 on direct output or duplicating threads
7463 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007464 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007465 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007466 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007467 lStatus = BAD_VALUE;
7468 goto Exit;
7469 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007470 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007471 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007472 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007473 desc->name, desc->flags, mType);
7474 lStatus = BAD_VALUE;
7475 goto Exit;
7476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007477
Steve Block3856b092011-10-20 11:56:00 +01007478 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479
7480 { // scope for mLock
7481 Mutex::Autolock _l(mLock);
7482
7483 // check for existing effect chain with the requested audio session
7484 chain = getEffectChain_l(sessionId);
7485 if (chain == 0) {
7486 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007487 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007488 chain = new EffectChain(this, sessionId);
7489 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007490 chain->setStrategy(getStrategyForSession_l(sessionId));
7491 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007493 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007494 }
7495
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007496 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007497
7498 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007499 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007501 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007502 if (lStatus != NO_ERROR) {
7503 goto Exit;
7504 }
7505 effectRegistered = true;
7506 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007507 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007508 lStatus = effect->status();
7509 if (lStatus != NO_ERROR) {
7510 goto Exit;
7511 }
Eric Laurentcab11242010-07-15 12:50:15 -07007512 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007513 if (lStatus != NO_ERROR) {
7514 goto Exit;
7515 }
7516 effectCreated = true;
7517
7518 effect->setDevice(mDevice);
7519 effect->setMode(mAudioFlinger->getMode());
7520 }
7521 // create effect handle and connect it to effect module
7522 handle = new EffectHandle(effect, client, effectClient, priority);
7523 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007524 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525 *enabled = (int)effect->isEnabled();
7526 }
7527 }
7528
7529Exit:
7530 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007531 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007532 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007533 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007534 }
7535 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007536 AudioSystem::unregisterEffect(effect->id());
7537 }
7538 if (chainCreated) {
7539 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 }
7541 handle.clear();
7542 }
7543
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007544 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007545 *status = lStatus;
7546 }
7547 return handle;
7548}
7549
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007550sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7551{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007552 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007553 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007554}
7555
Eric Laurentde070132010-07-13 04:45:46 -07007556// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7557// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007558status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007559{
7560 // check for existing effect chain with the requested audio session
7561 int sessionId = effect->sessionId();
7562 sp<EffectChain> chain = getEffectChain_l(sessionId);
7563 bool chainCreated = false;
7564
7565 if (chain == 0) {
7566 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007567 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007568 chain = new EffectChain(this, sessionId);
7569 addEffectChain_l(chain);
7570 chain->setStrategy(getStrategyForSession_l(sessionId));
7571 chainCreated = true;
7572 }
Steve Block3856b092011-10-20 11:56:00 +01007573 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007574
7575 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007576 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007577 this, effect->desc().name, chain.get());
7578 return BAD_VALUE;
7579 }
7580
7581 status_t status = chain->addEffect_l(effect);
7582 if (status != NO_ERROR) {
7583 if (chainCreated) {
7584 removeEffectChain_l(chain);
7585 }
7586 return status;
7587 }
7588
7589 effect->setDevice(mDevice);
7590 effect->setMode(mAudioFlinger->getMode());
7591 return NO_ERROR;
7592}
7593
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007594void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007595
Steve Block3856b092011-10-20 11:56:00 +01007596 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007598 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7599 detachAuxEffect_l(effect->id());
7600 }
7601
7602 sp<EffectChain> chain = effect->chain().promote();
7603 if (chain != 0) {
7604 // remove effect chain if removing last effect
7605 if (chain->removeEffect_l(effect) == 0) {
7606 removeEffectChain_l(chain);
7607 }
7608 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007609 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007610 }
7611}
7612
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007613void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007614 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007615{
7616 effectChains = mEffectChains;
7617 for (size_t i = 0; i < mEffectChains.size(); i++) {
7618 mEffectChains[i]->lock();
7619 }
7620}
7621
7622void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007623 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007624{
7625 for (size_t i = 0; i < effectChains.size(); i++) {
7626 effectChains[i]->unlock();
7627 }
7628}
7629
7630sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7631{
7632 Mutex::Autolock _l(mLock);
7633 return getEffectChain_l(sessionId);
7634}
7635
7636sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7637{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007638 size_t size = mEffectChains.size();
7639 for (size_t i = 0; i < size; i++) {
7640 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007641 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007642 }
7643 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007644 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007645}
7646
Glenn Kastenf78aee72012-01-04 11:00:47 -08007647void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007648{
7649 Mutex::Autolock _l(mLock);
7650 size_t size = mEffectChains.size();
7651 for (size_t i = 0; i < size; i++) {
7652 mEffectChains[i]->setMode_l(mode);
7653 }
7654}
7655
7656void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007657 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007658 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007659
Mathias Agopian65ab4712010-07-14 17:59:35 -07007660 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007661 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007662 // delete the effect module if removing last handle on it
7663 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007664 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007665 removeEffect_l(effect);
7666 AudioSystem::unregisterEffect(effect->id());
7667 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007668 }
7669}
7670
7671status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7672{
7673 int session = chain->sessionId();
7674 int16_t *buffer = mMixBuffer;
7675 bool ownsBuffer = false;
7676
Steve Block3856b092011-10-20 11:56:00 +01007677 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678 if (session > 0) {
7679 // Only one effect chain can be present in direct output thread and it uses
7680 // the mix buffer as input
7681 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007682 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683 buffer = new int16_t[numSamples];
7684 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007685 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007686 ownsBuffer = true;
7687 }
7688
7689 // Attach all tracks with same session ID to this chain.
7690 for (size_t i = 0; i < mTracks.size(); ++i) {
7691 sp<Track> track = mTracks[i];
7692 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007693 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007694 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007695 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696 }
7697 }
7698
7699 // indicate all active tracks in the chain
7700 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7701 sp<Track> track = mActiveTracks[i].promote();
7702 if (track == 0) continue;
7703 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007704 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007705 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007706 }
7707 }
7708 }
7709
7710 chain->setInBuffer(buffer, ownsBuffer);
7711 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007712 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007713 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007714 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7715 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007717 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7718 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007719 // Effect chain for other sessions are inserted at beginning of effect
7720 // chains list to be processed before output mix effects. Relative order between other
7721 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007722 size_t size = mEffectChains.size();
7723 size_t i = 0;
7724 for (i = 0; i < size; i++) {
7725 if (mEffectChains[i]->sessionId() < session) break;
7726 }
7727 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007728 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729
7730 return NO_ERROR;
7731}
7732
7733size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7734{
7735 int session = chain->sessionId();
7736
Steve Block3856b092011-10-20 11:56:00 +01007737 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007738
7739 for (size_t i = 0; i < mEffectChains.size(); i++) {
7740 if (chain == mEffectChains[i]) {
7741 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007742 // detach all active tracks from the chain
7743 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7744 sp<Track> track = mActiveTracks[i].promote();
7745 if (track == 0) continue;
7746 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007747 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007748 chain.get(), session);
7749 chain->decActiveTrackCnt();
7750 }
7751 }
7752
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753 // detach all tracks with same session ID from this chain
7754 for (size_t i = 0; i < mTracks.size(); ++i) {
7755 sp<Track> track = mTracks[i];
7756 if (session == track->sessionId()) {
7757 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007758 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007759 }
7760 }
Eric Laurentde070132010-07-13 04:45:46 -07007761 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 }
7763 }
7764 return mEffectChains.size();
7765}
7766
Eric Laurentde070132010-07-13 04:45:46 -07007767status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7768 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769{
7770 Mutex::Autolock _l(mLock);
7771 return attachAuxEffect_l(track, EffectId);
7772}
7773
Eric Laurentde070132010-07-13 04:45:46 -07007774status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7775 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776{
7777 status_t status = NO_ERROR;
7778
7779 if (EffectId == 0) {
7780 track->setAuxBuffer(0, NULL);
7781 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007782 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7783 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 if (effect != 0) {
7785 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7786 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7787 } else {
7788 status = INVALID_OPERATION;
7789 }
7790 } else {
7791 status = BAD_VALUE;
7792 }
7793 }
7794 return status;
7795}
7796
7797void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7798{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007799 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800 sp<Track> track = mTracks[i];
7801 if (track->auxEffectId() == effectId) {
7802 attachAuxEffect_l(track, 0);
7803 }
7804 }
7805}
7806
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007807status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7808{
7809 // only one chain per input thread
7810 if (mEffectChains.size() != 0) {
7811 return INVALID_OPERATION;
7812 }
Steve Block3856b092011-10-20 11:56:00 +01007813 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007814
7815 chain->setInBuffer(NULL);
7816 chain->setOutBuffer(NULL);
7817
Eric Laurent59255e42011-07-27 19:49:51 -07007818 checkSuspendOnAddEffectChain_l(chain);
7819
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007820 mEffectChains.add(chain);
7821
7822 return NO_ERROR;
7823}
7824
7825size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7826{
Steve Block3856b092011-10-20 11:56:00 +01007827 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007828 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007829 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7830 chain.get(), mEffectChains.size(), this);
7831 if (mEffectChains.size() == 1) {
7832 mEffectChains.removeAt(0);
7833 }
7834 return 0;
7835}
7836
Mathias Agopian65ab4712010-07-14 17:59:35 -07007837// ----------------------------------------------------------------------------
7838// EffectModule implementation
7839// ----------------------------------------------------------------------------
7840
7841#undef LOG_TAG
7842#define LOG_TAG "AudioFlinger::EffectModule"
7843
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007844AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845 const wp<AudioFlinger::EffectChain>& chain,
7846 effect_descriptor_t *desc,
7847 int id,
7848 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007849 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007850 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007851{
Steve Block3856b092011-10-20 11:56:00 +01007852 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007854 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007855 return;
7856 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857
7858 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7859
7860 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007861 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862
7863 if (mStatus != NO_ERROR) {
7864 return;
7865 }
7866 lStatus = init();
7867 if (lStatus < 0) {
7868 mStatus = lStatus;
7869 goto Error;
7870 }
7871
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007872 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7873 mPinned = true;
7874 }
Steve Block3856b092011-10-20 11:56:00 +01007875 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 return;
7877Error:
7878 EffectRelease(mEffectInterface);
7879 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007880 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881}
7882
7883AudioFlinger::EffectModule::~EffectModule()
7884{
Steve Block3856b092011-10-20 11:56:00 +01007885 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007886 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007887 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7888 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7889 sp<ThreadBase> thread = mThread.promote();
7890 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007891 audio_stream_t *stream = thread->stream();
7892 if (stream != NULL) {
7893 stream->remove_audio_effect(stream, mEffectInterface);
7894 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007895 }
7896 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897 // release effect engine
7898 EffectRelease(mEffectInterface);
7899 }
7900}
7901
Glenn Kasten435dbe62012-01-30 10:15:48 -08007902status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007903{
7904 status_t status;
7905
7906 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907 int priority = handle->priority();
7908 size_t size = mHandles.size();
7909 sp<EffectHandle> h;
7910 size_t i;
7911 for (i = 0; i < size; i++) {
7912 h = mHandles[i].promote();
7913 if (h == 0) continue;
7914 if (h->priority() <= priority) break;
7915 }
7916 // if inserted in first place, move effect control from previous owner to this handle
7917 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007918 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007920 enabled = h->enabled();
7921 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 }
Eric Laurent59255e42011-07-27 19:49:51 -07007923 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007924 status = NO_ERROR;
7925 } else {
7926 status = ALREADY_EXISTS;
7927 }
Steve Block3856b092011-10-20 11:56:00 +01007928 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007929 mHandles.insertAt(handle, i);
7930 return status;
7931}
7932
7933size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7934{
7935 Mutex::Autolock _l(mLock);
7936 size_t size = mHandles.size();
7937 size_t i;
7938 for (i = 0; i < size; i++) {
7939 if (mHandles[i] == handle) break;
7940 }
7941 if (i == size) {
7942 return size;
7943 }
Steve Block3856b092011-10-20 11:56:00 +01007944 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007945
7946 bool enabled = false;
7947 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007948 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007949 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007950 enabled = hdl->enabled();
7951 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952 mHandles.removeAt(i);
7953 size = mHandles.size();
7954 // if removed from first place, move effect control from this handle to next in line
7955 if (i == 0 && size != 0) {
7956 sp<EffectHandle> h = mHandles[0].promote();
7957 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007958 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 }
7960 }
7961
Eric Laurentec437d82011-07-26 20:54:46 -07007962 // Prevent calls to process() and other functions on effect interface from now on.
7963 // The effect engine will be released by the destructor when the last strong reference on
7964 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007965 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007966 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007967 }
7968
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969 return size;
7970}
7971
Eric Laurent59255e42011-07-27 19:49:51 -07007972sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7973{
7974 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007975 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007976}
7977
Glenn Kasten58123c32012-02-03 10:32:24 -08007978void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007979{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007980 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007981 // keep a strong reference on this EffectModule to avoid calling the
7982 // destructor before we exit
7983 sp<EffectModule> keep(this);
7984 {
7985 sp<ThreadBase> thread = mThread.promote();
7986 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007987 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988 }
7989 }
7990}
7991
7992void AudioFlinger::EffectModule::updateState() {
7993 Mutex::Autolock _l(mLock);
7994
7995 switch (mState) {
7996 case RESTART:
7997 reset_l();
7998 // FALL THROUGH
7999
8000 case STARTING:
8001 // clear auxiliary effect input buffer for next accumulation
8002 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8003 memset(mConfig.inputCfg.buffer.raw,
8004 0,
8005 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8006 }
8007 start_l();
8008 mState = ACTIVE;
8009 break;
8010 case STOPPING:
8011 stop_l();
8012 mDisableWaitCnt = mMaxDisableWaitCnt;
8013 mState = STOPPED;
8014 break;
8015 case STOPPED:
8016 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8017 // turn off sequence.
8018 if (--mDisableWaitCnt == 0) {
8019 reset_l();
8020 mState = IDLE;
8021 }
8022 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008023 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024 break;
8025 }
8026}
8027
8028void AudioFlinger::EffectModule::process()
8029{
8030 Mutex::Autolock _l(mLock);
8031
Eric Laurentec437d82011-07-26 20:54:46 -07008032 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008033 mConfig.inputCfg.buffer.raw == NULL ||
8034 mConfig.outputCfg.buffer.raw == NULL) {
8035 return;
8036 }
8037
Eric Laurent8f45bd72010-08-31 13:50:07 -07008038 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008039 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8040 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008041 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008043 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044 }
8045
8046 // do the actual processing in the effect engine
8047 int ret = (*mEffectInterface)->process(mEffectInterface,
8048 &mConfig.inputCfg.buffer,
8049 &mConfig.outputCfg.buffer);
8050
8051 // force transition to IDLE state when engine is ready
8052 if (mState == STOPPED && ret == -ENODATA) {
8053 mDisableWaitCnt = 1;
8054 }
8055
8056 // clear auxiliary effect input buffer for next accumulation
8057 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008058 memset(mConfig.inputCfg.buffer.raw, 0,
8059 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060 }
8061 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008062 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8063 // If an insert effect is idle and input buffer is different from output buffer,
8064 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008066 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008067 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8068 int16_t *in = mConfig.inputCfg.buffer.s16;
8069 int16_t *out = mConfig.outputCfg.buffer.s16;
8070 for (size_t i = 0; i < frameCnt; i++) {
8071 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008072 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073 }
8074 }
8075}
8076
8077void AudioFlinger::EffectModule::reset_l()
8078{
8079 if (mEffectInterface == NULL) {
8080 return;
8081 }
8082 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8083}
8084
8085status_t AudioFlinger::EffectModule::configure()
8086{
8087 uint32_t channels;
8088 if (mEffectInterface == NULL) {
8089 return NO_INIT;
8090 }
8091
8092 sp<ThreadBase> thread = mThread.promote();
8093 if (thread == 0) {
8094 return DEAD_OBJECT;
8095 }
8096
8097 // TODO: handle configuration of effects replacing track process
8098 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008099 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008100 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008101 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102 }
8103
8104 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008105 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008106 } else {
8107 mConfig.inputCfg.channels = channels;
8108 }
8109 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008110 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8111 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008112 mConfig.inputCfg.samplingRate = thread->sampleRate();
8113 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8114 mConfig.inputCfg.bufferProvider.cookie = NULL;
8115 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8116 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8117 mConfig.outputCfg.bufferProvider.cookie = NULL;
8118 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8119 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8120 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8121 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008122 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008123 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008124 // - in other sessions:
8125 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8126 // other effect: overwrites output buffer: input buffer == output buffer
8127 // Auxiliary effect:
8128 // accumulates in output buffer: input buffer != output buffer
8129 // Therefore: accumulate <=> input buffer != output buffer
8130 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8131 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8132 } else {
8133 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8134 }
8135 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8136 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8137 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8138 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8139
Steve Block3856b092011-10-20 11:56:00 +01008140 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008141 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8142
Mathias Agopian65ab4712010-07-14 17:59:35 -07008143 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008144 uint32_t size = sizeof(int);
8145 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008146 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008147 sizeof(effect_config_t),
8148 &mConfig,
8149 &size,
8150 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008151 if (status == 0) {
8152 status = cmdStatus;
8153 }
8154
8155 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8156 (1000 * mConfig.outputCfg.buffer.frameCount);
8157
8158 return status;
8159}
8160
8161status_t AudioFlinger::EffectModule::init()
8162{
8163 Mutex::Autolock _l(mLock);
8164 if (mEffectInterface == NULL) {
8165 return NO_INIT;
8166 }
8167 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008168 uint32_t size = sizeof(status_t);
8169 status_t status = (*mEffectInterface)->command(mEffectInterface,
8170 EFFECT_CMD_INIT,
8171 0,
8172 NULL,
8173 &size,
8174 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008175 if (status == 0) {
8176 status = cmdStatus;
8177 }
8178 return status;
8179}
8180
Eric Laurentec35a142011-10-05 17:42:25 -07008181status_t AudioFlinger::EffectModule::start()
8182{
8183 Mutex::Autolock _l(mLock);
8184 return start_l();
8185}
8186
Mathias Agopian65ab4712010-07-14 17:59:35 -07008187status_t AudioFlinger::EffectModule::start_l()
8188{
8189 if (mEffectInterface == NULL) {
8190 return NO_INIT;
8191 }
8192 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008193 uint32_t size = sizeof(status_t);
8194 status_t status = (*mEffectInterface)->command(mEffectInterface,
8195 EFFECT_CMD_ENABLE,
8196 0,
8197 NULL,
8198 &size,
8199 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 if (status == 0) {
8201 status = cmdStatus;
8202 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008203 if (status == 0 &&
8204 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8205 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8206 sp<ThreadBase> thread = mThread.promote();
8207 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008208 audio_stream_t *stream = thread->stream();
8209 if (stream != NULL) {
8210 stream->add_audio_effect(stream, mEffectInterface);
8211 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008212 }
8213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214 return status;
8215}
8216
Eric Laurentec437d82011-07-26 20:54:46 -07008217status_t AudioFlinger::EffectModule::stop()
8218{
8219 Mutex::Autolock _l(mLock);
8220 return stop_l();
8221}
8222
Mathias Agopian65ab4712010-07-14 17:59:35 -07008223status_t AudioFlinger::EffectModule::stop_l()
8224{
8225 if (mEffectInterface == NULL) {
8226 return NO_INIT;
8227 }
8228 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008229 uint32_t size = sizeof(status_t);
8230 status_t status = (*mEffectInterface)->command(mEffectInterface,
8231 EFFECT_CMD_DISABLE,
8232 0,
8233 NULL,
8234 &size,
8235 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008236 if (status == 0) {
8237 status = cmdStatus;
8238 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008239 if (status == 0 &&
8240 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8241 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8242 sp<ThreadBase> thread = mThread.promote();
8243 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008244 audio_stream_t *stream = thread->stream();
8245 if (stream != NULL) {
8246 stream->remove_audio_effect(stream, mEffectInterface);
8247 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008248 }
8249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250 return status;
8251}
8252
Eric Laurent25f43952010-07-28 05:40:18 -07008253status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8254 uint32_t cmdSize,
8255 void *pCmdData,
8256 uint32_t *replySize,
8257 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008258{
8259 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008260// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008261
Eric Laurentec437d82011-07-26 20:54:46 -07008262 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008263 return NO_INIT;
8264 }
Eric Laurent25f43952010-07-28 05:40:18 -07008265 status_t status = (*mEffectInterface)->command(mEffectInterface,
8266 cmdCode,
8267 cmdSize,
8268 pCmdData,
8269 replySize,
8270 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008272 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008273 for (size_t i = 1; i < mHandles.size(); i++) {
8274 sp<EffectHandle> h = mHandles[i].promote();
8275 if (h != 0) {
8276 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8277 }
8278 }
8279 }
8280 return status;
8281}
8282
8283status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8284{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008285
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008287 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008288
8289 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008290 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8291 if (enabled && status != NO_ERROR) {
8292 return status;
8293 }
8294
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295 switch (mState) {
8296 // going from disabled to enabled
8297 case IDLE:
8298 mState = STARTING;
8299 break;
8300 case STOPPED:
8301 mState = RESTART;
8302 break;
8303 case STOPPING:
8304 mState = ACTIVE;
8305 break;
8306
8307 // going from enabled to disabled
8308 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008309 mState = STOPPED;
8310 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008311 case STARTING:
8312 mState = IDLE;
8313 break;
8314 case ACTIVE:
8315 mState = STOPPING;
8316 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008317 case DESTROYED:
8318 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319 }
8320 for (size_t i = 1; i < mHandles.size(); i++) {
8321 sp<EffectHandle> h = mHandles[i].promote();
8322 if (h != 0) {
8323 h->setEnabled(enabled);
8324 }
8325 }
8326 }
8327 return NO_ERROR;
8328}
8329
Glenn Kastenc59c0042012-02-02 14:06:11 -08008330bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008331{
8332 switch (mState) {
8333 case RESTART:
8334 case STARTING:
8335 case ACTIVE:
8336 return true;
8337 case IDLE:
8338 case STOPPING:
8339 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008340 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008341 default:
8342 return false;
8343 }
8344}
8345
Glenn Kastenc59c0042012-02-02 14:06:11 -08008346bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008347{
8348 switch (mState) {
8349 case RESTART:
8350 case ACTIVE:
8351 case STOPPING:
8352 case STOPPED:
8353 return true;
8354 case IDLE:
8355 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008356 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008357 default:
8358 return false;
8359 }
8360}
8361
Mathias Agopian65ab4712010-07-14 17:59:35 -07008362status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8363{
8364 Mutex::Autolock _l(mLock);
8365 status_t status = NO_ERROR;
8366
8367 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8368 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008369 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008370 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8371 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008372 status_t cmdStatus;
8373 uint32_t volume[2];
8374 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008375 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376 volume[0] = *left;
8377 volume[1] = *right;
8378 if (controller) {
8379 pVolume = volume;
8380 }
Eric Laurent25f43952010-07-28 05:40:18 -07008381 status = (*mEffectInterface)->command(mEffectInterface,
8382 EFFECT_CMD_SET_VOLUME,
8383 size,
8384 volume,
8385 &size,
8386 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8388 *left = volume[0];
8389 *right = volume[1];
8390 }
8391 }
8392 return status;
8393}
8394
8395status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8396{
8397 Mutex::Autolock _l(mLock);
8398 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008399 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8400 // audio pre processing modules on RecordThread can receive both output and
8401 // input device indication in the same call
8402 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8403 if (dev) {
8404 status_t cmdStatus;
8405 uint32_t size = sizeof(status_t);
8406
8407 status = (*mEffectInterface)->command(mEffectInterface,
8408 EFFECT_CMD_SET_DEVICE,
8409 sizeof(uint32_t),
8410 &dev,
8411 &size,
8412 &cmdStatus);
8413 if (status == NO_ERROR) {
8414 status = cmdStatus;
8415 }
8416 }
8417 dev = device & AUDIO_DEVICE_IN_ALL;
8418 if (dev) {
8419 status_t cmdStatus;
8420 uint32_t size = sizeof(status_t);
8421
8422 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8423 EFFECT_CMD_SET_INPUT_DEVICE,
8424 sizeof(uint32_t),
8425 &dev,
8426 &size,
8427 &cmdStatus);
8428 if (status2 == NO_ERROR) {
8429 status2 = cmdStatus;
8430 }
8431 if (status == NO_ERROR) {
8432 status = status2;
8433 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008434 }
8435 }
8436 return status;
8437}
8438
Glenn Kastenf78aee72012-01-04 11:00:47 -08008439status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008440{
8441 Mutex::Autolock _l(mLock);
8442 status_t status = NO_ERROR;
8443 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008445 uint32_t size = sizeof(status_t);
8446 status = (*mEffectInterface)->command(mEffectInterface,
8447 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008448 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008449 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008450 &size,
8451 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452 if (status == NO_ERROR) {
8453 status = cmdStatus;
8454 }
8455 }
8456 return status;
8457}
8458
Eric Laurent59255e42011-07-27 19:49:51 -07008459void AudioFlinger::EffectModule::setSuspended(bool suspended)
8460{
8461 Mutex::Autolock _l(mLock);
8462 mSuspended = suspended;
8463}
Glenn Kastena3a85482012-01-04 11:01:11 -08008464
8465bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008466{
8467 Mutex::Autolock _l(mLock);
8468 return mSuspended;
8469}
8470
Mathias Agopian65ab4712010-07-14 17:59:35 -07008471status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8472{
8473 const size_t SIZE = 256;
8474 char buffer[SIZE];
8475 String8 result;
8476
8477 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8478 result.append(buffer);
8479
8480 bool locked = tryLock(mLock);
8481 // failed to lock - AudioFlinger is probably deadlocked
8482 if (!locked) {
8483 result.append("\t\tCould not lock Fx mutex:\n");
8484 }
8485
8486 result.append("\t\tSession Status State Engine:\n");
8487 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8488 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8489 result.append(buffer);
8490
8491 result.append("\t\tDescriptor:\n");
8492 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8493 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8494 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8495 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8496 result.append(buffer);
8497 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8498 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8499 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8500 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8501 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008502 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503 mDescriptor.apiVersion,
8504 mDescriptor.flags);
8505 result.append(buffer);
8506 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8507 mDescriptor.name);
8508 result.append(buffer);
8509 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8510 mDescriptor.implementor);
8511 result.append(buffer);
8512
8513 result.append("\t\t- Input configuration:\n");
8514 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8515 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8516 (uint32_t)mConfig.inputCfg.buffer.raw,
8517 mConfig.inputCfg.buffer.frameCount,
8518 mConfig.inputCfg.samplingRate,
8519 mConfig.inputCfg.channels,
8520 mConfig.inputCfg.format);
8521 result.append(buffer);
8522
8523 result.append("\t\t- Output configuration:\n");
8524 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8525 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8526 (uint32_t)mConfig.outputCfg.buffer.raw,
8527 mConfig.outputCfg.buffer.frameCount,
8528 mConfig.outputCfg.samplingRate,
8529 mConfig.outputCfg.channels,
8530 mConfig.outputCfg.format);
8531 result.append(buffer);
8532
8533 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8534 result.append(buffer);
8535 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8536 for (size_t i = 0; i < mHandles.size(); ++i) {
8537 sp<EffectHandle> handle = mHandles[i].promote();
8538 if (handle != 0) {
8539 handle->dump(buffer, SIZE);
8540 result.append(buffer);
8541 }
8542 }
8543
8544 result.append("\n");
8545
8546 write(fd, result.string(), result.length());
8547
8548 if (locked) {
8549 mLock.unlock();
8550 }
8551
8552 return NO_ERROR;
8553}
8554
8555// ----------------------------------------------------------------------------
8556// EffectHandle implementation
8557// ----------------------------------------------------------------------------
8558
8559#undef LOG_TAG
8560#define LOG_TAG "AudioFlinger::EffectHandle"
8561
8562AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8563 const sp<AudioFlinger::Client>& client,
8564 const sp<IEffectClient>& effectClient,
8565 int32_t priority)
8566 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008567 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008568 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569{
Steve Block3856b092011-10-20 11:56:00 +01008570 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008572 if (client == 0) {
8573 return;
8574 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8576 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8577 if (mCblkMemory != 0) {
8578 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8579
Glenn Kastena0d68332012-01-27 16:47:15 -08008580 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008581 new(mCblk) effect_param_cblk_t();
8582 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008583 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008584 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008585 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008586 return;
8587 }
8588}
8589
8590AudioFlinger::EffectHandle::~EffectHandle()
8591{
Steve Block3856b092011-10-20 11:56:00 +01008592 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008593 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008594 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008595}
8596
8597status_t AudioFlinger::EffectHandle::enable()
8598{
Steve Block3856b092011-10-20 11:56:00 +01008599 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008600 if (!mHasControl) return INVALID_OPERATION;
8601 if (mEffect == 0) return DEAD_OBJECT;
8602
Eric Laurentdb7c0792011-08-10 10:37:50 -07008603 if (mEnabled) {
8604 return NO_ERROR;
8605 }
8606
Eric Laurent59255e42011-07-27 19:49:51 -07008607 mEnabled = true;
8608
8609 sp<ThreadBase> thread = mEffect->thread().promote();
8610 if (thread != 0) {
8611 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8612 }
8613
8614 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8615 if (mEffect->suspended()) {
8616 return NO_ERROR;
8617 }
8618
Eric Laurentdb7c0792011-08-10 10:37:50 -07008619 status_t status = mEffect->setEnabled(true);
8620 if (status != NO_ERROR) {
8621 if (thread != 0) {
8622 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8623 }
8624 mEnabled = false;
8625 }
8626 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008627}
8628
8629status_t AudioFlinger::EffectHandle::disable()
8630{
Steve Block3856b092011-10-20 11:56:00 +01008631 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008632 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008633 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008634
Eric Laurentdb7c0792011-08-10 10:37:50 -07008635 if (!mEnabled) {
8636 return NO_ERROR;
8637 }
Eric Laurent59255e42011-07-27 19:49:51 -07008638 mEnabled = false;
8639
8640 if (mEffect->suspended()) {
8641 return NO_ERROR;
8642 }
8643
8644 status_t status = mEffect->setEnabled(false);
8645
8646 sp<ThreadBase> thread = mEffect->thread().promote();
8647 if (thread != 0) {
8648 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8649 }
8650
8651 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008652}
8653
8654void AudioFlinger::EffectHandle::disconnect()
8655{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008656 disconnect(true);
8657}
8658
Glenn Kasten58123c32012-02-03 10:32:24 -08008659void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008660{
Glenn Kasten58123c32012-02-03 10:32:24 -08008661 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008662 if (mEffect == 0) {
8663 return;
8664 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008665 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008666
Eric Laurenta85a74a2011-10-19 11:44:54 -07008667 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008668 sp<ThreadBase> thread = mEffect->thread().promote();
8669 if (thread != 0) {
8670 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8671 }
Eric Laurent59255e42011-07-27 19:49:51 -07008672 }
8673
Mathias Agopian65ab4712010-07-14 17:59:35 -07008674 // release sp on module => module destructor can be called now
8675 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008676 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008677 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008678 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008679 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8680 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008681 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008682 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008683 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8684 mClient.clear();
8685 }
8686}
8687
Eric Laurent25f43952010-07-28 05:40:18 -07008688status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8689 uint32_t cmdSize,
8690 void *pCmdData,
8691 uint32_t *replySize,
8692 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008693{
Steve Block3856b092011-10-20 11:56:00 +01008694// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008695// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008696
8697 // only get parameter command is permitted for applications not controlling the effect
8698 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8699 return INVALID_OPERATION;
8700 }
8701 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008702 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008703
8704 // handle commands that are not forwarded transparently to effect engine
8705 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8706 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8707 // no risk to block the whole media server process or mixer threads is we are stuck here
8708 Mutex::Autolock _l(mCblk->lock);
8709 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8710 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8711 mCblk->serverIndex = 0;
8712 mCblk->clientIndex = 0;
8713 return BAD_VALUE;
8714 }
8715 status_t status = NO_ERROR;
8716 while (mCblk->serverIndex < mCblk->clientIndex) {
8717 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008718 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008719 int *p = (int *)(mBuffer + mCblk->serverIndex);
8720 int size = *p++;
8721 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008722 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008723 break;
8724 }
8725 effect_param_t *param = (effect_param_t *)p;
8726 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008727 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008728 mCblk->serverIndex += size;
8729 continue;
8730 }
Eric Laurent25f43952010-07-28 05:40:18 -07008731 uint32_t psize = sizeof(effect_param_t) +
8732 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8733 param->vsize;
8734 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8735 psize,
8736 p,
8737 &rsize,
8738 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008739 // stop at first error encountered
8740 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008741 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008742 *(int *)pReplyData = reply;
8743 break;
8744 } else if (reply != NO_ERROR) {
8745 *(int *)pReplyData = reply;
8746 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008747 }
8748 mCblk->serverIndex += size;
8749 }
8750 mCblk->serverIndex = 0;
8751 mCblk->clientIndex = 0;
8752 return status;
8753 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008754 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755 return enable();
8756 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008757 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008758 return disable();
8759 }
8760
8761 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8762}
8763
Eric Laurent59255e42011-07-27 19:49:51 -07008764void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765{
Steve Block3856b092011-10-20 11:56:00 +01008766 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008767
8768 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008769 mEnabled = enabled;
8770
Mathias Agopian65ab4712010-07-14 17:59:35 -07008771 if (signal && mEffectClient != 0) {
8772 mEffectClient->controlStatusChanged(hasControl);
8773 }
8774}
8775
Eric Laurent25f43952010-07-28 05:40:18 -07008776void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8777 uint32_t cmdSize,
8778 void *pCmdData,
8779 uint32_t replySize,
8780 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008781{
8782 if (mEffectClient != 0) {
8783 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8784 }
8785}
8786
8787
8788
8789void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8790{
8791 if (mEffectClient != 0) {
8792 mEffectClient->enableStatusChanged(enabled);
8793 }
8794}
8795
8796status_t AudioFlinger::EffectHandle::onTransact(
8797 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8798{
8799 return BnEffect::onTransact(code, data, reply, flags);
8800}
8801
8802
8803void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8804{
Glenn Kastena0d68332012-01-27 16:47:15 -08008805 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008806
8807 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008808 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008809 mPriority,
8810 mHasControl,
8811 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008812 mCblk ? mCblk->clientIndex : 0,
8813 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008814 );
8815
8816 if (locked) {
8817 mCblk->lock.unlock();
8818 }
8819}
8820
8821#undef LOG_TAG
8822#define LOG_TAG "AudioFlinger::EffectChain"
8823
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008824AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008825 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008826 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008827 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8828 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008829{
Dima Zavinfce7a472011-04-19 22:30:36 -07008830 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008831 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008832 return;
8833 }
8834 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8835 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008836}
8837
8838AudioFlinger::EffectChain::~EffectChain()
8839{
8840 if (mOwnInBuffer) {
8841 delete mInBuffer;
8842 }
8843
8844}
8845
Eric Laurent59255e42011-07-27 19:49:51 -07008846// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008847sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008848{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008849 size_t size = mEffects.size();
8850
8851 for (size_t i = 0; i < size; i++) {
8852 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008853 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008854 }
8855 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008856 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857}
8858
Eric Laurent59255e42011-07-27 19:49:51 -07008859// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008860sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008861{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008862 size_t size = mEffects.size();
8863
8864 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008865 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8866 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008867 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868 }
8869 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008870 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008871}
8872
Eric Laurent59255e42011-07-27 19:49:51 -07008873// getEffectFromType_l() must be called with ThreadBase::mLock held
8874sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8875 const effect_uuid_t *type)
8876{
Eric Laurent59255e42011-07-27 19:49:51 -07008877 size_t size = mEffects.size();
8878
8879 for (size_t i = 0; i < size; i++) {
8880 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008881 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008882 }
8883 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008884 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008885}
8886
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887// Must be called with EffectChain::mLock locked
8888void AudioFlinger::EffectChain::process_l()
8889{
Eric Laurentdac69112010-09-28 14:09:57 -07008890 sp<ThreadBase> thread = mThread.promote();
8891 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008892 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008893 return;
8894 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008895 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8896 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008897 // always process effects unless no more tracks are on the session and the effect tail
8898 // has been rendered
8899 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008900 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008901 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008902
Eric Laurent544fe9b2011-11-11 15:42:52 -08008903 if (!tracksOnSession && mTailBufferCount == 0) {
8904 doProcess = false;
8905 }
8906
8907 if (activeTrackCnt() == 0) {
8908 // if no track is active and the effect tail has not been rendered,
8909 // the input buffer must be cleared here as the mixer process will not do it
8910 if (tracksOnSession || mTailBufferCount > 0) {
8911 size_t numSamples = thread->frameCount() * thread->channelCount();
8912 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8913 if (mTailBufferCount > 0) {
8914 mTailBufferCount--;
8915 }
8916 }
8917 }
Eric Laurentdac69112010-09-28 14:09:57 -07008918 }
8919
Mathias Agopian65ab4712010-07-14 17:59:35 -07008920 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008921 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008922 for (size_t i = 0; i < size; i++) {
8923 mEffects[i]->process();
8924 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008925 }
8926 for (size_t i = 0; i < size; i++) {
8927 mEffects[i]->updateState();
8928 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929}
8930
Eric Laurentcab11242010-07-15 12:50:15 -07008931// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008932status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008933{
8934 effect_descriptor_t desc = effect->desc();
8935 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8936
8937 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008938 effect->setChain(this);
8939 sp<ThreadBase> thread = mThread.promote();
8940 if (thread == 0) {
8941 return NO_INIT;
8942 }
8943 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008944
8945 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8946 // Auxiliary effects are inserted at the beginning of mEffects vector as
8947 // they are processed first and accumulated in chain input buffer
8948 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008949
Mathias Agopian65ab4712010-07-14 17:59:35 -07008950 // the input buffer for auxiliary effect contains mono samples in
8951 // 32 bit format. This is to avoid saturation in AudoMixer
8952 // accumulation stage. Saturation is done in EffectModule::process() before
8953 // calling the process in effect engine
8954 size_t numSamples = thread->frameCount();
8955 int32_t *buffer = new int32_t[numSamples];
8956 memset(buffer, 0, numSamples * sizeof(int32_t));
8957 effect->setInBuffer((int16_t *)buffer);
8958 // auxiliary effects output samples to chain input buffer for further processing
8959 // by insert effects
8960 effect->setOutBuffer(mInBuffer);
8961 } else {
8962 // Insert effects are inserted at the end of mEffects vector as they are processed
8963 // after track and auxiliary effects.
8964 // Insert effect order as a function of indicated preference:
8965 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8966 // another effect is present
8967 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8968 // last effect claiming first position
8969 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8970 // first effect claiming last position
8971 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8972 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8973 // already present
8974
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008975 size_t size = mEffects.size();
8976 size_t idx_insert = size;
8977 ssize_t idx_insert_first = -1;
8978 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008979
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008980 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008981 effect_descriptor_t d = mEffects[i]->desc();
8982 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8983 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8984 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8985 // check invalid effect chaining combinations
8986 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8987 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008988 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989 return INVALID_OPERATION;
8990 }
8991 // remember position of first insert effect and by default
8992 // select this as insert position for new effect
8993 if (idx_insert == size) {
8994 idx_insert = i;
8995 }
8996 // remember position of last insert effect claiming
8997 // first position
8998 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8999 idx_insert_first = i;
9000 }
9001 // remember position of first insert effect claiming
9002 // last position
9003 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9004 idx_insert_last == -1) {
9005 idx_insert_last = i;
9006 }
9007 }
9008 }
9009
9010 // modify idx_insert from first position if needed
9011 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9012 if (idx_insert_last != -1) {
9013 idx_insert = idx_insert_last;
9014 } else {
9015 idx_insert = size;
9016 }
9017 } else {
9018 if (idx_insert_first != -1) {
9019 idx_insert = idx_insert_first + 1;
9020 }
9021 }
9022
9023 // always read samples from chain input buffer
9024 effect->setInBuffer(mInBuffer);
9025
9026 // if last effect in the chain, output samples to chain
9027 // output buffer, otherwise to chain input buffer
9028 if (idx_insert == size) {
9029 if (idx_insert != 0) {
9030 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9031 mEffects[idx_insert-1]->configure();
9032 }
9033 effect->setOutBuffer(mOutBuffer);
9034 } else {
9035 effect->setOutBuffer(mInBuffer);
9036 }
9037 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038
Steve Block3856b092011-10-20 11:56:00 +01009039 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009040 }
9041 effect->configure();
9042 return NO_ERROR;
9043}
9044
Eric Laurentcab11242010-07-15 12:50:15 -07009045// removeEffect_l() must be called with PlaybackThread::mLock held
9046size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009047{
9048 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009049 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009050 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9051
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009052 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009053 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009054 // calling stop here will remove pre-processing effect from the audio HAL.
9055 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9056 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009057 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9058 mEffects[i]->state() == EffectModule::STOPPING) {
9059 mEffects[i]->stop();
9060 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009061 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9062 delete[] effect->inBuffer();
9063 } else {
9064 if (i == size - 1 && i != 0) {
9065 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9066 mEffects[i - 1]->configure();
9067 }
9068 }
9069 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009070 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009071 break;
9072 }
9073 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009074
9075 return mEffects.size();
9076}
9077
Eric Laurentcab11242010-07-15 12:50:15 -07009078// setDevice_l() must be called with PlaybackThread::mLock held
9079void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009080{
9081 size_t size = mEffects.size();
9082 for (size_t i = 0; i < size; i++) {
9083 mEffects[i]->setDevice(device);
9084 }
9085}
9086
Eric Laurentcab11242010-07-15 12:50:15 -07009087// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009088void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009089{
9090 size_t size = mEffects.size();
9091 for (size_t i = 0; i < size; i++) {
9092 mEffects[i]->setMode(mode);
9093 }
9094}
9095
Eric Laurentcab11242010-07-15 12:50:15 -07009096// setVolume_l() must be called with PlaybackThread::mLock held
9097bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009098{
9099 uint32_t newLeft = *left;
9100 uint32_t newRight = *right;
9101 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009102 int ctrlIdx = -1;
9103 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009104
Eric Laurentcab11242010-07-15 12:50:15 -07009105 // first update volume controller
9106 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009107 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009108 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9109 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009110 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009111 break;
9112 }
9113 }
9114
9115 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009116 if (hasControl) {
9117 *left = mNewLeftVolume;
9118 *right = mNewRightVolume;
9119 }
9120 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009121 }
9122
9123 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009124 mLeftVolume = newLeft;
9125 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009126
9127 // second get volume update from volume controller
9128 if (ctrlIdx >= 0) {
9129 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009130 mNewLeftVolume = newLeft;
9131 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009132 }
9133 // then indicate volume to all other effects in chain.
9134 // Pass altered volume to effects before volume controller
9135 // and requested volume to effects after controller
9136 uint32_t lVol = newLeft;
9137 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009138
Mathias Agopian65ab4712010-07-14 17:59:35 -07009139 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009140 if ((int)i == ctrlIdx) continue;
9141 // this also works for ctrlIdx == -1 when there is no volume controller
9142 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009143 lVol = *left;
9144 rVol = *right;
9145 }
9146 mEffects[i]->setVolume(&lVol, &rVol, false);
9147 }
9148 *left = newLeft;
9149 *right = newRight;
9150
9151 return hasControl;
9152}
9153
Mathias Agopian65ab4712010-07-14 17:59:35 -07009154status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9155{
9156 const size_t SIZE = 256;
9157 char buffer[SIZE];
9158 String8 result;
9159
9160 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9161 result.append(buffer);
9162
9163 bool locked = tryLock(mLock);
9164 // failed to lock - AudioFlinger is probably deadlocked
9165 if (!locked) {
9166 result.append("\tCould not lock mutex:\n");
9167 }
9168
Eric Laurentcab11242010-07-15 12:50:15 -07009169 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9170 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009171 mEffects.size(),
9172 (uint32_t)mInBuffer,
9173 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009174 mActiveTrackCnt);
9175 result.append(buffer);
9176 write(fd, result.string(), result.size());
9177
9178 for (size_t i = 0; i < mEffects.size(); ++i) {
9179 sp<EffectModule> effect = mEffects[i];
9180 if (effect != 0) {
9181 effect->dump(fd, args);
9182 }
9183 }
9184
9185 if (locked) {
9186 mLock.unlock();
9187 }
9188
9189 return NO_ERROR;
9190}
9191
Eric Laurent59255e42011-07-27 19:49:51 -07009192// must be called with ThreadBase::mLock held
9193void AudioFlinger::EffectChain::setEffectSuspended_l(
9194 const effect_uuid_t *type, bool suspend)
9195{
9196 sp<SuspendedEffectDesc> desc;
9197 // use effect type UUID timelow as key as there is no real risk of identical
9198 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009199 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009200 if (suspend) {
9201 if (index >= 0) {
9202 desc = mSuspendedEffects.valueAt(index);
9203 } else {
9204 desc = new SuspendedEffectDesc();
9205 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9206 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009207 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009208 }
9209 if (desc->mRefCount++ == 0) {
9210 sp<EffectModule> effect = getEffectIfEnabled(type);
9211 if (effect != 0) {
9212 desc->mEffect = effect;
9213 effect->setSuspended(true);
9214 effect->setEnabled(false);
9215 }
9216 }
9217 } else {
9218 if (index < 0) {
9219 return;
9220 }
9221 desc = mSuspendedEffects.valueAt(index);
9222 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009223 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009224 desc->mRefCount = 1;
9225 }
9226 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009227 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009228 if (desc->mEffect != 0) {
9229 sp<EffectModule> effect = desc->mEffect.promote();
9230 if (effect != 0) {
9231 effect->setSuspended(false);
9232 sp<EffectHandle> handle = effect->controlHandle();
9233 if (handle != 0) {
9234 effect->setEnabled(handle->enabled());
9235 }
9236 }
9237 desc->mEffect.clear();
9238 }
9239 mSuspendedEffects.removeItemsAt(index);
9240 }
9241 }
9242}
9243
9244// must be called with ThreadBase::mLock held
9245void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9246{
9247 sp<SuspendedEffectDesc> desc;
9248
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009249 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009250 if (suspend) {
9251 if (index >= 0) {
9252 desc = mSuspendedEffects.valueAt(index);
9253 } else {
9254 desc = new SuspendedEffectDesc();
9255 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009256 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009257 }
9258 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009259 Vector< sp<EffectModule> > effects;
9260 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009261 for (size_t i = 0; i < effects.size(); i++) {
9262 setEffectSuspended_l(&effects[i]->desc().type, true);
9263 }
9264 }
9265 } else {
9266 if (index < 0) {
9267 return;
9268 }
9269 desc = mSuspendedEffects.valueAt(index);
9270 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009271 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009272 desc->mRefCount = 1;
9273 }
9274 if (--desc->mRefCount == 0) {
9275 Vector<const effect_uuid_t *> types;
9276 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9277 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9278 continue;
9279 }
9280 types.add(&mSuspendedEffects.valueAt(i)->mType);
9281 }
9282 for (size_t i = 0; i < types.size(); i++) {
9283 setEffectSuspended_l(types[i], false);
9284 }
Steve Block3856b092011-10-20 11:56:00 +01009285 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009286 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9287 }
9288 }
9289}
9290
Eric Laurent6bffdb82011-09-23 08:40:41 -07009291
9292// The volume effect is used for automated tests only
9293#ifndef OPENSL_ES_H_
9294static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9295 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9296const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9297#endif //OPENSL_ES_H_
9298
Eric Laurentdb7c0792011-08-10 10:37:50 -07009299bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9300{
9301 // auxiliary effects and visualizer are never suspended on output mix
9302 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9303 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009304 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9305 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009306 return false;
9307 }
9308 return true;
9309}
9310
Glenn Kastend0539712012-01-30 12:56:03 -08009311void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009312{
Glenn Kastend0539712012-01-30 12:56:03 -08009313 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009314 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009315 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9316 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009317 }
Eric Laurent59255e42011-07-27 19:49:51 -07009318 }
Eric Laurent59255e42011-07-27 19:49:51 -07009319}
9320
9321sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9322 const effect_uuid_t *type)
9323{
Glenn Kasten090f0192012-01-30 13:00:02 -08009324 sp<EffectModule> effect = getEffectFromType_l(type);
9325 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009326}
9327
9328void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9329 bool enabled)
9330{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009331 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009332 if (enabled) {
9333 if (index < 0) {
9334 // if the effect is not suspend check if all effects are suspended
9335 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9336 if (index < 0) {
9337 return;
9338 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009339 if (!isEffectEligibleForSuspend(effect->desc())) {
9340 return;
9341 }
Eric Laurent59255e42011-07-27 19:49:51 -07009342 setEffectSuspended_l(&effect->desc().type, enabled);
9343 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009344 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009345 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009346 return;
9347 }
Eric Laurent59255e42011-07-27 19:49:51 -07009348 }
Steve Block3856b092011-10-20 11:56:00 +01009349 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009350 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009351 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9352 // if effect is requested to suspended but was not yet enabled, supend it now.
9353 if (desc->mEffect == 0) {
9354 desc->mEffect = effect;
9355 effect->setEnabled(false);
9356 effect->setSuspended(true);
9357 }
9358 } else {
9359 if (index < 0) {
9360 return;
9361 }
Steve Block3856b092011-10-20 11:56:00 +01009362 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009363 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009364 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9365 desc->mEffect.clear();
9366 effect->setSuspended(false);
9367 }
9368}
9369
Mathias Agopian65ab4712010-07-14 17:59:35 -07009370#undef LOG_TAG
9371#define LOG_TAG "AudioFlinger"
9372
9373// ----------------------------------------------------------------------------
9374
9375status_t AudioFlinger::onTransact(
9376 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9377{
9378 return BnAudioFlinger::onTransact(code, data, reply, flags);
9379}
9380
Mathias Agopian65ab4712010-07-14 17:59:35 -07009381}; // namespace android