blob: 5acf29a5a8e2d99235af19b18322afbc785d8e15 [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
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139// ----------------------------------------------------------------------------
2140
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002141AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002142 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002143 : PlaybackThread(audioFlinger, output, id, device, type),
2144 // mAudioMixer below
2145#ifdef SOAKER
2146 mSoaker(NULL),
2147#endif
2148 // mFastMixer below
2149 mFastMixerFutex(0)
2150 // mOutputSink below
2151 // mPipeSink below
2152 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153{
Glenn Kasten58912562012-04-03 10:45:00 -07002154 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2155 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2156 "mFrameCount=%d, mNormalFrameCount=%d",
2157 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2158 mNormalFrameCount);
2159 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2160
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 // FIXME - Current mixer implementation only supports stereo output
2162 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002163 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 }
Glenn Kasten58912562012-04-03 10:45:00 -07002165
2166 // create an NBAIO sink for the HAL output stream, and negotiate
2167 mOutputSink = new AudioStreamOutSink(output->stream);
2168 size_t numCounterOffers = 0;
2169 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2170 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2171 ALOG_ASSERT(index == 0);
2172
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002173 // initialize fast mixer depending on configuration
2174 bool initFastMixer;
2175 switch (kUseFastMixer) {
2176 case FastMixer_Never:
2177 initFastMixer = false;
2178 break;
2179 case FastMixer_Always:
2180 initFastMixer = true;
2181 break;
2182 case FastMixer_Static:
2183 case FastMixer_Dynamic:
2184 initFastMixer = mFrameCount < mNormalFrameCount;
2185 break;
2186 }
2187 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002188
2189 // create a MonoPipe to connect our submix to FastMixer
2190 NBAIO_Format format = mOutputSink->format();
2191 // frame count will be rounded up to a power of 2, so this formula should work well
2192 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2193 true /*writeCanBlock*/);
2194 const NBAIO_Format offers[1] = {format};
2195 size_t numCounterOffers = 0;
2196 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2197 ALOG_ASSERT(index == 0);
2198 mPipeSink = monoPipe;
2199
2200#ifdef SOAKER
2201 // create a soaker as workaround for governor issues
2202 mSoaker = new Soaker();
2203 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2204 mSoaker->run("Soaker", PRIORITY_LOWEST);
2205#endif
2206
2207 // create fast mixer and configure it initially with just one fast track for our submix
2208 mFastMixer = new FastMixer();
2209 FastMixerStateQueue *sq = mFastMixer->sq();
2210 FastMixerState *state = sq->begin();
2211 FastTrack *fastTrack = &state->mFastTracks[0];
2212 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2213 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2214 fastTrack->mVolumeProvider = NULL;
2215 fastTrack->mGeneration++;
2216 state->mFastTracksGen++;
2217 state->mTrackMask = 1;
2218 // fast mixer will use the HAL output sink
2219 state->mOutputSink = mOutputSink.get();
2220 state->mOutputSinkGen++;
2221 state->mFrameCount = mFrameCount;
2222 state->mCommand = FastMixerState::COLD_IDLE;
2223 // already done in constructor initialization list
2224 //mFastMixerFutex = 0;
2225 state->mColdFutexAddr = &mFastMixerFutex;
2226 state->mColdGen++;
2227 state->mDumpState = &mFastMixerDumpState;
2228 sq->end();
2229 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2230
2231 // start the fast mixer
2232 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2233#ifdef HAVE_REQUEST_PRIORITY
2234 pid_t tid = mFastMixer->getTid();
2235 int err = requestPriority(getpid_cached, tid, 2);
2236 if (err != 0) {
2237 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2238 2, getpid_cached, tid, err);
2239 }
2240#endif
2241
2242 } else {
2243 mFastMixer = NULL;
2244 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002245
2246 switch (kUseFastMixer) {
2247 case FastMixer_Never:
2248 case FastMixer_Dynamic:
2249 mNormalSink = mOutputSink;
2250 break;
2251 case FastMixer_Always:
2252 mNormalSink = mPipeSink;
2253 break;
2254 case FastMixer_Static:
2255 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2256 break;
2257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258}
2259
2260AudioFlinger::MixerThread::~MixerThread()
2261{
Glenn Kasten58912562012-04-03 10:45:00 -07002262 if (mFastMixer != NULL) {
2263 FastMixerStateQueue *sq = mFastMixer->sq();
2264 FastMixerState *state = sq->begin();
2265 if (state->mCommand == FastMixerState::COLD_IDLE) {
2266 int32_t old = android_atomic_inc(&mFastMixerFutex);
2267 if (old == -1) {
2268 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2269 }
2270 }
2271 state->mCommand = FastMixerState::EXIT;
2272 sq->end();
2273 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2274 mFastMixer->join();
2275 // Though the fast mixer thread has exited, it's state queue is still valid.
2276 // We'll use that extract the final state which contains one remaining fast track
2277 // corresponding to our sub-mix.
2278 state = sq->begin();
2279 ALOG_ASSERT(state->mTrackMask == 1);
2280 FastTrack *fastTrack = &state->mFastTracks[0];
2281 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2282 delete fastTrack->mBufferProvider;
2283 sq->end(false /*didModify*/);
2284 delete mFastMixer;
2285#ifdef SOAKER
2286 if (mSoaker != NULL) {
2287 mSoaker->requestExitAndWait();
2288 }
2289 delete mSoaker;
2290#endif
2291 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 delete mAudioMixer;
2293}
2294
Glenn Kasten83efdd02012-02-24 07:21:32 -08002295class CpuStats {
2296public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002297 CpuStats();
2298 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002299#ifdef DEBUG_CPU_USAGE
2300private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002301 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2302 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2303
2304 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2305
2306 int mCpuNum; // thread's current CPU number
2307 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002308#endif
2309};
2310
Glenn Kasten190a46f2012-03-06 11:27:10 -08002311CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002312#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002313 : mCpuNum(-1), mCpukHz(-1)
2314#endif
2315{
2316}
2317
2318void CpuStats::sample(const String8 &title) {
2319#ifdef DEBUG_CPU_USAGE
2320 // get current thread's delta CPU time in wall clock ns
2321 double wcNs;
2322 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2323
2324 // record sample for wall clock statistics
2325 if (valid) {
2326 mWcStats.sample(wcNs);
2327 }
2328
2329 // get the current CPU number
2330 int cpuNum = sched_getcpu();
2331
2332 // get the current CPU frequency in kHz
2333 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2334
2335 // check if either CPU number or frequency changed
2336 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2337 mCpuNum = cpuNum;
2338 mCpukHz = cpukHz;
2339 // ignore sample for purposes of cycles
2340 valid = false;
2341 }
2342
2343 // if no change in CPU number or frequency, then record sample for cycle statistics
2344 if (valid && mCpukHz > 0) {
2345 double cycles = wcNs * cpukHz * 0.000001;
2346 mHzStats.sample(cycles);
2347 }
2348
2349 unsigned n = mWcStats.n();
2350 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002351 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002352 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002353 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2354 double perLoop = elapsed / (double) n;
2355 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002356 double perLoop1k = perLoop * 0.001;
2357 double mean = mWcStats.mean();
2358 double stddev = mWcStats.stddev();
2359 double minimum = mWcStats.minimum();
2360 double maximum = mWcStats.maximum();
2361 double meanCycles = mHzStats.mean();
2362 double stddevCycles = mHzStats.stddev();
2363 double minCycles = mHzStats.minimum();
2364 double maxCycles = mHzStats.maximum();
2365 mCpuUsage.resetElapsed();
2366 mWcStats.reset();
2367 mHzStats.reset();
2368 ALOGD("CPU usage for %s over past %.1f secs\n"
2369 " (%u mixer loops at %.1f mean ms per loop):\n"
2370 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2371 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2372 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2373 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002374 elapsed * .000000001, n, perLoop * .000001,
2375 mean * .001,
2376 stddev * .001,
2377 minimum * .001,
2378 maximum * .001,
2379 mean / perLoop100,
2380 stddev / perLoop100,
2381 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002382 maximum / perLoop100,
2383 meanCycles / perLoop1k,
2384 stddevCycles / perLoop1k,
2385 minCycles / perLoop1k,
2386 maxCycles / perLoop1k);
2387
Glenn Kasten83efdd02012-02-24 07:21:32 -08002388 }
2389 }
2390#endif
2391};
2392
Glenn Kasten37d825e2012-02-24 07:21:48 -08002393void AudioFlinger::PlaybackThread::checkSilentMode_l()
2394{
2395 if (!mMasterMute) {
2396 char value[PROPERTY_VALUE_MAX];
2397 if (property_get("ro.audio.silent", value, "0") > 0) {
2398 char *endptr;
2399 unsigned long ul = strtoul(value, &endptr, 0);
2400 if (*endptr == '\0' && ul != 0) {
2401 ALOGD("Silence is golden");
2402 // The setprop command will not allow a property to be changed after
2403 // the first time it is set, so we don't have to worry about un-muting.
2404 setMasterMute_l(true);
2405 }
2406 }
2407 }
2408}
2409
Glenn Kasten000f0e32012-03-01 17:10:56 -08002410bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411{
2412 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002413
Glenn Kasten000f0e32012-03-01 17:10:56 -08002414 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002415
2416 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002418if (mType == MIXER) {
2419 longStandbyExit = false;
2420}
Glenn Kasten688a6402012-02-29 07:57:06 -08002421
Glenn Kasten000f0e32012-03-01 17:10:56 -08002422 // DUPLICATING
2423 // FIXME could this be made local to while loop?
2424 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002425
Glenn Kasten66fcab92012-02-24 14:59:21 -08002426 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002427 sleepTime = idleSleepTime;
2428
2429if (mType == MIXER) {
2430 sleepTimeShift = 0;
2431}
2432
Glenn Kasten83efdd02012-02-24 07:21:32 -08002433 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002434 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435
Eric Laurentfeb0db62011-07-22 09:04:31 -07002436 acquireWakeLock();
2437
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 while (!exitPending())
2439 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002440 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002441
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002442 Vector< sp<EffectChain> > effectChains;
2443
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 processConfigEvents();
2445
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 { // scope for mLock
2447
2448 Mutex::Autolock _l(mLock);
2449
2450 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002451 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 }
2453
Glenn Kastenfa26a852012-03-06 11:28:04 -08002454 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002455
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002457 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002458 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002460
2461 threadLoop_standby();
2462
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463 mStandby = true;
2464 mBytesWritten = 0;
2465 }
2466
Glenn Kasten3e074702012-02-28 18:40:35 -08002467 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 // we're about to wait, flush the binder command buffer
2469 IPCThreadState::self()->flushCommands();
2470
Glenn Kastenfa26a852012-03-06 11:28:04 -08002471 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002472
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473 if (exitPending()) break;
2474
Eric Laurentfeb0db62011-07-22 09:04:31 -07002475 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002477 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002479 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002480 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481
Eric Laurentda747442012-04-25 18:53:13 -07002482 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002483 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002484
Glenn Kasten37d825e2012-02-24 07:21:48 -08002485 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486
Glenn Kasten000f0e32012-03-01 17:10:56 -08002487 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002489 if (mType == MIXER) {
2490 sleepTimeShift = 0;
2491 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002492
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 continue;
2494 }
2495 }
2496
Glenn Kasten81028042012-04-30 18:15:12 -07002497 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002498 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499
2500 // prevent any changes in effect chain list and in each effect chain
2501 // during mixing and effect process as the audio buffers could be deleted
2502 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002503 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505
Glenn Kastenfec279f2012-03-08 07:47:15 -08002506 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002507 threadLoop_mix();
2508 } else {
2509 threadLoop_sleepTime();
2510 }
2511
2512 if (mSuspended > 0) {
2513 sleepTime = suspendSleepTimeUs();
2514 }
2515
2516 // only process effects if we're going to write
2517 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002518 for (size_t i = 0; i < effectChains.size(); i ++) {
2519 effectChains[i]->process_l();
2520 }
2521 }
2522
2523 // enable changes in effect chain
2524 unlockEffectChains(effectChains);
2525
2526 // sleepTime == 0 means we must write to audio hardware
2527 if (sleepTime == 0) {
2528
2529 threadLoop_write();
2530
2531if (mType == MIXER) {
2532 // write blocked detection
2533 nsecs_t now = systemTime();
2534 nsecs_t delta = now - mLastWriteTime;
2535 if (!mStandby && delta > maxPeriod) {
2536 mNumDelayedWrites++;
2537 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002538 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten000f0e32012-03-01 17:10:56 -08002539 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2540 ns2ms(delta), mNumDelayedWrites, this);
2541 lastWarning = now;
2542 }
2543 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2544 // a different threshold. Or completely removed for what it is worth anyway...
2545 if (mStandby) {
2546 longStandbyExit = true;
2547 }
2548 }
2549}
2550
2551 mStandby = false;
2552 } else {
2553 usleep(sleepTime);
2554 }
2555
Glenn Kasten58912562012-04-03 10:45:00 -07002556 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002557 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002558 // same lock. This will also mutate and push a new fast mixer state.
2559 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002560 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002561
Glenn Kastenfa26a852012-03-06 11:28:04 -08002562 // FIXME I don't understand the need for this here;
2563 // it was in the original code but maybe the
2564 // assignment in saveOutputTracks() makes this unnecessary?
2565 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002566
2567 // Effect chains will be actually deleted here if they were removed from
2568 // mEffectChains list during mixing or effects processing
2569 effectChains.clear();
2570
2571 // FIXME Note that the above .clear() is no longer necessary since effectChains
2572 // is now local to this block, but will keep it for now (at least until merge done).
2573 }
2574
2575if (mType == MIXER || mType == DIRECT) {
2576 // put output stream into standby mode
2577 if (!mStandby) {
2578 mOutput->stream->common.standby(&mOutput->stream->common);
2579 }
2580}
2581if (mType == DUPLICATING) {
2582 // for DuplicatingThread, standby mode is handled by the outputTracks
2583}
2584
2585 releaseWakeLock();
2586
2587 ALOGV("Thread %p type %d exiting", this, mType);
2588 return false;
2589}
2590
Glenn Kasten288ed212012-04-25 17:52:27 -07002591// returns (via tracksToRemove) a set of tracks to remove.
Glenn Kasten58912562012-04-03 10:45:00 -07002592void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2593{
Glenn Kasten58912562012-04-03 10:45:00 -07002594 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2595}
2596
2597void AudioFlinger::MixerThread::threadLoop_write()
2598{
2599 // FIXME we should only do one push per cycle; confirm this is true
2600 // Start the fast mixer if it's not already running
2601 if (mFastMixer != NULL) {
2602 FastMixerStateQueue *sq = mFastMixer->sq();
2603 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002604 if (state->mCommand != FastMixerState::MIX_WRITE &&
2605 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002606 if (state->mCommand == FastMixerState::COLD_IDLE) {
2607 int32_t old = android_atomic_inc(&mFastMixerFutex);
2608 if (old == -1) {
2609 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2610 }
2611 }
2612 state->mCommand = FastMixerState::MIX_WRITE;
2613 sq->end();
2614 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002615 if (kUseFastMixer == FastMixer_Dynamic) {
2616 mNormalSink = mPipeSink;
2617 }
Glenn Kasten58912562012-04-03 10:45:00 -07002618 } else {
2619 sq->end(false /*didModify*/);
2620 }
2621 }
2622 PlaybackThread::threadLoop_write();
2623}
2624
Glenn Kasten000f0e32012-03-01 17:10:56 -08002625// shared by MIXER and DIRECT, overridden by DUPLICATING
2626void AudioFlinger::PlaybackThread::threadLoop_write()
2627{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002628 // FIXME rewrite to reduce number of system calls
2629 mLastWriteTime = systemTime();
2630 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002631
Glenn Kasten58912562012-04-03 10:45:00 -07002632#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002633 size_t count = mixBufferSize >> mBitShift;
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002634 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002635 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002636 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002637 if (framesWritten > 0) {
2638 size_t bytesWritten = framesWritten << mBitShift;
2639 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002640 }
2641
Glenn Kasten952eeb22012-03-06 11:30:57 -08002642 mNumWrites++;
2643 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002644}
2645
Glenn Kasten58912562012-04-03 10:45:00 -07002646void AudioFlinger::MixerThread::threadLoop_standby()
2647{
2648 // Idle the fast mixer if it's currently running
2649 if (mFastMixer != NULL) {
2650 FastMixerStateQueue *sq = mFastMixer->sq();
2651 FastMixerState *state = sq->begin();
2652 if (!(state->mCommand & FastMixerState::IDLE)) {
2653 state->mCommand = FastMixerState::COLD_IDLE;
2654 state->mColdFutexAddr = &mFastMixerFutex;
2655 state->mColdGen++;
2656 mFastMixerFutex = 0;
2657 sq->end();
2658 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2659 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002660 if (kUseFastMixer == FastMixer_Dynamic) {
2661 mNormalSink = mOutputSink;
2662 }
Glenn Kasten58912562012-04-03 10:45:00 -07002663 } else {
2664 sq->end(false /*didModify*/);
2665 }
2666 }
2667 PlaybackThread::threadLoop_standby();
2668}
2669
Glenn Kasten000f0e32012-03-01 17:10:56 -08002670// shared by MIXER and DIRECT, overridden by DUPLICATING
2671void AudioFlinger::PlaybackThread::threadLoop_standby()
2672{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002673 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2674 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002675}
2676
2677void AudioFlinger::MixerThread::threadLoop_mix()
2678{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002679 // obtain the presentation timestamp of the next output buffer
2680 int64_t pts;
2681 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002682
Glenn Kasten952eeb22012-03-06 11:30:57 -08002683 if (NULL != mOutput->stream->get_next_write_timestamp) {
2684 status = mOutput->stream->get_next_write_timestamp(
2685 mOutput->stream, &pts);
2686 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002687
Glenn Kasten952eeb22012-03-06 11:30:57 -08002688 if (status != NO_ERROR) {
2689 pts = AudioBufferProvider::kInvalidPTS;
2690 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002691
Glenn Kasten952eeb22012-03-06 11:30:57 -08002692 // mix buffers...
2693 mAudioMixer->process(pts);
2694 // increase sleep time progressively when application underrun condition clears.
2695 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2696 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2697 // such that we would underrun the audio HAL.
2698 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2699 sleepTimeShift--;
2700 }
2701 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002702 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002703 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002704}
2705
2706void AudioFlinger::MixerThread::threadLoop_sleepTime()
2707{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002708 // If no tracks are ready, sleep once for the duration of an output
2709 // buffer size, then write 0s to the output
2710 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002711 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002712 sleepTime = activeSleepTime >> sleepTimeShift;
2713 if (sleepTime < kMinThreadSleepTimeUs) {
2714 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002716 // reduce sleep time in case of consecutive application underruns to avoid
2717 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2718 // duration we would end up writing less data than needed by the audio HAL if
2719 // the condition persists.
2720 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2721 sleepTimeShift++;
2722 }
2723 } else {
2724 sleepTime = idleSleepTime;
2725 }
2726 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002727 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002728 memset (mMixBuffer, 0, mixBufferSize);
2729 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002730 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002731 }
2732 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733}
2734
2735// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002736AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002737 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738{
2739
Glenn Kasten29c23c32012-01-26 13:37:52 -08002740 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002742 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 size_t mixedTracks = 0;
2744 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002745 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002746 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002747 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748
2749 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002750 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751
Eric Laurent571d49c2010-08-11 05:20:11 -07002752 if (masterMute) {
2753 masterVolume = 0;
2754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002756 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002758 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002759 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 masterVolume = (float)((v + (1 << 23)) >> 24);
2761 chain.clear();
2762 }
2763
Glenn Kasten288ed212012-04-25 17:52:27 -07002764 // prepare a new state to push
2765 FastMixerStateQueue *sq = NULL;
2766 FastMixerState *state = NULL;
2767 bool didModify = false;
2768 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2769 if (mFastMixer != NULL) {
2770 sq = mFastMixer->sq();
2771 state = sq->begin();
2772 }
2773
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002775 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776 if (t == 0) continue;
2777
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002778 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002780
Glenn Kasten288ed212012-04-25 17:52:27 -07002781 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002782 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002783
2784 // It's theoretically possible (though unlikely) for a fast track to be created
2785 // and then removed within the same normal mix cycle. This is not a problem, as
2786 // the track never becomes active so it's fast mixer slot is never touched.
2787 // The converse, of removing an (active) track and then creating a new track
2788 // at the identical fast mixer slot within the same normal mix cycle,
2789 // is impossible because the slot isn't marked available until the end of each cycle.
2790 int j = track->mFastIndex;
2791 FastTrack *fastTrack = &state->mFastTracks[j];
2792
2793 // Determine whether the track is currently in underrun condition,
2794 // and whether it had a recent underrun.
Glenn Kasten09474df2012-05-10 14:48:07 -07002795 FastTrackUnderruns underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2796 uint32_t recentFull = (underruns.mBitFields.mFull -
2797 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2798 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2799 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2800 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2801 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2802 uint32_t recentUnderruns = recentPartial + recentEmpty;
2803 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002804 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002805 // or stopped which can occur when flush() is called while active
2806 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002807 track->mUnderrunCount += recentUnderruns;
2808 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002809
Glenn Kastend08f48c2012-05-01 18:14:02 -07002810 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002811 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002812 bool isActive = true;
2813 switch (track->mState) {
2814 case TrackBase::STOPPING_1:
2815 // track stays active in STOPPING_1 state until first underrun
2816 if (recentUnderruns > 0) {
2817 track->mState = TrackBase::STOPPING_2;
2818 }
2819 break;
2820 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002821 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002822 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002823 break;
2824 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002825 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002826 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002827 break;
2828 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002829 if (recentFull > 0 || recentPartial > 0) {
2830 // track has provided at least some frames recently: reset retry count
2831 track->mRetryCount = kMaxTrackRetries;
2832 }
2833 if (recentUnderruns == 0) {
2834 // no recent underruns: stay active
2835 break;
2836 }
2837 // there has recently been an underrun of some kind
2838 if (track->sharedBuffer() == 0) {
2839 // were any of the recent underruns "empty" (no frames available)?
2840 if (recentEmpty == 0) {
2841 // no, then ignore the partial underruns as they are allowed indefinitely
2842 break;
2843 }
2844 // there has recently been an "empty" underrun: decrement the retry counter
2845 if (--(track->mRetryCount) > 0) {
2846 break;
2847 }
2848 // indicate to client process that the track was disabled because of underrun;
2849 // it will then automatically call start() when data is available
2850 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2851 // remove from active list, but state remains ACTIVE [confusing but true]
2852 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002853 break;
2854 }
2855 // fall through
2856 case TrackBase::STOPPING_2:
2857 case TrackBase::PAUSED:
2858 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002859 case TrackBase::STOPPED:
2860 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002861 // Check for presentation complete if track is inactive
2862 // We have consumed all the buffers of this track.
2863 // This would be incomplete if we auto-paused on underrun
2864 {
2865 size_t audioHALFrames =
2866 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2867 size_t framesWritten =
2868 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2869 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2870 // track stays in active list until presentation is complete
2871 break;
2872 }
2873 }
2874 if (track->isStopping_2()) {
2875 track->mState = TrackBase::STOPPED;
2876 }
2877 if (track->isStopped()) {
2878 // Can't reset directly, as fast mixer is still polling this track
2879 // track->reset();
2880 // So instead mark this track as needing to be reset after push with ack
2881 resetMask |= 1 << i;
2882 }
2883 isActive = false;
2884 break;
2885 case TrackBase::IDLE:
2886 default:
2887 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002888 }
2889
2890 if (isActive) {
2891 // was it previously inactive?
2892 if (!(state->mTrackMask & (1 << j))) {
2893 ExtendedAudioBufferProvider *eabp = track;
2894 VolumeProvider *vp = track;
2895 fastTrack->mBufferProvider = eabp;
2896 fastTrack->mVolumeProvider = vp;
2897 fastTrack->mSampleRate = track->mSampleRate;
2898 fastTrack->mChannelMask = track->mChannelMask;
2899 fastTrack->mGeneration++;
2900 state->mTrackMask |= 1 << j;
2901 didModify = true;
2902 // no acknowledgement required for newly active tracks
2903 }
2904 // cache the combined master volume and stream type volume for fast mixer; this
2905 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2906 track->mCachedVolume = track->isMuted() ?
2907 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2908 ++fastTracks;
2909 } else {
2910 // was it previously active?
2911 if (state->mTrackMask & (1 << j)) {
2912 fastTrack->mBufferProvider = NULL;
2913 fastTrack->mGeneration++;
2914 state->mTrackMask &= ~(1 << j);
2915 didModify = true;
2916 // If any fast tracks were removed, we must wait for acknowledgement
2917 // because we're about to decrement the last sp<> on those tracks.
2918 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002919 } else {
2920 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002921 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002922 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002923 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07002924 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002925 }
2926 continue;
2927 }
2928
2929 { // local variable scope to avoid goto warning
2930
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 audio_track_cblk_t* cblk = track->cblk();
2932
2933 // The first time a track is added we wait
2934 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002935 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002936 // make sure that we have enough frames to mix one full buffer.
2937 // enforce this condition only once to enable draining the buffer in case the client
2938 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002939 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002940 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002941 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002942 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002943 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002944 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002945 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002946 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002947 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002948 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002949 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002950 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002951 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2952 // the minimum track buffer size is normally twice the number of frames necessary
2953 // to fill one buffer and the resampler should not leave more than one buffer worth
2954 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002955 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002956 }
2957 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002958 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959 !track->isPaused() && !track->isTerminated())
2960 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002961 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962
2963 mixedTracks++;
2964
2965 // track->mainBuffer() != mMixBuffer means there is an effect chain
2966 // connected to the track
2967 chain.clear();
2968 if (track->mainBuffer() != mMixBuffer) {
2969 chain = getEffectChain_l(track->sessionId());
2970 // Delegate volume control to effect in track effect chain if needed
2971 if (chain != 0) {
2972 tracksWithEffect++;
2973 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002974 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002975 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976 }
2977 }
2978
2979
2980 int param = AudioMixer::VOLUME;
2981 if (track->mFillingUpStatus == Track::FS_FILLED) {
2982 // no ramp for the first volume setting
2983 track->mFillingUpStatus = Track::FS_ACTIVE;
2984 if (track->mState == TrackBase::RESUMING) {
2985 track->mState = TrackBase::ACTIVE;
2986 param = AudioMixer::RAMP_VOLUME;
2987 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002988 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989 } else if (cblk->server != 0) {
2990 // If the track is stopped before the first frame was mixed,
2991 // do not apply ramp
2992 param = AudioMixer::RAMP_VOLUME;
2993 }
2994
2995 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002996 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002997 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002998 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002999 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000 if (track->isPausing()) {
3001 track->setPaused();
3002 }
3003 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003004
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003006 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003008 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003009 vl = vlr & 0xFFFF;
3010 vr = vlr >> 16;
3011 // track volumes come from shared memory, so can't be trusted and must be clamped
3012 if (vl > MAX_GAIN_INT) {
3013 ALOGV("Track left volume out of range: %04X", vl);
3014 vl = MAX_GAIN_INT;
3015 }
3016 if (vr > MAX_GAIN_INT) {
3017 ALOGV("Track right volume out of range: %04X", vr);
3018 vr = MAX_GAIN_INT;
3019 }
3020 // now apply the master volume and stream type volume
3021 vl = (uint32_t)(v * vl) << 12;
3022 vr = (uint32_t)(v * vr) << 12;
3023 // assuming master volume and stream type volume each go up to 1.0,
3024 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025
Glenn Kasten05632a52012-01-03 14:22:33 -08003026 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3027 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003028 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003029 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003030 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003031 }
3032 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003034 // Delegate volume control to effect in track effect chain if needed
3035 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3036 // Do not ramp volume if volume is controlled by effect
3037 param = AudioMixer::VOLUME;
3038 track->mHasVolumeController = true;
3039 } else {
3040 // force no volume ramp when volume controller was just disabled or removed
3041 // from effect chain to avoid volume spike
3042 if (track->mHasVolumeController) {
3043 param = AudioMixer::VOLUME;
3044 }
3045 track->mHasVolumeController = false;
3046 }
3047
3048 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003049 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003050 vl = (vl + (1 << 11)) >> 12;
3051 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3052 vr = (vr + (1 << 11)) >> 12;
3053 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003054
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003055 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 -07003056
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003058 mAudioMixer->setBufferProvider(name, track);
3059 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003061 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3062 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3063 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003065 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 AudioMixer::TRACK,
3067 AudioMixer::FORMAT, (void *)track->format());
3068 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003069 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003071 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003073 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074 AudioMixer::RESAMPLE,
3075 AudioMixer::SAMPLE_RATE,
3076 (void *)(cblk->sampleRate));
3077 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003078 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003079 AudioMixer::TRACK,
3080 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3081 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003082 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 AudioMixer::TRACK,
3084 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3085
3086 // reset retry count
3087 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003088
Eric Laurent27741442012-01-17 19:20:12 -08003089 // If one track is ready, set the mixer ready if:
3090 // - the mixer was not ready during previous round OR
3091 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003092 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003093 mixerStatus != MIXER_TRACKS_ENABLED) {
3094 mixerStatus = MIXER_TRACKS_READY;
3095 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003097 //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 -07003098 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3099 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003100 // We have consumed all the buffers of this track.
3101 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003102 // TODO: use actual buffer filling status instead of latency when available from
3103 // audio HAL
3104 size_t audioHALFrames =
3105 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3106 size_t framesWritten =
3107 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3108 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003109 if (track->isStopped()) {
3110 track->reset();
3111 }
Eric Laurenta011e352012-03-29 15:51:43 -07003112 tracksToRemove->add(track);
3113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114 } else {
3115 // No buffers for this track. Give it a few chances to
3116 // fill a buffer, then remove it from active list.
3117 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003118 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003120 // indicate to client process that the track was disabled because of underrun;
3121 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003122 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003123 // If one track is not ready, mark the mixer also not ready if:
3124 // - the mixer was ready during previous round OR
3125 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003126 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003127 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128 mixerStatus = MIXER_TRACKS_ENABLED;
3129 }
3130 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003131 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 }
Glenn Kasten58912562012-04-03 10:45:00 -07003133
3134 } // local variable scope to avoid goto warning
3135track_is_ready: ;
3136
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137 }
3138
Glenn Kasten288ed212012-04-25 17:52:27 -07003139 // Push the new FastMixer state if necessary
3140 if (didModify) {
3141 state->mFastTracksGen++;
3142 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3143 if (kUseFastMixer == FastMixer_Dynamic &&
3144 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3145 state->mCommand = FastMixerState::COLD_IDLE;
3146 state->mColdFutexAddr = &mFastMixerFutex;
3147 state->mColdGen++;
3148 mFastMixerFutex = 0;
3149 if (kUseFastMixer == FastMixer_Dynamic) {
3150 mNormalSink = mOutputSink;
3151 }
3152 // If we go into cold idle, need to wait for acknowledgement
3153 // so that fast mixer stops doing I/O.
3154 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3155 }
3156 sq->end();
3157 }
3158 if (sq != NULL) {
3159 sq->end(didModify);
3160 sq->push(block);
3161 }
3162
3163 // Now perform the deferred reset on fast tracks that have stopped
3164 while (resetMask != 0) {
3165 size_t i = __builtin_ctz(resetMask);
3166 ALOG_ASSERT(i < count);
3167 resetMask &= ~(1 << i);
3168 sp<Track> t = mActiveTracks[i].promote();
3169 if (t == 0) continue;
3170 Track* track = t.get();
3171 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3172 track->reset();
3173 }
Glenn Kasten58912562012-04-03 10:45:00 -07003174
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 // remove all the tracks that need to be...
3176 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003177 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178 for (size_t i=0 ; i<count ; i++) {
3179 const sp<Track>& track = tracksToRemove->itemAt(i);
3180 mActiveTracks.remove(track);
3181 if (track->mainBuffer() != mMixBuffer) {
3182 chain = getEffectChain_l(track->sessionId());
3183 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003184 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003185 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 }
3187 }
3188 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003189 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 }
3191 }
3192 }
3193
3194 // mix buffer must be cleared if all tracks are connected to an
3195 // effect chain as in this case the mixer will not write to
3196 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003197 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3198 // FIXME as a performance optimization, should remember previous zero status
3199 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 }
3201
Glenn Kasten58912562012-04-03 10:45:00 -07003202 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003203 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003204 if (fastTracks > 0) {
3205 mixerStatus = MIXER_TRACKS_READY;
3206 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 return mixerStatus;
3208}
3209
Glenn Kasten66fcab92012-02-24 14:59:21 -08003210/*
3211The derived values that are cached:
3212 - mixBufferSize from frame count * frame size
3213 - activeSleepTime from activeSleepTimeUs()
3214 - idleSleepTime from idleSleepTimeUs()
3215 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3216 - maxPeriod from frame count and sample rate (MIXER only)
3217
3218The parameters that affect these derived values are:
3219 - frame count
3220 - frame size
3221 - sample rate
3222 - device type: A2DP or not
3223 - device latency
3224 - format: PCM or not
3225 - active sleep time
3226 - idle sleep time
3227*/
3228
3229void AudioFlinger::PlaybackThread::cacheParameters_l()
3230{
Glenn Kasten58912562012-04-03 10:45:00 -07003231 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003232 activeSleepTime = activeSleepTimeUs();
3233 idleSleepTime = idleSleepTimeUs();
3234}
3235
Glenn Kastenfff6d712012-01-12 16:38:12 -08003236void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237{
Steve Block3856b092011-10-20 11:56:00 +01003238 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003239 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003241
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 size_t size = mTracks.size();
3243 for (size_t i = 0; i < size; i++) {
3244 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003245 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003246 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 }
3249 }
3250}
3251
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003253int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003255 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256}
3257
3258// deleteTrackName_l() must be called with ThreadBase::mLock held
3259void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3260{
Steve Block3856b092011-10-20 11:56:00 +01003261 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 mAudioMixer->deleteTrackName(name);
3263}
3264
3265// checkForNewParameters_l() must be called with ThreadBase::mLock held
3266bool AudioFlinger::MixerThread::checkForNewParameters_l()
3267{
Glenn Kasten58912562012-04-03 10:45:00 -07003268 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3269 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 bool reconfig = false;
3271
3272 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003273
3274 if (mFastMixer != NULL) {
3275 FastMixerStateQueue *sq = mFastMixer->sq();
3276 FastMixerState *state = sq->begin();
3277 if (!(state->mCommand & FastMixerState::IDLE)) {
3278 previousCommand = state->mCommand;
3279 state->mCommand = FastMixerState::HOT_IDLE;
3280 sq->end();
3281 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3282 } else {
3283 sq->end(false /*didModify*/);
3284 }
3285 }
3286
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 status_t status = NO_ERROR;
3288 String8 keyValuePair = mNewParameters[0];
3289 AudioParameter param = AudioParameter(keyValuePair);
3290 int value;
3291
3292 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3293 reconfig = true;
3294 }
3295 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003296 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 status = BAD_VALUE;
3298 } else {
3299 reconfig = true;
3300 }
3301 }
3302 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003303 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 status = BAD_VALUE;
3305 } else {
3306 reconfig = true;
3307 }
3308 }
3309 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3310 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003311 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 // if frame count is changed after track creation
3313 if (!mTracks.isEmpty()) {
3314 status = INVALID_OPERATION;
3315 } else {
3316 reconfig = true;
3317 }
3318 }
3319 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003320#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003321 // when changing the audio output device, call addBatteryData to notify
3322 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003323 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003324 uint32_t params = 0;
3325 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003326 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003327 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3328 }
3329
3330 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003331 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003332 // check if any other device (except speaker) is on
3333 if (value & deviceWithoutSpeaker ) {
3334 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3335 }
3336
3337 if (params != 0) {
3338 addBatteryData(params);
3339 }
3340 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003341#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003342
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 // forward device change to effects that have requested to be
3344 // aware of attached audio device.
3345 mDevice = (uint32_t)value;
3346 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003347 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 }
3349 }
3350
3351 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003352 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003353 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003355 mOutput->stream->common.standby(&mOutput->stream->common);
3356 mStandby = true;
3357 mBytesWritten = 0;
3358 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003359 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360 }
3361 if (status == NO_ERROR && reconfig) {
3362 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003363 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3364 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003366 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003368 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 if (name < 0) break;
3370 mTracks[i]->mName = name;
3371 // limit track sample rate to 2 x new output sample rate
3372 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3373 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3374 }
3375 }
3376 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3377 }
3378 }
3379
3380 mNewParameters.removeAt(0);
3381
3382 mParamStatus = status;
3383 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003384 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3385 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003386 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 }
Glenn Kasten58912562012-04-03 10:45:00 -07003388
3389 if (!(previousCommand & FastMixerState::IDLE)) {
3390 ALOG_ASSERT(mFastMixer != NULL);
3391 FastMixerStateQueue *sq = mFastMixer->sq();
3392 FastMixerState *state = sq->begin();
3393 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3394 state->mCommand = previousCommand;
3395 sq->end();
3396 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3397 }
3398
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 return reconfig;
3400}
3401
3402status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3403{
3404 const size_t SIZE = 256;
3405 char buffer[SIZE];
3406 String8 result;
3407
3408 PlaybackThread::dumpInternals(fd, args);
3409
3410 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3411 result.append(buffer);
3412 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003413
3414 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3415 FastMixerDumpState copy = mFastMixerDumpState;
3416 copy.dump(fd);
3417
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 return NO_ERROR;
3419}
3420
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003421uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422{
Glenn Kasten58912562012-04-03 10:45:00 -07003423 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424}
3425
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003426uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003427{
Glenn Kasten58912562012-04-03 10:45:00 -07003428 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003429}
3430
Glenn Kasten66fcab92012-02-24 14:59:21 -08003431void AudioFlinger::MixerThread::cacheParameters_l()
3432{
3433 PlaybackThread::cacheParameters_l();
3434
3435 // FIXME: Relaxed timing because of a certain device that can't meet latency
3436 // Should be reduced to 2x after the vendor fixes the driver issue
3437 // increase threshold again due to low power audio mode. The way this warning
3438 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003439 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003440}
3441
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003443AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3444 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003445 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003446 // mLeftVolFloat, mRightVolFloat
3447 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449}
3450
3451AudioFlinger::DirectOutputThread::~DirectOutputThread()
3452{
3453}
3454
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003455AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3456 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003457)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003459 sp<Track> trackToRemove;
3460
Glenn Kastenfec279f2012-03-08 07:47:15 -08003461 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462
Glenn Kasten952eeb22012-03-06 11:30:57 -08003463 // find out which tracks need to be processed
3464 if (mActiveTracks.size() != 0) {
3465 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003466 // The track died recently
3467 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468
Glenn Kasten952eeb22012-03-06 11:30:57 -08003469 Track* const track = t.get();
3470 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471
Glenn Kasten952eeb22012-03-06 11:30:57 -08003472 // The first time a track is added we wait
3473 // for all its buffers to be filled before processing it
3474 if (cblk->framesReady() && track->isReady() &&
3475 !track->isPaused() && !track->isTerminated())
3476 {
3477 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478
Glenn Kasten952eeb22012-03-06 11:30:57 -08003479 if (track->mFillingUpStatus == Track::FS_FILLED) {
3480 track->mFillingUpStatus = Track::FS_ACTIVE;
3481 mLeftVolFloat = mRightVolFloat = 0;
3482 mLeftVolShort = mRightVolShort = 0;
3483 if (track->mState == TrackBase::RESUMING) {
3484 track->mState = TrackBase::ACTIVE;
3485 rampVolume = true;
3486 }
3487 } else if (cblk->server != 0) {
3488 // If the track is stopped before the first frame was mixed,
3489 // do not apply ramp
3490 rampVolume = true;
3491 }
3492 // compute volume for this track
3493 float left, right;
3494 if (track->isMuted() || mMasterMute || track->isPausing() ||
3495 mStreamTypes[track->streamType()].mute) {
3496 left = right = 0;
3497 if (track->isPausing()) {
3498 track->setPaused();
3499 }
3500 } else {
3501 float typeVolume = mStreamTypes[track->streamType()].volume;
3502 float v = mMasterVolume * typeVolume;
3503 uint32_t vlr = cblk->getVolumeLR();
3504 float v_clamped = v * (vlr & 0xFFFF);
3505 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3506 left = v_clamped/MAX_GAIN;
3507 v_clamped = v * (vlr >> 16);
3508 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3509 right = v_clamped/MAX_GAIN;
3510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511
Glenn Kasten952eeb22012-03-06 11:30:57 -08003512 if (left != mLeftVolFloat || right != mRightVolFloat) {
3513 mLeftVolFloat = left;
3514 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515
Glenn Kasten952eeb22012-03-06 11:30:57 -08003516 // If audio HAL implements volume control,
3517 // force software volume to nominal value
3518 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3519 left = 1.0f;
3520 right = 1.0f;
3521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522
Glenn Kasten952eeb22012-03-06 11:30:57 -08003523 // Convert volumes from float to 8.24
3524 uint32_t vl = (uint32_t)(left * (1 << 24));
3525 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526
Glenn Kasten952eeb22012-03-06 11:30:57 -08003527 // Delegate volume control to effect in track effect chain if needed
3528 // only one effect chain can be present on DirectOutputThread, so if
3529 // there is one, the track is connected to it
3530 if (!mEffectChains.isEmpty()) {
3531 // Do not ramp volume if volume is controlled by effect
3532 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 rampVolume = false;
3534 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003535 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536
Glenn Kasten952eeb22012-03-06 11:30:57 -08003537 // Convert volumes from 8.24 to 4.12 format
3538 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3539 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3540 leftVol = (uint16_t)v_clamped;
3541 v_clamped = (vr + (1 << 11)) >> 12;
3542 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3543 rightVol = (uint16_t)v_clamped;
3544 } else {
3545 leftVol = mLeftVolShort;
3546 rightVol = mRightVolShort;
3547 rampVolume = false;
3548 }
3549
3550 // reset retry count
3551 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003552 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003553 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003554 } else {
3555 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003556 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3557 // We have consumed all the buffers of this track.
3558 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003559 // TODO: implement behavior for compressed audio
3560 size_t audioHALFrames =
3561 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3562 size_t framesWritten =
3563 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3564 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003565 if (track->isStopped()) {
3566 track->reset();
3567 }
Eric Laurenta011e352012-03-29 15:51:43 -07003568 trackToRemove = track;
3569 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003570 } else {
3571 // No buffers for this track. Give it a few chances to
3572 // fill a buffer, then remove it from active list.
3573 if (--(track->mRetryCount) <= 0) {
3574 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3575 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003577 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 }
3579 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003580 }
3581 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003583 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003584 // remove all the tracks that need to be...
3585 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003586 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003587 mActiveTracks.remove(trackToRemove);
3588 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003589 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003590 trackToRemove->sessionId());
3591 mEffectChains[0]->decActiveTrackCnt();
3592 }
3593 if (trackToRemove->isTerminated()) {
3594 removeTrack_l(trackToRemove);
3595 }
3596 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597
Glenn Kastenfec279f2012-03-08 07:47:15 -08003598 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003599}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600
Glenn Kasten000f0e32012-03-01 17:10:56 -08003601void AudioFlinger::DirectOutputThread::threadLoop_mix()
3602{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003603 AudioBufferProvider::Buffer buffer;
3604 size_t frameCount = mFrameCount;
3605 int8_t *curBuf = (int8_t *)mMixBuffer;
3606 // output audio to hardware
3607 while (frameCount) {
3608 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003609 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003610 if (CC_UNLIKELY(buffer.raw == NULL)) {
3611 memset(curBuf, 0, frameCount * mFrameSize);
3612 break;
3613 }
3614 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3615 frameCount -= buffer.frameCount;
3616 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003617 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003618 }
3619 sleepTime = 0;
3620 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003621 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003622
3623 // apply volume
3624
3625 // Do not apply volume on compressed audio
3626 if (!audio_is_linear_pcm(mFormat)) {
3627 return;
3628 }
3629
3630 // convert to signed 16 bit before volume calculation
3631 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3632 size_t count = mFrameCount * mChannelCount;
3633 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3634 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003635 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003636 *dst-- = (int16_t)(*src--^0x80) << 8;
3637 }
3638 }
3639
3640 frameCount = mFrameCount;
3641 int16_t *out = mMixBuffer;
3642 if (rampVolume) {
3643 if (mChannelCount == 1) {
3644 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3645 int32_t vlInc = d / (int32_t)frameCount;
3646 int32_t vl = ((int32_t)mLeftVolShort << 16);
3647 do {
3648 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3649 out++;
3650 vl += vlInc;
3651 } while (--frameCount);
3652
3653 } else {
3654 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3655 int32_t vlInc = d / (int32_t)frameCount;
3656 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3657 int32_t vrInc = d / (int32_t)frameCount;
3658 int32_t vl = ((int32_t)mLeftVolShort << 16);
3659 int32_t vr = ((int32_t)mRightVolShort << 16);
3660 do {
3661 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3662 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3663 out += 2;
3664 vl += vlInc;
3665 vr += vrInc;
3666 } while (--frameCount);
3667 }
3668 } else {
3669 if (mChannelCount == 1) {
3670 do {
3671 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3672 out++;
3673 } while (--frameCount);
3674 } else {
3675 do {
3676 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3677 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3678 out += 2;
3679 } while (--frameCount);
3680 }
3681 }
3682
3683 // convert back to unsigned 8 bit after volume calculation
3684 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3685 size_t count = mFrameCount * mChannelCount;
3686 int16_t *src = mMixBuffer;
3687 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003688 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003689 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3690 }
3691 }
3692
3693 mLeftVolShort = leftVol;
3694 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003695}
3696
3697void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3698{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003699 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003700 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003701 sleepTime = activeSleepTime;
3702 } else {
3703 sleepTime = idleSleepTime;
3704 }
3705 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003706 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003707 sleepTime = 0;
3708 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709}
3710
3711// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003712int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713{
3714 return 0;
3715}
3716
3717// deleteTrackName_l() must be called with ThreadBase::mLock held
3718void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3719{
3720}
3721
3722// checkForNewParameters_l() must be called with ThreadBase::mLock held
3723bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3724{
3725 bool reconfig = false;
3726
3727 while (!mNewParameters.isEmpty()) {
3728 status_t status = NO_ERROR;
3729 String8 keyValuePair = mNewParameters[0];
3730 AudioParameter param = AudioParameter(keyValuePair);
3731 int value;
3732
3733 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3734 // do not accept frame count changes if tracks are open as the track buffer
3735 // size depends on frame count and correct behavior would not be garantied
3736 // if frame count is changed after track creation
3737 if (!mTracks.isEmpty()) {
3738 status = INVALID_OPERATION;
3739 } else {
3740 reconfig = true;
3741 }
3742 }
3743 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003744 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003745 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003747 mOutput->stream->common.standby(&mOutput->stream->common);
3748 mStandby = true;
3749 mBytesWritten = 0;
3750 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003751 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 }
3753 if (status == NO_ERROR && reconfig) {
3754 readOutputParameters();
3755 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3756 }
3757 }
3758
3759 mNewParameters.removeAt(0);
3760
3761 mParamStatus = status;
3762 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003763 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3764 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003765 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 }
3767 return reconfig;
3768}
3769
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003770uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771{
3772 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003773 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003774 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 } else {
3776 time = 10000;
3777 }
3778 return time;
3779}
3780
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003781uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782{
3783 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003784 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003785 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 } else {
3787 time = 10000;
3788 }
3789 return time;
3790}
3791
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003792uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003793{
3794 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003795 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003796 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3797 } else {
3798 time = 10000;
3799 }
3800 return time;
3801}
3802
Glenn Kasten66fcab92012-02-24 14:59:21 -08003803void AudioFlinger::DirectOutputThread::cacheParameters_l()
3804{
3805 PlaybackThread::cacheParameters_l();
3806
3807 // use shorter standby delay as on normal output to release
3808 // hardware resources as soon as possible
3809 standbyDelay = microseconds(activeSleepTime*2);
3810}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003811
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812// ----------------------------------------------------------------------------
3813
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003814AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003815 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003816 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3817 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003819 addOutputTrack(mainThread);
3820}
3821
3822AudioFlinger::DuplicatingThread::~DuplicatingThread()
3823{
3824 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3825 mOutputTracks[i]->destroy();
3826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827}
3828
Glenn Kasten000f0e32012-03-01 17:10:56 -08003829void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003831 // mix buffers...
3832 if (outputsReady(outputTracks)) {
3833 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3834 } else {
3835 memset(mMixBuffer, 0, mixBufferSize);
3836 }
3837 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003838 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003839}
3840
3841void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3842{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003843 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003844 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003845 sleepTime = activeSleepTime;
3846 } else {
3847 sleepTime = idleSleepTime;
3848 }
3849 } else if (mBytesWritten != 0) {
3850 // flush remaining overflow buffers in output tracks
3851 for (size_t i = 0; i < outputTracks.size(); i++) {
3852 if (outputTracks[i]->isActive()) {
3853 sleepTime = 0;
3854 writeFrames = 0;
3855 memset(mMixBuffer, 0, mixBufferSize);
3856 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003858 }
3859 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003860}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861
Glenn Kasten000f0e32012-03-01 17:10:56 -08003862void AudioFlinger::DuplicatingThread::threadLoop_write()
3863{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003864 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003865 for (size_t i = 0; i < outputTracks.size(); i++) {
3866 outputTracks[i]->write(mMixBuffer, writeFrames);
3867 }
3868 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003869}
Glenn Kasten688a6402012-02-29 07:57:06 -08003870
Glenn Kasten000f0e32012-03-01 17:10:56 -08003871void AudioFlinger::DuplicatingThread::threadLoop_standby()
3872{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003873 // DuplicatingThread implements standby by stopping all tracks
3874 for (size_t i = 0; i < outputTracks.size(); i++) {
3875 outputTracks[i]->stop();
3876 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877}
3878
Glenn Kastenfa26a852012-03-06 11:28:04 -08003879void AudioFlinger::DuplicatingThread::saveOutputTracks()
3880{
3881 outputTracks = mOutputTracks;
3882}
3883
3884void AudioFlinger::DuplicatingThread::clearOutputTracks()
3885{
3886 outputTracks.clear();
3887}
3888
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3890{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003891 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003892 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003893 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003894 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 this,
3896 mSampleRate,
3897 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003898 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899 frameCount);
3900 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003901 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003903 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003904 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 }
3906}
3907
3908void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3909{
3910 Mutex::Autolock _l(mLock);
3911 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003912 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913 mOutputTracks[i]->destroy();
3914 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003915 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916 return;
3917 }
3918 }
Steve Block3856b092011-10-20 11:56:00 +01003919 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920}
3921
Glenn Kasten438b0362012-03-06 11:24:48 -08003922// caller must hold mLock
3923void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003924{
3925 mWaitTimeMs = UINT_MAX;
3926 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3927 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003928 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3930 if (waitTimeMs < mWaitTimeMs) {
3931 mWaitTimeMs = waitTimeMs;
3932 }
3933 }
3934 }
3935}
3936
3937
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003938bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939{
3940 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003941 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003943 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944 return false;
3945 }
3946 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3947 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003948 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003949 return false;
3950 }
3951 }
3952 return true;
3953}
3954
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003955uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956{
3957 return (mWaitTimeMs * 1000) / 2;
3958}
3959
Glenn Kasten66fcab92012-02-24 14:59:21 -08003960void AudioFlinger::DuplicatingThread::cacheParameters_l()
3961{
3962 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3963 updateWaitTime_l();
3964
3965 MixerThread::cacheParameters_l();
3966}
3967
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968// ----------------------------------------------------------------------------
3969
3970// TrackBase constructor must be called with AudioFlinger::mLock held
3971AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003972 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003973 const sp<Client>& client,
3974 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003975 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003976 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 const sp<IMemory>& sharedBuffer,
3979 int sessionId)
3980 : RefBase(),
3981 mThread(thread),
3982 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003983 mCblk(NULL),
3984 // mBuffer
3985 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986 mFrameCount(0),
3987 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003988 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003990 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003992 // mChannelCount
3993 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003994{
Steve Block3856b092011-10-20 11:56:00 +01003995 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996
Steve Blockb8a80522011-12-20 16:23:08 +00003997 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003998 size_t size = sizeof(audio_track_cblk_t);
3999 uint8_t channelCount = popcount(channelMask);
4000 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4001 if (sharedBuffer == 0) {
4002 size += bufferSize;
4003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004005 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006 mCblkMemory = client->heap()->allocate(size);
4007 if (mCblkMemory != 0) {
4008 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004009 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010 new(mCblk) audio_track_cblk_t();
4011 // clear all buffers
4012 mCblk->frameCount = frameCount;
4013 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004014// uncomment the following lines to quickly test 32-bit wraparound
4015// mCblk->user = 0xffff0000;
4016// mCblk->server = 0xffff0000;
4017// mCblk->userBase = 0xffff0000;
4018// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004019 mChannelCount = channelCount;
4020 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 if (sharedBuffer == 0) {
4022 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4023 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4024 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004025 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026 mCblk->flags = CBLK_UNDERRUN_ON;
4027 } else {
4028 mBuffer = sharedBuffer->pointer();
4029 }
4030 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4031 }
4032 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004033 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 client->heap()->dump("AudioTrack");
4035 return;
4036 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004037 } else {
4038 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004039 // construct the shared structure in-place.
4040 new(mCblk) audio_track_cblk_t();
4041 // clear all buffers
4042 mCblk->frameCount = frameCount;
4043 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004044// uncomment the following lines to quickly test 32-bit wraparound
4045// mCblk->user = 0xffff0000;
4046// mCblk->server = 0xffff0000;
4047// mCblk->userBase = 0xffff0000;
4048// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004049 mChannelCount = channelCount;
4050 mChannelMask = channelMask;
4051 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4052 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4053 // Force underrun condition to avoid false underrun callback until first data is
4054 // written to buffer (other flags are cleared)
4055 mCblk->flags = CBLK_UNDERRUN_ON;
4056 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058}
4059
4060AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4061{
Glenn Kastena0d68332012-01-27 16:47:15 -08004062 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004063 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004065 } else {
4066 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 }
4068 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004069 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004070 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004071 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004073 // If the client's reference count drops to zero, the associated destructor
4074 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4075 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076 mClient.clear();
4077 }
4078}
4079
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004080// AudioBufferProvider interface
4081// getNextBuffer() = 0;
4082// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4084{
Glenn Kastene0feee32011-12-13 11:53:26 -08004085 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004087 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004088 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 buffer->frameCount = 0;
4090}
4091
4092bool AudioFlinger::ThreadBase::TrackBase::step() {
4093 bool result;
4094 audio_track_cblk_t* cblk = this->cblk();
4095
4096 result = cblk->stepServer(mFrameCount);
4097 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004098 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004099 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 }
4101 return result;
4102}
4103
4104void AudioFlinger::ThreadBase::TrackBase::reset() {
4105 audio_track_cblk_t* cblk = this->cblk();
4106
4107 cblk->user = 0;
4108 cblk->server = 0;
4109 cblk->userBase = 0;
4110 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004111 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004112 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113}
4114
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4116 return (int)mCblk->sampleRate;
4117}
4118
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4120 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004121 size_t frameSize = cblk->frameSize;
4122 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4123 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004124
4125 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004126 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4127 "TrackBase::getBuffer buffer out of range:\n"
4128 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4129 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004131 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132
4133 return bufferStart;
4134}
4135
Eric Laurenta011e352012-03-29 15:51:43 -07004136status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4137{
4138 mSyncEvents.add(event);
4139 return NO_ERROR;
4140}
4141
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142// ----------------------------------------------------------------------------
4143
4144// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4145AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004146 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004148 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004150 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004151 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 int frameCount,
4153 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004154 int sessionId,
4155 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004156 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004157 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004158 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004159 // mRetryCount initialized later when needed
4160 mSharedBuffer(sharedBuffer),
4161 mStreamType(streamType),
4162 mName(-1), // see note below
4163 mMainBuffer(thread->mixBuffer()),
4164 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004165 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004166 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004167 mFlags(flags),
4168 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004169 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004170 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171{
4172 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4174 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004175 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004176 if (flags & IAudioFlinger::TRACK_FAST) {
4177 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4178 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4179 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004180 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004181 // FIXME This is too eager. We allocate a fast track index before the
4182 // fast track becomes active. Since fast tracks are a scarce resource,
4183 // this means we are potentially denying other more important fast tracks from
4184 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004185 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004186 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004187 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004188 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004189 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004190 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004191 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004192 if (mName < 0) {
4193 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004194 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4195 // then we leak a fast track index. Should swap these two sections, or better yet
4196 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004197 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004199 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200}
4201
4202AudioFlinger::PlaybackThread::Track::~Track()
4203{
Steve Block3856b092011-10-20 11:56:00 +01004204 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205 sp<ThreadBase> thread = mThread.promote();
4206 if (thread != 0) {
4207 Mutex::Autolock _l(thread->mLock);
4208 mState = TERMINATED;
4209 }
4210}
4211
4212void AudioFlinger::PlaybackThread::Track::destroy()
4213{
4214 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4215 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004216 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 // we must acquire a strong reference on this Track before locking mLock
4218 // here so that the destructor is called only when exiting this function.
4219 // On the other hand, as long as Track::destroy() is only called by
4220 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4221 // this Track with its member mTrack.
4222 sp<Track> keep(this);
4223 { // scope for mLock
4224 sp<ThreadBase> thread = mThread.promote();
4225 if (thread != 0) {
4226 if (!isOutputTrack()) {
4227 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004228 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004229
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004230#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004231 // to track the speaker usage
4232 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004233#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234 }
4235 AudioSystem::releaseOutput(thread->id());
4236 }
4237 Mutex::Autolock _l(thread->mLock);
4238 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4239 playbackThread->destroyTrack_l(this);
4240 }
4241 }
4242}
4243
Glenn Kasten288ed212012-04-25 17:52:27 -07004244/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4245{
Glenn Kastene213c862012-04-25 13:46:15 -07004246 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4247 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004248}
4249
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4251{
Glenn Kasten83d86532012-01-17 14:39:34 -08004252 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004253 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004254 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004255 } else {
4256 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4257 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004258 track_state state = mState;
4259 char stateChar;
4260 switch (state) {
4261 case IDLE:
4262 stateChar = 'I';
4263 break;
4264 case TERMINATED:
4265 stateChar = 'T';
4266 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004267 case STOPPING_1:
4268 stateChar = 's';
4269 break;
4270 case STOPPING_2:
4271 stateChar = '5';
4272 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004273 case STOPPED:
4274 stateChar = 'S';
4275 break;
4276 case RESUMING:
4277 stateChar = 'R';
4278 break;
4279 case ACTIVE:
4280 stateChar = 'A';
4281 break;
4282 case PAUSING:
4283 stateChar = 'p';
4284 break;
4285 case PAUSED:
4286 stateChar = 'P';
4287 break;
Eric Laurent29864602012-05-08 18:57:51 -07004288 case FLUSHED:
4289 stateChar = 'F';
4290 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004291 default:
4292 stateChar = '?';
4293 break;
4294 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004295 char nowInUnderrun;
4296 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4297 case UNDERRUN_FULL:
4298 nowInUnderrun = ' ';
4299 break;
4300 case UNDERRUN_PARTIAL:
4301 nowInUnderrun = '<';
4302 break;
4303 case UNDERRUN_EMPTY:
4304 nowInUnderrun = '*';
4305 break;
4306 default:
4307 nowInUnderrun = '?';
4308 break;
4309 }
Glenn Kastene213c862012-04-25 13:46:15 -07004310 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4311 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004312 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 mStreamType,
4314 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004315 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 mSessionId,
4317 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004318 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004319 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 mMute,
4321 mFillingUpStatus,
4322 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004323 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4324 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 mCblk->server,
4326 mCblk->user,
4327 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004328 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004329 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004330 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004331 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004332}
4333
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004334// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004335status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004336 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004338 audio_track_cblk_t* cblk = this->cblk();
4339 uint32_t framesReady;
4340 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004342 // Check if last stepServer failed, try to step now
4343 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004344 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4345 // Since the fast mixer is higher priority than client callback thread,
4346 // it does not result in priority inversion for client.
4347 // But a non-blocking solution would be preferable to avoid
4348 // fast mixer being unable to tryLock(), and
4349 // to avoid the extra context switches if the client wakes up,
4350 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004351 if (!step()) goto getNextBuffer_exit;
4352 ALOGV("stepServer recovered");
4353 mStepServerFailed = false;
4354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355
Glenn Kasten288ed212012-04-25 17:52:27 -07004356 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004357 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004358
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004359 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360 uint32_t s = cblk->server;
4361 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4362
4363 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4364 if (framesReq > framesReady) {
4365 framesReq = framesReady;
4366 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004367 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 framesReq = bufferEnd - s;
4369 }
4370
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004371 buffer->raw = getBuffer(s, framesReq);
4372 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004374 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004376 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377
4378getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004379 buffer->raw = NULL;
4380 buffer->frameCount = 0;
4381 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4382 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383}
4384
Glenn Kasten288ed212012-04-25 17:52:27 -07004385// Note that framesReady() takes a mutex on the control block using tryLock().
4386// This could result in priority inversion if framesReady() is called by the normal mixer,
4387// as the normal mixer thread runs at lower
4388// priority than the client's callback thread: there is a short window within framesReady()
4389// during which the normal mixer could be preempted, and the client callback would block.
4390// Another problem can occur if framesReady() is called by the fast mixer:
4391// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4392// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4393size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004394 return mCblk->framesReady();
4395}
4396
Glenn Kasten288ed212012-04-25 17:52:27 -07004397// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004399 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400
John Grossman4ff14ba2012-02-08 16:37:41 -08004401 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4403 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004404 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 return true;
4406 }
4407 return false;
4408}
4409
Glenn Kasten3acbd052012-02-28 10:39:56 -08004410status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004411 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412{
4413 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004414 ALOGV("start(%d), calling pid %d session %d",
4415 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004416
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417 sp<ThreadBase> thread = mThread.promote();
4418 if (thread != 0) {
4419 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004420 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 // here the track could be either new, or restarted
4422 // in both cases "unstop" the track
4423 if (mState == PAUSED) {
4424 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004425 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 } else {
4427 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004428 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 }
4430
4431 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4432 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004433 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004435
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004436#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004437 // to track the speaker usage
4438 if (status == NO_ERROR) {
4439 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4440 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004441#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442 }
4443 if (status == NO_ERROR) {
4444 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4445 playbackThread->addTrack_l(this);
4446 } else {
4447 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004448 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450 } else {
4451 status = BAD_VALUE;
4452 }
4453 return status;
4454}
4455
4456void AudioFlinger::PlaybackThread::Track::stop()
4457{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004458 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 sp<ThreadBase> thread = mThread.promote();
4460 if (thread != 0) {
4461 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004462 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004463 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 // If the track is not active (PAUSED and buffers full), flush buffers
4465 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4466 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4467 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004468 mState = STOPPED;
4469 } else if (!isFastTrack()) {
4470 mState = STOPPED;
4471 } else {
4472 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4473 // and then to STOPPED and reset() when presentation is complete
4474 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004476 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477 }
4478 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4479 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004480 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004482
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004483#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004484 // to track the speaker usage
4485 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004486#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 }
4488 }
4489}
4490
4491void AudioFlinger::PlaybackThread::Track::pause()
4492{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004493 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494 sp<ThreadBase> thread = mThread.promote();
4495 if (thread != 0) {
4496 Mutex::Autolock _l(thread->mLock);
4497 if (mState == ACTIVE || mState == RESUMING) {
4498 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004499 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500 if (!isOutputTrack()) {
4501 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004502 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004504
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004505#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004506 // to track the speaker usage
4507 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004508#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 }
4510 }
4511 }
4512}
4513
4514void AudioFlinger::PlaybackThread::Track::flush()
4515{
Steve Block3856b092011-10-20 11:56:00 +01004516 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 sp<ThreadBase> thread = mThread.promote();
4518 if (thread != 0) {
4519 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004520 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4521 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 return;
4523 }
4524 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004525 // FLUSHED state
4526 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004527 // do not reset the track if it is still in the process of being stopped or paused.
4528 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004529 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004530 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004531 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4532 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4533 reset();
4534 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 }
4536}
4537
4538void AudioFlinger::PlaybackThread::Track::reset()
4539{
4540 // Do not reset twice to avoid discarding data written just after a flush and before
4541 // the audioflinger thread detects the track is stopped.
4542 if (!mResetDone) {
4543 TrackBase::reset();
4544 // Force underrun condition to avoid false underrun callback until first data is
4545 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004546 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4547 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 mFillingUpStatus = FS_FILLING;
4549 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004550 if (mState == FLUSHED) {
4551 mState = IDLE;
4552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 }
4554}
4555
4556void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4557{
4558 mMute = muted;
4559}
4560
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4562{
4563 status_t status = DEAD_OBJECT;
4564 sp<ThreadBase> thread = mThread.promote();
4565 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004566 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4567 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 }
4569 return status;
4570}
4571
4572void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4573{
4574 mAuxEffectId = EffectId;
4575 mAuxBuffer = buffer;
4576}
4577
Eric Laurenta011e352012-03-29 15:51:43 -07004578bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4579 size_t audioHalFrames)
4580{
4581 // a track is considered presented when the total number of frames written to audio HAL
4582 // corresponds to the number of frames written when presentationComplete() is called for the
4583 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4584 if (mPresentationCompleteFrames == 0) {
4585 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4586 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4587 mPresentationCompleteFrames, audioHalFrames);
4588 }
4589 if (framesWritten >= mPresentationCompleteFrames) {
4590 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4591 mSessionId, framesWritten);
4592 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004593 return true;
4594 }
4595 return false;
4596}
4597
4598void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4599{
4600 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4601 if (mSyncEvents[i]->type() == type) {
4602 mSyncEvents[i]->trigger();
4603 mSyncEvents.removeAt(i);
4604 i--;
4605 }
4606 }
4607}
4608
Glenn Kasten58912562012-04-03 10:45:00 -07004609// implement VolumeBufferProvider interface
4610
4611uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4612{
4613 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4614 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4615 uint32_t vlr = mCblk->getVolumeLR();
4616 uint32_t vl = vlr & 0xFFFF;
4617 uint32_t vr = vlr >> 16;
4618 // track volumes come from shared memory, so can't be trusted and must be clamped
4619 if (vl > MAX_GAIN_INT) {
4620 vl = MAX_GAIN_INT;
4621 }
4622 if (vr > MAX_GAIN_INT) {
4623 vr = MAX_GAIN_INT;
4624 }
4625 // now apply the cached master volume and stream type volume;
4626 // this is trusted but lacks any synchronization or barrier so may be stale
4627 float v = mCachedVolume;
4628 vl *= v;
4629 vr *= v;
4630 // re-combine into U4.16
4631 vlr = (vr << 16) | (vl & 0xFFFF);
4632 // FIXME look at mute, pause, and stop flags
4633 return vlr;
4634}
Eric Laurenta011e352012-03-29 15:51:43 -07004635
Eric Laurent29864602012-05-08 18:57:51 -07004636status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4637{
4638 if (mState == TERMINATED || mState == PAUSED ||
4639 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4640 (mState == STOPPED)))) {
4641 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4642 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4643 event->cancel();
4644 return INVALID_OPERATION;
4645 }
4646 TrackBase::setSyncEvent(event);
4647 return NO_ERROR;
4648}
4649
John Grossman4ff14ba2012-02-08 16:37:41 -08004650// timed audio tracks
4651
4652sp<AudioFlinger::PlaybackThread::TimedTrack>
4653AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004654 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004655 const sp<Client>& client,
4656 audio_stream_type_t streamType,
4657 uint32_t sampleRate,
4658 audio_format_t format,
4659 uint32_t channelMask,
4660 int frameCount,
4661 const sp<IMemory>& sharedBuffer,
4662 int sessionId) {
4663 if (!client->reserveTimedTrack())
4664 return NULL;
4665
Glenn Kastena0356762012-03-19 10:38:51 -07004666 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004667 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4668 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004669}
4670
4671AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004672 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004673 const sp<Client>& client,
4674 audio_stream_type_t streamType,
4675 uint32_t sampleRate,
4676 audio_format_t format,
4677 uint32_t channelMask,
4678 int frameCount,
4679 const sp<IMemory>& sharedBuffer,
4680 int sessionId)
4681 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004682 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004683 mQueueHeadInFlight(false),
4684 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004685 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004686 mTimedSilenceBuffer(NULL),
4687 mTimedSilenceBufferSize(0),
4688 mTimedAudioOutputOnTime(false),
4689 mMediaTimeTransformValid(false)
4690{
4691 LocalClock lc;
4692 mLocalTimeFreq = lc.getLocalFreq();
4693
4694 mLocalTimeToSampleTransform.a_zero = 0;
4695 mLocalTimeToSampleTransform.b_zero = 0;
4696 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4697 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4698 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4699 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004700
4701 mMediaTimeToSampleTransform.a_zero = 0;
4702 mMediaTimeToSampleTransform.b_zero = 0;
4703 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4704 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4705 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4706 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004707}
4708
4709AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4710 mClient->releaseTimedTrack();
4711 delete [] mTimedSilenceBuffer;
4712}
4713
4714status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4715 size_t size, sp<IMemory>* buffer) {
4716
4717 Mutex::Autolock _l(mTimedBufferQueueLock);
4718
4719 trimTimedBufferQueue_l();
4720
4721 // lazily initialize the shared memory heap for timed buffers
4722 if (mTimedMemoryDealer == NULL) {
4723 const int kTimedBufferHeapSize = 512 << 10;
4724
4725 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4726 "AudioFlingerTimed");
4727 if (mTimedMemoryDealer == NULL)
4728 return NO_MEMORY;
4729 }
4730
4731 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4732 if (newBuffer == NULL) {
4733 newBuffer = mTimedMemoryDealer->allocate(size);
4734 if (newBuffer == NULL)
4735 return NO_MEMORY;
4736 }
4737
4738 *buffer = newBuffer;
4739 return NO_ERROR;
4740}
4741
4742// caller must hold mTimedBufferQueueLock
4743void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4744 int64_t mediaTimeNow;
4745 {
4746 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4747 if (!mMediaTimeTransformValid)
4748 return;
4749
4750 int64_t targetTimeNow;
4751 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4752 ? mCCHelper.getCommonTime(&targetTimeNow)
4753 : mCCHelper.getLocalTime(&targetTimeNow);
4754
4755 if (OK != res)
4756 return;
4757
4758 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4759 &mediaTimeNow)) {
4760 return;
4761 }
4762 }
4763
John Grossman1c345192012-03-27 14:00:17 -07004764 size_t trimEnd;
4765 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004766 int64_t bufEnd;
4767
John Grossmanc95cfbb2012-04-12 11:53:11 -07004768 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4769 // We have a next buffer. Just use its PTS as the PTS of the frame
4770 // following the last frame in this buffer. If the stream is sparse
4771 // (ie, there are deliberate gaps left in the stream which should be
4772 // filled with silence by the TimedAudioTrack), then this can result
4773 // in one extra buffer being left un-trimmed when it could have
4774 // been. In general, this is not typical, and we would rather
4775 // optimized away the TS calculation below for the more common case
4776 // where PTSes are contiguous.
4777 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4778 } else {
4779 // We have no next buffer. Compute the PTS of the frame following
4780 // the last frame in this buffer by computing the duration of of
4781 // this frame in media time units and adding it to the PTS of the
4782 // buffer.
4783 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4784 / mCblk->frameSize;
4785
4786 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4787 &bufEnd)) {
4788 ALOGE("Failed to convert frame count of %lld to media time"
4789 " duration" " (scale factor %d/%u) in %s",
4790 frameCount,
4791 mMediaTimeToSampleTransform.a_to_b_numer,
4792 mMediaTimeToSampleTransform.a_to_b_denom,
4793 __PRETTY_FUNCTION__);
4794 break;
4795 }
4796 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004797 }
John Grossman9fbdee12012-03-26 17:51:46 -07004798
4799 if (bufEnd > mediaTimeNow)
4800 break;
4801
4802 // Is the buffer we want to use in the middle of a mix operation right
4803 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4804 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004805 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004806 mTrimQueueHeadOnRelease = true;
4807 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004808 }
4809
John Grossman9fbdee12012-03-26 17:51:46 -07004810 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004811 if (trimStart < trimEnd) {
4812 // Update the bookkeeping for framesReady()
4813 for (size_t i = trimStart; i < trimEnd; ++i) {
4814 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4815 }
4816
4817 // Now actually remove the buffers from the queue.
4818 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004819 }
4820}
4821
John Grossman1c345192012-03-27 14:00:17 -07004822void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4823 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004824 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4825 "%s called (reason \"%s\"), but timed buffer queue has no"
4826 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004827
4828 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4829 mTimedBufferQueue.removeAt(0);
4830}
4831
4832void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4833 const TimedBuffer& buf,
4834 const char* logTag) {
4835 uint32_t bufBytes = buf.buffer()->size();
4836 uint32_t consumedAlready = buf.position();
4837
Eric Laurentb388e532012-04-14 13:32:48 -07004838 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004839 "Bad bookkeeping while updating frames pending. Timed buffer is"
4840 " only %u bytes long, but claims to have consumed %u"
4841 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004842 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004843
4844 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004845 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4846 "Bad bookkeeping while updating frames pending. Should have at"
4847 " least %u queued frames, but we think we have only %u. (update"
4848 " reason: \"%s\")",
4849 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004850
4851 mFramesPendingInQueue -= bufFrames;
4852}
4853
John Grossman4ff14ba2012-02-08 16:37:41 -08004854status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4855 const sp<IMemory>& buffer, int64_t pts) {
4856
4857 {
4858 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4859 if (!mMediaTimeTransformValid)
4860 return INVALID_OPERATION;
4861 }
4862
4863 Mutex::Autolock _l(mTimedBufferQueueLock);
4864
John Grossman1c345192012-03-27 14:00:17 -07004865 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4866 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004867 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4868
4869 return NO_ERROR;
4870}
4871
4872status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4873 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4874
John Grossman1c345192012-03-27 14:00:17 -07004875 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4876 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4877 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004878
4879 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4880 target == TimedAudioTrack::COMMON_TIME)) {
4881 return BAD_VALUE;
4882 }
4883
4884 Mutex::Autolock lock(mMediaTimeTransformLock);
4885 mMediaTimeTransform = xform;
4886 mMediaTimeTransformTarget = target;
4887 mMediaTimeTransformValid = true;
4888
4889 return NO_ERROR;
4890}
4891
4892#define min(a, b) ((a) < (b) ? (a) : (b))
4893
4894// implementation of getNextBuffer for tracks whose buffers have timestamps
4895status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4896 AudioBufferProvider::Buffer* buffer, int64_t pts)
4897{
4898 if (pts == AudioBufferProvider::kInvalidPTS) {
4899 buffer->raw = 0;
4900 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004901 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004902 return INVALID_OPERATION;
4903 }
4904
John Grossman4ff14ba2012-02-08 16:37:41 -08004905 Mutex::Autolock _l(mTimedBufferQueueLock);
4906
John Grossman9fbdee12012-03-26 17:51:46 -07004907 ALOG_ASSERT(!mQueueHeadInFlight,
4908 "getNextBuffer called without releaseBuffer!");
4909
John Grossman4ff14ba2012-02-08 16:37:41 -08004910 while (true) {
4911
4912 // if we have no timed buffers, then fail
4913 if (mTimedBufferQueue.isEmpty()) {
4914 buffer->raw = 0;
4915 buffer->frameCount = 0;
4916 return NOT_ENOUGH_DATA;
4917 }
4918
4919 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4920
4921 // calculate the PTS of the head of the timed buffer queue expressed in
4922 // local time
4923 int64_t headLocalPTS;
4924 {
4925 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4926
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004927 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004928
4929 if (mMediaTimeTransform.a_to_b_denom == 0) {
4930 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004931 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004932 return NO_ERROR;
4933 }
4934
4935 int64_t transformedPTS;
4936 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4937 &transformedPTS)) {
4938 // the transform failed. this shouldn't happen, but if it does
4939 // then just drop this buffer
4940 ALOGW("timedGetNextBuffer transform failed");
4941 buffer->raw = 0;
4942 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004943 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004944 return NO_ERROR;
4945 }
4946
4947 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4948 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4949 &headLocalPTS)) {
4950 buffer->raw = 0;
4951 buffer->frameCount = 0;
4952 return INVALID_OPERATION;
4953 }
4954 } else {
4955 headLocalPTS = transformedPTS;
4956 }
4957 }
4958
4959 // adjust the head buffer's PTS to reflect the portion of the head buffer
4960 // that has already been consumed
4961 int64_t effectivePTS = headLocalPTS +
4962 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4963
4964 // Calculate the delta in samples between the head of the input buffer
4965 // queue and the start of the next output buffer that will be written.
4966 // If the transformation fails because of over or underflow, it means
4967 // that the sample's position in the output stream is so far out of
4968 // whack that it should just be dropped.
4969 int64_t sampleDelta;
4970 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4971 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004972 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4973 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004974 continue;
4975 }
4976 if (!mLocalTimeToSampleTransform.doForwardTransform(
4977 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004978 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004979 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004980 continue;
4981 }
4982
John Grossman1c345192012-03-27 14:00:17 -07004983 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4984 " sampleDelta=[%d.%08x]",
4985 head.pts(), head.position(), pts,
4986 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4987 + (sampleDelta >> 32)),
4988 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004989
4990 // if the delta between the ideal placement for the next input sample and
4991 // the current output position is within this threshold, then we will
4992 // concatenate the next input samples to the previous output
4993 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004994 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004995
4996 // if this is the first buffer of audio that we're emitting from this track
4997 // then it should be almost exactly on time.
4998 const int64_t kSampleStartupThreshold = 1LL << 32;
4999
5000 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005001 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005002 // the next input is close enough to being on time, so concatenate it
5003 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005004 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005005
John Grossman1c345192012-03-27 14:00:17 -07005006 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5007 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005008 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005009 }
5010
5011 // Looks like our output is not on time. Reset our on timed status.
5012 // Next time we mix samples from our input queue, then should be within
5013 // the StartupThreshold.
5014 mTimedAudioOutputOnTime = false;
5015 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005016 // the gap between the current output position and the proper start of
5017 // the next input sample is too big, so fill it with silence
5018 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5019
John Grossman9fbdee12012-03-26 17:51:46 -07005020 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005021 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5022 return NO_ERROR;
5023 } else {
5024 // the next input sample is late
5025 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5026 size_t onTimeSamplePosition =
5027 head.position() + lateFrames * mCblk->frameSize;
5028
5029 if (onTimeSamplePosition > head.buffer()->size()) {
5030 // all the remaining samples in the head are too late, so
5031 // drop it and move on
5032 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005033 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005034 continue;
5035 } else {
5036 // skip over the late samples
5037 head.setPosition(onTimeSamplePosition);
5038
5039 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005040 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005041
5042 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5043 return NO_ERROR;
5044 }
5045 }
5046 }
5047}
5048
5049// Yield samples from the timed buffer queue head up to the given output
5050// buffer's capacity.
5051//
5052// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005053void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005054 AudioBufferProvider::Buffer* buffer) {
5055
5056 const TimedBuffer& head = mTimedBufferQueue[0];
5057
5058 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5059 head.position());
5060
5061 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5062 mCblk->frameSize);
5063 size_t framesRequested = buffer->frameCount;
5064 buffer->frameCount = min(framesLeftInHead, framesRequested);
5065
John Grossman9fbdee12012-03-26 17:51:46 -07005066 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005067 mTimedAudioOutputOnTime = true;
5068}
5069
5070// Yield samples of silence up to the given output buffer's capacity
5071//
5072// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005073void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005074 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5075
5076 // lazily allocate a buffer filled with silence
5077 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5078 delete [] mTimedSilenceBuffer;
5079 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5080 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5081 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5082 }
5083
5084 buffer->raw = mTimedSilenceBuffer;
5085 size_t framesRequested = buffer->frameCount;
5086 buffer->frameCount = min(numFrames, framesRequested);
5087
5088 mTimedAudioOutputOnTime = false;
5089}
5090
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005091// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005092void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5093 AudioBufferProvider::Buffer* buffer) {
5094
5095 Mutex::Autolock _l(mTimedBufferQueueLock);
5096
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005097 // If the buffer which was just released is part of the buffer at the head
5098 // of the queue, be sure to update the amt of the buffer which has been
5099 // consumed. If the buffer being returned is not part of the head of the
5100 // queue, its either because the buffer is part of the silence buffer, or
5101 // because the head of the timed queue was trimmed after the mixer called
5102 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005103 if (buffer->raw == mTimedSilenceBuffer) {
5104 ALOG_ASSERT(!mQueueHeadInFlight,
5105 "Queue head in flight during release of silence buffer!");
5106 goto done;
5107 }
5108
5109 ALOG_ASSERT(mQueueHeadInFlight,
5110 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5111 " head in flight.");
5112
5113 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005114 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005115
5116 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005117 void* end = reinterpret_cast<void*>(
5118 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5119 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005120
John Grossman9fbdee12012-03-26 17:51:46 -07005121 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5122 "released buffer not within the head of the timed buffer"
5123 " queue; qHead = [%p, %p], released buffer = %p",
5124 start, end, buffer->raw);
5125
5126 head.setPosition(head.position() +
5127 (buffer->frameCount * mCblk->frameSize));
5128 mQueueHeadInFlight = false;
5129
John Grossman1c345192012-03-27 14:00:17 -07005130 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5131 "Bad bookkeeping during releaseBuffer! Should have at"
5132 " least %u queued frames, but we think we have only %u",
5133 buffer->frameCount, mFramesPendingInQueue);
5134
5135 mFramesPendingInQueue -= buffer->frameCount;
5136
John Grossman9fbdee12012-03-26 17:51:46 -07005137 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5138 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005139 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005140 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005141 }
John Grossman9fbdee12012-03-26 17:51:46 -07005142 } else {
5143 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5144 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 }
5146
John Grossman9fbdee12012-03-26 17:51:46 -07005147done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005148 buffer->raw = 0;
5149 buffer->frameCount = 0;
5150}
5151
Glenn Kasten288ed212012-04-25 17:52:27 -07005152size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005153 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005154 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005155}
5156
5157AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5158 : mPTS(0), mPosition(0) {}
5159
5160AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5161 const sp<IMemory>& buffer, int64_t pts)
5162 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5163
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164// ----------------------------------------------------------------------------
5165
5166// RecordTrack constructor must be called with AudioFlinger::mLock held
5167AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005168 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 const sp<Client>& client,
5170 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005171 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005172 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 int sessionId)
5175 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005176 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177 mOverflow(false)
5178{
5179 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005180 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5181 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5182 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5183 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5184 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5185 } else {
5186 mCblk->frameSize = sizeof(int8_t);
5187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 }
5189}
5190
5191AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5192{
5193 sp<ThreadBase> thread = mThread.promote();
5194 if (thread != 0) {
5195 AudioSystem::releaseInput(thread->id());
5196 }
5197}
5198
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005199// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005200status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005201{
5202 audio_track_cblk_t* cblk = this->cblk();
5203 uint32_t framesAvail;
5204 uint32_t framesReq = buffer->frameCount;
5205
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005206 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005207 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005208 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005209 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005210 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211 }
5212
5213 framesAvail = cblk->framesAvailable_l();
5214
Glenn Kastenf6b16782011-12-15 09:51:17 -08005215 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 uint32_t s = cblk->server;
5217 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5218
5219 if (framesReq > framesAvail) {
5220 framesReq = framesAvail;
5221 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005222 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005223 framesReq = bufferEnd - s;
5224 }
5225
5226 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005227 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228
5229 buffer->frameCount = framesReq;
5230 return NO_ERROR;
5231 }
5232
5233getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005234 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005235 buffer->frameCount = 0;
5236 return NOT_ENOUGH_DATA;
5237}
5238
Glenn Kasten3acbd052012-02-28 10:39:56 -08005239status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005240 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005241{
5242 sp<ThreadBase> thread = mThread.promote();
5243 if (thread != 0) {
5244 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005245 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005246 } else {
5247 return BAD_VALUE;
5248 }
5249}
5250
5251void AudioFlinger::RecordThread::RecordTrack::stop()
5252{
5253 sp<ThreadBase> thread = mThread.promote();
5254 if (thread != 0) {
5255 RecordThread *recordThread = (RecordThread *)thread.get();
5256 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005257 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005258 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005259 // read from buffer
5260 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261 }
5262}
5263
5264void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5265{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005266 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005267 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005268 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005269 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005270 mSessionId,
5271 mFrameCount,
5272 mState,
5273 mCblk->sampleRate,
5274 mCblk->server,
5275 mCblk->user);
5276}
5277
5278
5279// ----------------------------------------------------------------------------
5280
5281AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005282 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005283 DuplicatingThread *sourceThread,
5284 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005285 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005286 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005287 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005288 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5289 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005290 mActive(false), mSourceThread(sourceThread)
5291{
5292
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293 if (mCblk != NULL) {
5294 mCblk->flags |= CBLK_DIRECTION_OUT;
5295 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005296 mOutBuffer.frameCount = 0;
5297 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005298 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005299 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5300 mCblk, mBuffer, mCblk->buffers,
5301 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005303 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304 }
5305}
5306
5307AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5308{
5309 clearBufferQueue();
5310}
5311
Glenn Kasten3acbd052012-02-28 10:39:56 -08005312status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005313 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005314{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005315 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316 if (status != NO_ERROR) {
5317 return status;
5318 }
5319
5320 mActive = true;
5321 mRetryCount = 127;
5322 return status;
5323}
5324
5325void AudioFlinger::PlaybackThread::OutputTrack::stop()
5326{
5327 Track::stop();
5328 clearBufferQueue();
5329 mOutBuffer.frameCount = 0;
5330 mActive = false;
5331}
5332
5333bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5334{
5335 Buffer *pInBuffer;
5336 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005337 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338 bool outputBufferFull = false;
5339 inBuffer.frameCount = frames;
5340 inBuffer.i16 = data;
5341
5342 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5343
5344 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005345 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 sp<ThreadBase> thread = mThread.promote();
5347 if (thread != 0) {
5348 MixerThread *mixerThread = (MixerThread *)thread.get();
5349 if (mCblk->frameCount > frames){
5350 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5351 uint32_t startFrames = (mCblk->frameCount - frames);
5352 pInBuffer = new Buffer;
5353 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5354 pInBuffer->frameCount = startFrames;
5355 pInBuffer->i16 = pInBuffer->mBuffer;
5356 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5357 mBufferQueue.add(pInBuffer);
5358 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005359 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005360 }
5361 }
5362 }
5363 }
5364
5365 while (waitTimeLeftMs) {
5366 // First write pending buffers, then new data
5367 if (mBufferQueue.size()) {
5368 pInBuffer = mBufferQueue.itemAt(0);
5369 } else {
5370 pInBuffer = &inBuffer;
5371 }
5372
5373 if (pInBuffer->frameCount == 0) {
5374 break;
5375 }
5376
5377 if (mOutBuffer.frameCount == 0) {
5378 mOutBuffer.frameCount = pInBuffer->frameCount;
5379 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005380 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005381 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382 outputBufferFull = true;
5383 break;
5384 }
5385 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5386 if (waitTimeLeftMs >= waitTimeMs) {
5387 waitTimeLeftMs -= waitTimeMs;
5388 } else {
5389 waitTimeLeftMs = 0;
5390 }
5391 }
5392
5393 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5394 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5395 mCblk->stepUser(outFrames);
5396 pInBuffer->frameCount -= outFrames;
5397 pInBuffer->i16 += outFrames * channelCount;
5398 mOutBuffer.frameCount -= outFrames;
5399 mOutBuffer.i16 += outFrames * channelCount;
5400
5401 if (pInBuffer->frameCount == 0) {
5402 if (mBufferQueue.size()) {
5403 mBufferQueue.removeAt(0);
5404 delete [] pInBuffer->mBuffer;
5405 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005406 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407 } else {
5408 break;
5409 }
5410 }
5411 }
5412
5413 // If we could not write all frames, allocate a buffer and queue it for next time.
5414 if (inBuffer.frameCount) {
5415 sp<ThreadBase> thread = mThread.promote();
5416 if (thread != 0 && !thread->standby()) {
5417 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5418 pInBuffer = new Buffer;
5419 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5420 pInBuffer->frameCount = inBuffer.frameCount;
5421 pInBuffer->i16 = pInBuffer->mBuffer;
5422 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5423 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005424 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005426 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 }
5428 }
5429 }
5430
5431 // Calling write() with a 0 length buffer, means that no more data will be written:
5432 // If no more buffers are pending, fill output track buffer to make sure it is started
5433 // by output mixer.
5434 if (frames == 0 && mBufferQueue.size() == 0) {
5435 if (mCblk->user < mCblk->frameCount) {
5436 frames = mCblk->frameCount - mCblk->user;
5437 pInBuffer = new Buffer;
5438 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5439 pInBuffer->frameCount = frames;
5440 pInBuffer->i16 = pInBuffer->mBuffer;
5441 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5442 mBufferQueue.add(pInBuffer);
5443 } else if (mActive) {
5444 stop();
5445 }
5446 }
5447
5448 return outputBufferFull;
5449}
5450
5451status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5452{
5453 int active;
5454 status_t result;
5455 audio_track_cblk_t* cblk = mCblk;
5456 uint32_t framesReq = buffer->frameCount;
5457
Steve Block3856b092011-10-20 11:56:00 +01005458// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 buffer->frameCount = 0;
5460
5461 uint32_t framesAvail = cblk->framesAvailable();
5462
5463
5464 if (framesAvail == 0) {
5465 Mutex::Autolock _l(cblk->lock);
5466 goto start_loop_here;
5467 while (framesAvail == 0) {
5468 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005469 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005470 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005471 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 }
5473 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5474 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005475 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 }
5477 // read the server count again
5478 start_loop_here:
5479 framesAvail = cblk->framesAvailable_l();
5480 }
5481 }
5482
5483// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005484// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485// }
5486
5487 if (framesReq > framesAvail) {
5488 framesReq = framesAvail;
5489 }
5490
5491 uint32_t u = cblk->user;
5492 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5493
Marco Nelissena1472d92012-03-30 14:36:54 -07005494 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 framesReq = bufferEnd - u;
5496 }
5497
5498 buffer->frameCount = framesReq;
5499 buffer->raw = (void *)cblk->buffer(u);
5500 return NO_ERROR;
5501}
5502
5503
5504void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5505{
5506 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005507
5508 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005509 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 delete [] pBuffer->mBuffer;
5511 delete pBuffer;
5512 }
5513 mBufferQueue.clear();
5514}
5515
5516// ----------------------------------------------------------------------------
5517
5518AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5519 : RefBase(),
5520 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005521 // 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 -07005522 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005523 mPid(pid),
5524 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525{
5526 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5527}
5528
5529// Client destructor must be called with AudioFlinger::mLock held
5530AudioFlinger::Client::~Client()
5531{
5532 mAudioFlinger->removeClient_l(mPid);
5533}
5534
Glenn Kasten435dbe62012-01-30 10:15:48 -08005535sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536{
5537 return mMemoryDealer;
5538}
5539
John Grossman4ff14ba2012-02-08 16:37:41 -08005540// Reserve one of the limited slots for a timed audio track associated
5541// with this client
5542bool AudioFlinger::Client::reserveTimedTrack()
5543{
5544 const int kMaxTimedTracksPerClient = 4;
5545
5546 Mutex::Autolock _l(mTimedTrackLock);
5547
5548 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5549 ALOGW("can not create timed track - pid %d has exceeded the limit",
5550 mPid);
5551 return false;
5552 }
5553
5554 mTimedTrackCount++;
5555 return true;
5556}
5557
5558// Release a slot for a timed audio track
5559void AudioFlinger::Client::releaseTimedTrack()
5560{
5561 Mutex::Autolock _l(mTimedTrackLock);
5562 mTimedTrackCount--;
5563}
5564
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565// ----------------------------------------------------------------------------
5566
5567AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5568 const sp<IAudioFlingerClient>& client,
5569 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005570 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571{
5572}
5573
5574AudioFlinger::NotificationClient::~NotificationClient()
5575{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005576}
5577
5578void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5579{
5580 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005581 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582}
5583
5584// ----------------------------------------------------------------------------
5585
5586AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5587 : BnAudioTrack(),
5588 mTrack(track)
5589{
5590}
5591
5592AudioFlinger::TrackHandle::~TrackHandle() {
5593 // just stop the track on deletion, associated resources
5594 // will be freed from the main thread once all pending buffers have
5595 // been played. Unless it's not in the active track list, in which
5596 // case we free everything now...
5597 mTrack->destroy();
5598}
5599
Glenn Kasten90716c52012-01-26 13:40:12 -08005600sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5601 return mTrack->getCblk();
5602}
5603
Glenn Kasten3acbd052012-02-28 10:39:56 -08005604status_t AudioFlinger::TrackHandle::start() {
5605 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606}
5607
5608void AudioFlinger::TrackHandle::stop() {
5609 mTrack->stop();
5610}
5611
5612void AudioFlinger::TrackHandle::flush() {
5613 mTrack->flush();
5614}
5615
5616void AudioFlinger::TrackHandle::mute(bool e) {
5617 mTrack->mute(e);
5618}
5619
5620void AudioFlinger::TrackHandle::pause() {
5621 mTrack->pause();
5622}
5623
Mathias Agopian65ab4712010-07-14 17:59:35 -07005624status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5625{
5626 return mTrack->attachAuxEffect(EffectId);
5627}
5628
John Grossman4ff14ba2012-02-08 16:37:41 -08005629status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5630 sp<IMemory>* buffer) {
5631 if (!mTrack->isTimedTrack())
5632 return INVALID_OPERATION;
5633
5634 PlaybackThread::TimedTrack* tt =
5635 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5636 return tt->allocateTimedBuffer(size, buffer);
5637}
5638
5639status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5640 int64_t pts) {
5641 if (!mTrack->isTimedTrack())
5642 return INVALID_OPERATION;
5643
5644 PlaybackThread::TimedTrack* tt =
5645 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5646 return tt->queueTimedBuffer(buffer, pts);
5647}
5648
5649status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5650 const LinearTransform& xform, int target) {
5651
5652 if (!mTrack->isTimedTrack())
5653 return INVALID_OPERATION;
5654
5655 PlaybackThread::TimedTrack* tt =
5656 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5657 return tt->setMediaTimeTransform(
5658 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5659}
5660
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661status_t AudioFlinger::TrackHandle::onTransact(
5662 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5663{
5664 return BnAudioTrack::onTransact(code, data, reply, flags);
5665}
5666
5667// ----------------------------------------------------------------------------
5668
5669sp<IAudioRecord> AudioFlinger::openRecord(
5670 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005671 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005673 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005674 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005676 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 int *sessionId,
5678 status_t *status)
5679{
5680 sp<RecordThread::RecordTrack> recordTrack;
5681 sp<RecordHandle> recordHandle;
5682 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683 status_t lStatus;
5684 RecordThread *thread;
5685 size_t inFrameCount;
5686 int lSessionId;
5687
5688 // check calling permissions
5689 if (!recordingAllowed()) {
5690 lStatus = PERMISSION_DENIED;
5691 goto Exit;
5692 }
5693
5694 // add client to list
5695 { // scope for mLock
5696 Mutex::Autolock _l(mLock);
5697 thread = checkRecordThread_l(input);
5698 if (thread == NULL) {
5699 lStatus = BAD_VALUE;
5700 goto Exit;
5701 }
5702
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005703 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704
5705 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005706 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 lSessionId = *sessionId;
5708 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005709 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710 if (sessionId != NULL) {
5711 *sessionId = lSessionId;
5712 }
5713 }
5714 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005715 recordTrack = thread->createRecordTrack_l(client,
5716 sampleRate,
5717 format,
5718 channelMask,
5719 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005720 lSessionId,
5721 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005723 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5725 // destructor is called by the TrackBase destructor with mLock held
5726 client.clear();
5727 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728 goto Exit;
5729 }
5730
5731 // return to handle to client
5732 recordHandle = new RecordHandle(recordTrack);
5733 lStatus = NO_ERROR;
5734
5735Exit:
5736 if (status) {
5737 *status = lStatus;
5738 }
5739 return recordHandle;
5740}
5741
5742// ----------------------------------------------------------------------------
5743
5744AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5745 : BnAudioRecord(),
5746 mRecordTrack(recordTrack)
5747{
5748}
5749
5750AudioFlinger::RecordHandle::~RecordHandle() {
5751 stop();
5752}
5753
Glenn Kasten90716c52012-01-26 13:40:12 -08005754sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5755 return mRecordTrack->getCblk();
5756}
5757
Glenn Kasten3acbd052012-02-28 10:39:56 -08005758status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005759 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005760 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761}
5762
5763void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005764 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005765 mRecordTrack->stop();
5766}
5767
Mathias Agopian65ab4712010-07-14 17:59:35 -07005768status_t AudioFlinger::RecordHandle::onTransact(
5769 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5770{
5771 return BnAudioRecord::onTransact(code, data, reply, flags);
5772}
5773
5774// ----------------------------------------------------------------------------
5775
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005776AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5777 AudioStreamIn *input,
5778 uint32_t sampleRate,
5779 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005780 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005781 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005782 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005783 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5784 // mRsmpInIndex and mInputBytes set by readInputParameters()
5785 mReqChannelCount(popcount(channels)),
5786 mReqSampleRate(sampleRate)
5787 // mBytesRead is only meaningful while active, and so is cleared in start()
5788 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789{
Glenn Kasten480b4682012-02-28 12:30:08 -08005790 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005791
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792 readInputParameters();
5793}
5794
5795
5796AudioFlinger::RecordThread::~RecordThread()
5797{
5798 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005799 delete mResampler;
5800 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801}
5802
5803void AudioFlinger::RecordThread::onFirstRef()
5804{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005805 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806}
5807
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005808status_t AudioFlinger::RecordThread::readyToRun()
5809{
5810 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005811 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005812 return status;
5813}
5814
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815bool AudioFlinger::RecordThread::threadLoop()
5816{
5817 AudioBufferProvider::Buffer buffer;
5818 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005819 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005820
Eric Laurent44d98482010-09-30 16:12:31 -07005821 nsecs_t lastWarning = 0;
5822
Eric Laurentfeb0db62011-07-22 09:04:31 -07005823 acquireWakeLock();
5824
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 // start recording
5826 while (!exitPending()) {
5827
5828 processConfigEvents();
5829
5830 { // scope for mLock
5831 Mutex::Autolock _l(mLock);
5832 checkForNewParameters_l();
5833 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5834 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005835 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 mStandby = true;
5837 }
5838
5839 if (exitPending()) break;
5840
Eric Laurentfeb0db62011-07-22 09:04:31 -07005841 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005842 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 // go to sleep
5844 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005845 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005846 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005847 continue;
5848 }
5849 if (mActiveTrack != 0) {
5850 if (mActiveTrack->mState == TrackBase::PAUSING) {
5851 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005852 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853 mStandby = true;
5854 }
5855 mActiveTrack.clear();
5856 mStartStopCond.broadcast();
5857 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5858 if (mReqChannelCount != mActiveTrack->channelCount()) {
5859 mActiveTrack.clear();
5860 mStartStopCond.broadcast();
5861 } else if (mBytesRead != 0) {
5862 // record start succeeds only if first read from audio input
5863 // succeeds
5864 if (mBytesRead > 0) {
5865 mActiveTrack->mState = TrackBase::ACTIVE;
5866 } else {
5867 mActiveTrack.clear();
5868 }
5869 mStartStopCond.broadcast();
5870 }
5871 mStandby = false;
5872 }
5873 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005874 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 }
5876
5877 if (mActiveTrack != 0) {
5878 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5879 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005880 unlockEffectChains(effectChains);
5881 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005882 continue;
5883 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005884 for (size_t i = 0; i < effectChains.size(); i ++) {
5885 effectChains[i]->process_l();
5886 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005887
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005889 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005891 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 // no resampling
5893 while (framesOut) {
5894 size_t framesIn = mFrameCount - mRsmpInIndex;
5895 if (framesIn) {
5896 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5897 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5898 if (framesIn > framesOut)
5899 framesIn = framesOut;
5900 mRsmpInIndex += framesIn;
5901 framesOut -= framesIn;
5902 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005903 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 memcpy(dst, src, framesIn * mFrameSize);
5905 } else {
5906 int16_t *src16 = (int16_t *)src;
5907 int16_t *dst16 = (int16_t *)dst;
5908 if (mChannelCount == 1) {
5909 while (framesIn--) {
5910 *dst16++ = *src16;
5911 *dst16++ = *src16++;
5912 }
5913 } else {
5914 while (framesIn--) {
5915 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5916 src16 += 2;
5917 }
5918 }
5919 }
5920 }
5921 if (framesOut && mFrameCount == mRsmpInIndex) {
5922 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005923 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005924 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925 framesOut = 0;
5926 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005927 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 mRsmpInIndex = 0;
5929 }
5930 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005931 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5933 // Force input into standby so that it tries to
5934 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005935 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005936 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 }
5938 mRsmpInIndex = mFrameCount;
5939 framesOut = 0;
5940 buffer.frameCount = 0;
5941 }
5942 }
5943 }
5944 } else {
5945 // resampling
5946
5947 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5948 // alter output frame count as if we were expecting stereo samples
5949 if (mChannelCount == 1 && mReqChannelCount == 1) {
5950 framesOut >>= 1;
5951 }
5952 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5953 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5954 // are 32 bit aligned which should be always true.
5955 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005956 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957 // the resampler always outputs stereo samples: do post stereo to mono conversion
5958 int16_t *src = (int16_t *)mRsmpOutBuffer;
5959 int16_t *dst = buffer.i16;
5960 while (framesOut--) {
5961 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5962 src += 2;
5963 }
5964 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005965 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 }
5967
5968 }
Eric Laurenta011e352012-03-29 15:51:43 -07005969 if (mFramestoDrop == 0) {
5970 mActiveTrack->releaseBuffer(&buffer);
5971 } else {
5972 if (mFramestoDrop > 0) {
5973 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07005974 if (mFramestoDrop <= 0) {
5975 clearSyncStartEvent();
5976 }
5977 } else {
5978 mFramestoDrop += buffer.frameCount;
5979 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
5980 mSyncStartEvent->isCancelled()) {
5981 ALOGW("Synced record %s, session %d, trigger session %d",
5982 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
5983 mActiveTrack->sessionId(),
5984 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
5985 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07005986 }
5987 }
5988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 mActiveTrack->overflow();
5990 }
5991 // client isn't retrieving buffers fast enough
5992 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005993 if (!mActiveTrack->setOverflow()) {
5994 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005995 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005996 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005997 lastWarning = now;
5998 }
5999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 // Release the processor for a while before asking for a new buffer.
6001 // This will give the application more chance to read from the buffer and
6002 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006003 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 }
6005 }
Eric Laurentec437d82011-07-26 20:54:46 -07006006 // enable changes in effect chain
6007 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006008 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 }
6010
6011 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006012 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 }
6014 mActiveTrack.clear();
6015
6016 mStartStopCond.broadcast();
6017
Eric Laurentfeb0db62011-07-22 09:04:31 -07006018 releaseWakeLock();
6019
Steve Block3856b092011-10-20 11:56:00 +01006020 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 return false;
6022}
6023
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006024
6025sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6026 const sp<AudioFlinger::Client>& client,
6027 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006028 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006029 int channelMask,
6030 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006031 int sessionId,
6032 status_t *status)
6033{
6034 sp<RecordTrack> track;
6035 status_t lStatus;
6036
6037 lStatus = initCheck();
6038 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006039 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006040 goto Exit;
6041 }
6042
6043 { // scope for mLock
6044 Mutex::Autolock _l(mLock);
6045
6046 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006047 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006048
Glenn Kasten7378ca52012-01-20 13:44:40 -08006049 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006050 lStatus = NO_MEMORY;
6051 goto Exit;
6052 }
6053
6054 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006055 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6056 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006057 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006058 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6059 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006060 }
6061 lStatus = NO_ERROR;
6062
6063Exit:
6064 if (status) {
6065 *status = lStatus;
6066 }
6067 return track;
6068}
6069
Eric Laurenta011e352012-03-29 15:51:43 -07006070status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006071 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006072 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073{
Glenn Kasten58912562012-04-03 10:45:00 -07006074 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006075 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006077
6078 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006079 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006080 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6081 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6082 triggerSession,
6083 recordTrack->sessionId(),
6084 syncStartEventCallback,
6085 this);
Eric Laurent29864602012-05-08 18:57:51 -07006086 // Sync event can be cancelled by the trigger session if the track is not in a
6087 // compatible state in which case we start record immediately
6088 if (mSyncStartEvent->isCancelled()) {
6089 clearSyncStartEvent();
6090 } else {
6091 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6092 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6093 }
Eric Laurenta011e352012-03-29 15:51:43 -07006094 }
6095
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006097 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 if (mActiveTrack != 0) {
6099 if (recordTrack != mActiveTrack.get()) {
6100 status = -EBUSY;
6101 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6102 mActiveTrack->mState = TrackBase::ACTIVE;
6103 }
6104 return status;
6105 }
6106
6107 recordTrack->mState = TrackBase::IDLE;
6108 mActiveTrack = recordTrack;
6109 mLock.unlock();
6110 status_t status = AudioSystem::startInput(mId);
6111 mLock.lock();
6112 if (status != NO_ERROR) {
6113 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006114 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 return status;
6116 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006117 mRsmpInIndex = mFrameCount;
6118 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006119 if (mResampler != NULL) {
6120 mResampler->reset();
6121 }
6122 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006124 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 mWaitWorkCV.signal();
6126 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006127 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 mActiveTrack.clear();
6129 status = INVALID_OPERATION;
6130 goto startError;
6131 }
6132 mStartStopCond.wait(mLock);
6133 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006134 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135 status = BAD_VALUE;
6136 goto startError;
6137 }
Steve Block3856b092011-10-20 11:56:00 +01006138 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 return status;
6140 }
6141startError:
6142 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006143 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 return status;
6145}
6146
Eric Laurenta011e352012-03-29 15:51:43 -07006147void AudioFlinger::RecordThread::clearSyncStartEvent()
6148{
6149 if (mSyncStartEvent != 0) {
6150 mSyncStartEvent->cancel();
6151 }
6152 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006153 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006154}
6155
6156void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6157{
6158 sp<SyncEvent> strongEvent = event.promote();
6159
6160 if (strongEvent != 0) {
6161 RecordThread *me = (RecordThread *)strongEvent->cookie();
6162 me->handleSyncStartEvent(strongEvent);
6163 }
6164}
6165
6166void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6167{
Eric Laurent29864602012-05-08 18:57:51 -07006168 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006169 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6170 // from audio HAL
6171 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006172 }
6173}
6174
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006176 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006177 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006179 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6181 mActiveTrack->mState = TrackBase::PAUSING;
6182 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006183 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184 return;
6185 }
6186 mStartStopCond.wait(mLock);
6187 // if we have been restarted, recordTrack == mActiveTrack.get() here
6188 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6189 mLock.unlock();
6190 AudioSystem::stopInput(mId);
6191 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006192 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 }
6194 }
6195 }
6196}
6197
Eric Laurenta011e352012-03-29 15:51:43 -07006198bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6199{
6200 return false;
6201}
6202
6203status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6204{
6205 if (!isValidSyncEvent(event)) {
6206 return BAD_VALUE;
6207 }
6208
6209 Mutex::Autolock _l(mLock);
6210
6211 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6212 mTrack->setSyncEvent(event);
6213 return NO_ERROR;
6214 }
6215 return NAME_NOT_FOUND;
6216}
6217
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6219{
6220 const size_t SIZE = 256;
6221 char buffer[SIZE];
6222 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223
6224 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6225 result.append(buffer);
6226
6227 if (mActiveTrack != 0) {
6228 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006229 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230 mActiveTrack->dump(buffer, SIZE);
6231 result.append(buffer);
6232
6233 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6234 result.append(buffer);
6235 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6236 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006237 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238 result.append(buffer);
6239 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6240 result.append(buffer);
6241 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6242 result.append(buffer);
6243
6244
6245 } else {
6246 result.append("No record client\n");
6247 }
6248 write(fd, result.string(), result.size());
6249
6250 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006251 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252
6253 return NO_ERROR;
6254}
6255
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006256// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006257status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006258{
6259 size_t framesReq = buffer->frameCount;
6260 size_t framesReady = mFrameCount - mRsmpInIndex;
6261 int channelCount;
6262
6263 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006264 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006266 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6268 // Force input into standby so that it tries to
6269 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006270 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006271 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006273 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 buffer->frameCount = 0;
6275 return NOT_ENOUGH_DATA;
6276 }
6277 mRsmpInIndex = 0;
6278 framesReady = mFrameCount;
6279 }
6280
6281 if (framesReq > framesReady) {
6282 framesReq = framesReady;
6283 }
6284
6285 if (mChannelCount == 1 && mReqChannelCount == 2) {
6286 channelCount = 1;
6287 } else {
6288 channelCount = 2;
6289 }
6290 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6291 buffer->frameCount = framesReq;
6292 return NO_ERROR;
6293}
6294
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006295// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6297{
6298 mRsmpInIndex += buffer->frameCount;
6299 buffer->frameCount = 0;
6300}
6301
6302bool AudioFlinger::RecordThread::checkForNewParameters_l()
6303{
6304 bool reconfig = false;
6305
6306 while (!mNewParameters.isEmpty()) {
6307 status_t status = NO_ERROR;
6308 String8 keyValuePair = mNewParameters[0];
6309 AudioParameter param = AudioParameter(keyValuePair);
6310 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006311 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 int reqSamplingRate = mReqSampleRate;
6313 int reqChannelCount = mReqChannelCount;
6314
6315 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6316 reqSamplingRate = value;
6317 reconfig = true;
6318 }
6319 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006320 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006321 reconfig = true;
6322 }
6323 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006324 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006325 reconfig = true;
6326 }
6327 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6328 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006329 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006330 // if frame count is changed after track creation
6331 if (mActiveTrack != 0) {
6332 status = INVALID_OPERATION;
6333 } else {
6334 reconfig = true;
6335 }
6336 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006337 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6338 // forward device change to effects that have requested to be
6339 // aware of attached audio device.
6340 for (size_t i = 0; i < mEffectChains.size(); i++) {
6341 mEffectChains[i]->setDevice_l(value);
6342 }
6343 // store input device and output device but do not forward output device to audio HAL.
6344 // Note that status is ignored by the caller for output device
6345 // (see AudioFlinger::setParameters()
6346 if (value & AUDIO_DEVICE_OUT_ALL) {
6347 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6348 status = BAD_VALUE;
6349 } else {
6350 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006351 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6352 if (mTrack != NULL) {
6353 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006354 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006355 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6356 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6357 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006358 }
6359 mDevice |= (uint32_t)value;
6360 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006362 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006364 mInput->stream->common.standby(&mInput->stream->common);
6365 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6366 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006367 }
6368 if (reconfig) {
6369 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006370 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006371 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006372 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006373 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6374 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006375 status = NO_ERROR;
6376 }
6377 if (status == NO_ERROR) {
6378 readInputParameters();
6379 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6380 }
6381 }
6382 }
6383
6384 mNewParameters.removeAt(0);
6385
6386 mParamStatus = status;
6387 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006388 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6389 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006390 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391 }
6392 return reconfig;
6393}
6394
6395String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6396{
Dima Zavinfce7a472011-04-19 22:30:36 -07006397 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006398 String8 out_s8 = String8();
6399
6400 Mutex::Autolock _l(mLock);
6401 if (initCheck() != NO_ERROR) {
6402 return out_s8;
6403 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006404
Dima Zavin799a70e2011-04-18 16:57:27 -07006405 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006406 out_s8 = String8(s);
6407 free(s);
6408 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409}
6410
6411void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6412 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006413 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414
6415 switch (event) {
6416 case AudioSystem::INPUT_OPENED:
6417 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006418 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 desc.samplingRate = mSampleRate;
6420 desc.format = mFormat;
6421 desc.frameCount = mFrameCount;
6422 desc.latency = 0;
6423 param2 = &desc;
6424 break;
6425
6426 case AudioSystem::INPUT_CLOSED:
6427 default:
6428 break;
6429 }
6430 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6431}
6432
6433void AudioFlinger::RecordThread::readInputParameters()
6434{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006435 delete mRsmpInBuffer;
6436 // mRsmpInBuffer is always assigned a new[] below
6437 delete mRsmpOutBuffer;
6438 mRsmpOutBuffer = NULL;
6439 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006440 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441
Dima Zavin799a70e2011-04-18 16:57:27 -07006442 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006443 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6444 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006445 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006446 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006447 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006449 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6451
Glenn Kasten53d76db2012-03-08 12:32:47 -08006452 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 {
6454 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006455 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6456 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 if (mChannelCount == 1 && mReqChannelCount == 2) {
6458 channelCount = 1;
6459 } else {
6460 channelCount = 2;
6461 }
6462 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6463 mResampler->setSampleRate(mSampleRate);
6464 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6465 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6466
6467 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6468 if (mChannelCount == 1 && mReqChannelCount == 1) {
6469 mFrameCount >>= 1;
6470 }
6471
6472 }
6473 mRsmpInIndex = mFrameCount;
6474}
6475
6476unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6477{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006478 Mutex::Autolock _l(mLock);
6479 if (initCheck() != NO_ERROR) {
6480 return 0;
6481 }
6482
Dima Zavin799a70e2011-04-18 16:57:27 -07006483 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484}
6485
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006486uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6487{
6488 Mutex::Autolock _l(mLock);
6489 uint32_t result = 0;
6490 if (getEffectChain_l(sessionId) != 0) {
6491 result = EFFECT_SESSION;
6492 }
6493
6494 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6495 result |= TRACK_SESSION;
6496 }
6497
6498 return result;
6499}
6500
Eric Laurent59bd0da2011-08-01 09:52:20 -07006501AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6502{
6503 Mutex::Autolock _l(mLock);
6504 return mTrack;
6505}
6506
Glenn Kastenaed850d2012-01-26 09:46:34 -08006507AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006508{
6509 Mutex::Autolock _l(mLock);
6510 return mInput;
6511}
6512
6513AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6514{
6515 Mutex::Autolock _l(mLock);
6516 AudioStreamIn *input = mInput;
6517 mInput = NULL;
6518 return input;
6519}
6520
6521// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006522audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006523{
6524 if (mInput == NULL) {
6525 return NULL;
6526 }
6527 return &mInput->stream->common;
6528}
6529
6530
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531// ----------------------------------------------------------------------------
6532
Eric Laurenta4c5a552012-03-29 10:12:40 -07006533audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6534{
6535 if (!settingsAllowed()) {
6536 return 0;
6537 }
6538 Mutex::Autolock _l(mLock);
6539 return loadHwModule_l(name);
6540}
6541
6542// loadHwModule_l() must be called with AudioFlinger::mLock held
6543audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6544{
6545 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6546 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6547 ALOGW("loadHwModule() module %s already loaded", name);
6548 return mAudioHwDevs.keyAt(i);
6549 }
6550 }
6551
Eric Laurenta4c5a552012-03-29 10:12:40 -07006552 audio_hw_device_t *dev;
6553
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006554 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006555 if (rc) {
6556 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6557 return 0;
6558 }
6559
6560 mHardwareStatus = AUDIO_HW_INIT;
6561 rc = dev->init_check(dev);
6562 mHardwareStatus = AUDIO_HW_IDLE;
6563 if (rc) {
6564 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6565 return 0;
6566 }
6567
6568 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6569 (NULL != dev->set_master_volume)) {
6570 AutoMutex lock(mHardwareLock);
6571 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6572 dev->set_master_volume(dev, mMasterVolume);
6573 mHardwareStatus = AUDIO_HW_IDLE;
6574 }
6575
6576 audio_module_handle_t handle = nextUniqueId();
6577 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6578
6579 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006580 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006581
6582 return handle;
6583
6584}
6585
6586audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6587 audio_devices_t *pDevices,
6588 uint32_t *pSamplingRate,
6589 audio_format_t *pFormat,
6590 audio_channel_mask_t *pChannelMask,
6591 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006592 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593{
6594 status_t status;
6595 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006596 struct audio_config config = {
6597 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6598 channel_mask: pChannelMask ? *pChannelMask : 0,
6599 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6600 };
6601 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006602 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603
Eric Laurenta4c5a552012-03-29 10:12:40 -07006604 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6605 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006606 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006607 config.sample_rate,
6608 config.format,
6609 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006610 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611
6612 if (pDevices == NULL || *pDevices == 0) {
6613 return 0;
6614 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006615
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 Mutex::Autolock _l(mLock);
6617
Eric Laurenta4c5a552012-03-29 10:12:40 -07006618 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006619 if (outHwDev == NULL)
6620 return 0;
6621
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006622 audio_io_handle_t id = nextUniqueId();
6623
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006624 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006625
6626 status = outHwDev->open_output_stream(outHwDev,
6627 id,
6628 *pDevices,
6629 (audio_output_flags_t)flags,
6630 &config,
6631 &outStream);
6632
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006633 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006634 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006635 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006636 config.sample_rate,
6637 config.format,
6638 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639 status);
6640
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006641 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006642 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006643
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006644 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006645 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6646 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006647 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006648 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649 } else {
6650 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006651 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652 }
6653 mPlaybackThreads.add(id, thread);
6654
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006655 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6656 if (pFormat != NULL) *pFormat = config.format;
6657 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006658 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659
6660 // notify client processes of the new output creation
6661 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006662
6663 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006664 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006665 ALOGI("Using module %d has the primary audio interface", module);
6666 mPrimaryHardwareDev = outHwDev;
6667
6668 AutoMutex lock(mHardwareLock);
6669 mHardwareStatus = AUDIO_HW_SET_MODE;
6670 outHwDev->set_mode(outHwDev, mMode);
6671
6672 // Determine the level of master volume support the primary audio HAL has,
6673 // and set the initial master volume at the same time.
6674 float initialVolume = 1.0;
6675 mMasterVolumeSupportLvl = MVS_NONE;
6676
6677 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6678 if ((NULL != outHwDev->get_master_volume) &&
6679 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6680 mMasterVolumeSupportLvl = MVS_FULL;
6681 } else {
6682 mMasterVolumeSupportLvl = MVS_SETONLY;
6683 initialVolume = 1.0;
6684 }
6685
6686 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6687 if ((NULL == outHwDev->set_master_volume) ||
6688 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6689 mMasterVolumeSupportLvl = MVS_NONE;
6690 }
6691 // now that we have a primary device, initialize master volume on other devices
6692 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6693 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6694
6695 if ((dev != mPrimaryHardwareDev) &&
6696 (NULL != dev->set_master_volume)) {
6697 dev->set_master_volume(dev, initialVolume);
6698 }
6699 }
6700 mHardwareStatus = AUDIO_HW_IDLE;
6701 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6702 ? initialVolume
6703 : 1.0;
6704 mMasterVolume = initialVolume;
6705 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 return id;
6707 }
6708
6709 return 0;
6710}
6711
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006712audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6713 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714{
6715 Mutex::Autolock _l(mLock);
6716 MixerThread *thread1 = checkMixerThread_l(output1);
6717 MixerThread *thread2 = checkMixerThread_l(output2);
6718
6719 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006720 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721 return 0;
6722 }
6723
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006724 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6726 thread->addOutputTrack(thread2);
6727 mPlaybackThreads.add(id, thread);
6728 // notify client processes of the new output creation
6729 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6730 return id;
6731}
6732
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006733status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734{
6735 // keep strong reference on the playback thread so that
6736 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006737 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006738 {
6739 Mutex::Autolock _l(mLock);
6740 thread = checkPlaybackThread_l(output);
6741 if (thread == NULL) {
6742 return BAD_VALUE;
6743 }
6744
Steve Block3856b092011-10-20 11:56:00 +01006745 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006747 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006748 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006749 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6751 dupThread->removeOutputTrack((MixerThread *)thread.get());
6752 }
6753 }
6754 }
Glenn Kastena1117922012-01-26 10:53:32 -08006755 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756 mPlaybackThreads.removeItem(output);
6757 }
6758 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006759 // The thread entity (active unit of execution) is no longer running here,
6760 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006762 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006763 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006764 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006765 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006766 out->hwDev->close_output_stream(out->hwDev, out->stream);
6767 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768 }
6769 return NO_ERROR;
6770}
6771
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006772status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773{
6774 Mutex::Autolock _l(mLock);
6775 PlaybackThread *thread = checkPlaybackThread_l(output);
6776
6777 if (thread == NULL) {
6778 return BAD_VALUE;
6779 }
6780
Steve Block3856b092011-10-20 11:56:00 +01006781 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006782 thread->suspend();
6783
6784 return NO_ERROR;
6785}
6786
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006787status_t AudioFlinger::restoreOutput(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("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797
6798 thread->restore();
6799
6800 return NO_ERROR;
6801}
6802
Eric Laurenta4c5a552012-03-29 10:12:40 -07006803audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6804 audio_devices_t *pDevices,
6805 uint32_t *pSamplingRate,
6806 audio_format_t *pFormat,
6807 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808{
6809 status_t status;
6810 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006811 struct audio_config config = {
6812 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6813 channel_mask: pChannelMask ? *pChannelMask : 0,
6814 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6815 };
6816 uint32_t reqSamplingRate = config.sample_rate;
6817 audio_format_t reqFormat = config.format;
6818 audio_channel_mask_t reqChannels = config.channel_mask;
6819 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006820 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821
6822 if (pDevices == NULL || *pDevices == 0) {
6823 return 0;
6824 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006825
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 Mutex::Autolock _l(mLock);
6827
Eric Laurenta4c5a552012-03-29 10:12:40 -07006828 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006829 if (inHwDev == NULL)
6830 return 0;
6831
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006832 audio_io_handle_t id = nextUniqueId();
6833
6834 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006835 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006836 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006837 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006838 config.sample_rate,
6839 config.format,
6840 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 status);
6842
6843 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6844 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6845 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006846 if (status == BAD_VALUE &&
6847 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6848 (config.sample_rate <= 2 * reqSamplingRate) &&
6849 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006850 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006851 inStream = NULL;
6852 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 }
6854
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006855 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006856 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6857
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006858 // Start record thread
6859 // RecorThread require both input and output device indication to forward to audio
6860 // pre processing modules
6861 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6862 thread = new RecordThread(this,
6863 input,
6864 reqSamplingRate,
6865 reqChannels,
6866 id,
6867 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006869 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006870 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006871 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006872 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873
Dima Zavin799a70e2011-04-18 16:57:27 -07006874 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875
6876 // notify client processes of the new input creation
6877 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6878 return id;
6879 }
6880
6881 return 0;
6882}
6883
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006884status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885{
6886 // keep strong reference on the record thread so that
6887 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006888 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 {
6890 Mutex::Autolock _l(mLock);
6891 thread = checkRecordThread_l(input);
6892 if (thread == NULL) {
6893 return BAD_VALUE;
6894 }
6895
Steve Block3856b092011-10-20 11:56:00 +01006896 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006897 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898 mRecordThreads.removeItem(input);
6899 }
6900 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006901 // The thread entity (active unit of execution) is no longer running here,
6902 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006904 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006905 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006906 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006907 in->hwDev->close_input_stream(in->hwDev, in->stream);
6908 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909
6910 return NO_ERROR;
6911}
6912
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006913status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914{
6915 Mutex::Autolock _l(mLock);
6916 MixerThread *dstThread = checkMixerThread_l(output);
6917 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006918 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919 return BAD_VALUE;
6920 }
6921
Steve Block3856b092011-10-20 11:56:00 +01006922 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6924
6925 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6926 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006927 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928 MixerThread *srcThread = (MixerThread *)thread;
6929 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930 }
Eric Laurentde070132010-07-13 04:45:46 -07006931 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932
6933 return NO_ERROR;
6934}
6935
6936
6937int AudioFlinger::newAudioSessionId()
6938{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006939 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006940}
6941
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006942void AudioFlinger::acquireAudioSessionId(int audioSession)
6943{
6944 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006945 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006946 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006947 size_t num = mAudioSessionRefs.size();
6948 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006949 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006950 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6951 ref->mCnt++;
6952 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006953 return;
6954 }
6955 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006956 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6957 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006958}
6959
6960void AudioFlinger::releaseAudioSessionId(int audioSession)
6961{
6962 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006963 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006964 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006965 size_t num = mAudioSessionRefs.size();
6966 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006967 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006968 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6969 ref->mCnt--;
6970 ALOGV(" decremented refcount to %d", ref->mCnt);
6971 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006972 mAudioSessionRefs.removeAt(i);
6973 delete ref;
6974 purgeStaleEffects_l();
6975 }
6976 return;
6977 }
6978 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006979 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006980}
6981
6982void AudioFlinger::purgeStaleEffects_l() {
6983
Steve Block3856b092011-10-20 11:56:00 +01006984 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006985
6986 Vector< sp<EffectChain> > chains;
6987
6988 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6989 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6990 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6991 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006992 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6993 chains.push(ec);
6994 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006995 }
6996 }
6997 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6998 sp<RecordThread> t = mRecordThreads.valueAt(i);
6999 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7000 sp<EffectChain> ec = t->mEffectChains[j];
7001 chains.push(ec);
7002 }
7003 }
7004
7005 for (size_t i = 0; i < chains.size(); i++) {
7006 sp<EffectChain> ec = chains[i];
7007 int sessionid = ec->sessionId();
7008 sp<ThreadBase> t = ec->mThread.promote();
7009 if (t == 0) {
7010 continue;
7011 }
7012 size_t numsessionrefs = mAudioSessionRefs.size();
7013 bool found = false;
7014 for (size_t k = 0; k < numsessionrefs; k++) {
7015 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007016 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007017 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007018 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007019 found = true;
7020 break;
7021 }
7022 }
7023 if (!found) {
7024 // remove all effects from the chain
7025 while (ec->mEffects.size()) {
7026 sp<EffectModule> effect = ec->mEffects[0];
7027 effect->unPin();
7028 Mutex::Autolock _l (t->mLock);
7029 t->removeEffect_l(effect);
7030 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7031 sp<EffectHandle> handle = effect->mHandles[j].promote();
7032 if (handle != 0) {
7033 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007034 if (handle->mHasControl && handle->mEnabled) {
7035 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7036 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007037 }
7038 }
7039 AudioSystem::unregisterEffect(effect->id());
7040 }
7041 }
7042 }
7043 return;
7044}
7045
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007047AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007048{
Glenn Kastena1117922012-01-26 10:53:32 -08007049 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050}
7051
7052// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007053AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054{
7055 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007056 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057}
7058
7059// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007060AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061{
Glenn Kastena1117922012-01-26 10:53:32 -08007062 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063}
7064
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007065uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007067 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068}
7069
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007070AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007071{
7072 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7073 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007074 AudioStreamOut *output = thread->getOutput();
7075 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007076 return thread;
7077 }
7078 }
7079 return NULL;
7080}
7081
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007082uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007083{
7084 PlaybackThread *thread = primaryPlaybackThread_l();
7085
7086 if (thread == NULL) {
7087 return 0;
7088 }
7089
7090 return thread->device();
7091}
7092
Eric Laurenta011e352012-03-29 15:51:43 -07007093sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7094 int triggerSession,
7095 int listenerSession,
7096 sync_event_callback_t callBack,
7097 void *cookie)
7098{
7099 Mutex::Autolock _l(mLock);
7100
7101 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7102 status_t playStatus = NAME_NOT_FOUND;
7103 status_t recStatus = NAME_NOT_FOUND;
7104 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7105 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7106 if (playStatus == NO_ERROR) {
7107 return event;
7108 }
7109 }
7110 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7111 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7112 if (recStatus == NO_ERROR) {
7113 return event;
7114 }
7115 }
7116 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7117 mPendingSyncEvents.add(event);
7118 } else {
7119 ALOGV("createSyncEvent() invalid event %d", event->type());
7120 event.clear();
7121 }
7122 return event;
7123}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007124
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125// ----------------------------------------------------------------------------
7126// Effect management
7127// ----------------------------------------------------------------------------
7128
7129
Glenn Kastenf587ba52012-01-26 16:25:10 -08007130status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131{
7132 Mutex::Autolock _l(mLock);
7133 return EffectQueryNumberEffects(numEffects);
7134}
7135
Glenn Kastenf587ba52012-01-26 16:25:10 -08007136status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137{
7138 Mutex::Autolock _l(mLock);
7139 return EffectQueryEffect(index, descriptor);
7140}
7141
Glenn Kasten5e92a782012-01-30 07:40:52 -08007142status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007143 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144{
7145 Mutex::Autolock _l(mLock);
7146 return EffectGetDescriptor(pUuid, descriptor);
7147}
7148
7149
Mathias Agopian65ab4712010-07-14 17:59:35 -07007150sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7151 effect_descriptor_t *pDesc,
7152 const sp<IEffectClient>& effectClient,
7153 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007154 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155 int sessionId,
7156 status_t *status,
7157 int *id,
7158 int *enabled)
7159{
7160 status_t lStatus = NO_ERROR;
7161 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007164 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007165 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166
7167 if (pDesc == NULL) {
7168 lStatus = BAD_VALUE;
7169 goto Exit;
7170 }
7171
Eric Laurent84e9a102010-09-23 16:10:16 -07007172 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007173 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007174 lStatus = PERMISSION_DENIED;
7175 goto Exit;
7176 }
7177
Dima Zavinfce7a472011-04-19 22:30:36 -07007178 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007179 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007180 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007181 lStatus = PERMISSION_DENIED;
7182 goto Exit;
7183 }
7184
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007185 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007186 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007187 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007188 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007189 lStatus = BAD_VALUE;
7190 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007191 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007192 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007193 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007194 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007195 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007196 }
7197 }
7198
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199 {
7200 Mutex::Autolock _l(mLock);
7201
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202
7203 if (!EffectIsNullUuid(&pDesc->uuid)) {
7204 // if uuid is specified, request effect descriptor
7205 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7206 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007207 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 goto Exit;
7209 }
7210 } else {
7211 // if uuid is not specified, look for an available implementation
7212 // of the required type in effect factory
7213 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007214 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007215 lStatus = BAD_VALUE;
7216 goto Exit;
7217 }
7218 uint32_t numEffects = 0;
7219 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007220 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221 bool found = false;
7222
7223 lStatus = EffectQueryNumberEffects(&numEffects);
7224 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007225 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 goto Exit;
7227 }
7228 for (uint32_t i = 0; i < numEffects; i++) {
7229 lStatus = EffectQueryEffect(i, &desc);
7230 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007231 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007232 continue;
7233 }
7234 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7235 // If matching type found save effect descriptor. If the session is
7236 // 0 and the effect is not auxiliary, continue enumeration in case
7237 // an auxiliary version of this effect type is available
7238 found = true;
7239 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007240 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7242 break;
7243 }
7244 }
7245 }
7246 if (!found) {
7247 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007248 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249 goto Exit;
7250 }
7251 // For same effect type, chose auxiliary version over insert version if
7252 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007253 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7255 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7256 }
7257 }
7258
7259 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007260 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7262 lStatus = INVALID_OPERATION;
7263 goto Exit;
7264 }
7265
Eric Laurent59255e42011-07-27 19:49:51 -07007266 // check recording permission for visualizer
7267 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7268 !recordingAllowed()) {
7269 lStatus = PERMISSION_DENIED;
7270 goto Exit;
7271 }
7272
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 // return effect descriptor
7274 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7275
7276 // If output is not specified try to find a matching audio session ID in one of the
7277 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007278 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7279 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007280 // Note: io is never 0 when creating an effect on an input
7281 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007282 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007283 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7284 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007285 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007286 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007289 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007290 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7291 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7292 io = mRecordThreads.keyAt(i);
7293 break;
7294 }
7295 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007296 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007297 // If no output thread contains the requested session ID, default to
7298 // first output. The effect chain will be moved to the correct output
7299 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007300 if (io == 0 && mPlaybackThreads.size()) {
7301 io = mPlaybackThreads.keyAt(0);
7302 }
Steve Block3856b092011-10-20 11:56:00 +01007303 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 }
7305 ThreadBase *thread = checkRecordThread_l(io);
7306 if (thread == NULL) {
7307 thread = checkPlaybackThread_l(io);
7308 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007309 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007310 lStatus = BAD_VALUE;
7311 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007314
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007315 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007317 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007318 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7319 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 if (handle != 0 && id != NULL) {
7321 *id = handle->id();
7322 }
7323 }
7324
7325Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007326 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327 *status = lStatus;
7328 }
7329 return handle;
7330}
7331
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007332status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7333 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007334{
Steve Block3856b092011-10-20 11:56:00 +01007335 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007336 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007337 Mutex::Autolock _l(mLock);
7338 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007339 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007340 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 }
Eric Laurentde070132010-07-13 04:45:46 -07007342 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7343 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007344 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007345 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 }
Eric Laurentde070132010-07-13 04:45:46 -07007347 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7348 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007349 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007350 return BAD_VALUE;
7351 }
7352
7353 Mutex::Autolock _dl(dstThread->mLock);
7354 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007355 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007356
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357 return NO_ERROR;
7358}
7359
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007360// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007361status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007362 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007363 AudioFlinger::PlaybackThread *dstThread,
7364 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007365{
Steve Block3856b092011-10-20 11:56:00 +01007366 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007367 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007368
Eric Laurent59255e42011-07-27 19:49:51 -07007369 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007370 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007371 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007372 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007373 return INVALID_OPERATION;
7374 }
7375
Eric Laurent39e94f82010-07-28 01:32:47 -07007376 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007377 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007378 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007379 // removed.
7380 srcThread->removeEffectChain_l(chain);
7381
7382 // transfer all effects one by one so that new effect chain is created on new thread with
7383 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007384 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007385 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007386 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007387 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7388 while (effect != 0) {
7389 srcThread->removeEffect_l(effect);
7390 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007391 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7392 if (effect->state() == EffectModule::ACTIVE ||
7393 effect->state() == EffectModule::STOPPING) {
7394 effect->start();
7395 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007396 // if the move request is not received from audio policy manager, the effect must be
7397 // re-registered with the new strategy and output
7398 if (dstChain == 0) {
7399 dstChain = effect->chain().promote();
7400 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007401 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007402 srcThread->addEffect_l(effect);
7403 return NO_INIT;
7404 }
7405 strategy = dstChain->strategy();
7406 }
7407 if (reRegister) {
7408 AudioSystem::unregisterEffect(effect->id());
7409 AudioSystem::registerEffect(&effect->desc(),
7410 dstOutput,
7411 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007412 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007413 effect->id());
7414 }
Eric Laurentde070132010-07-13 04:45:46 -07007415 effect = chain->getEffectFromId_l(0);
7416 }
7417
7418 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419}
7420
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007421
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007423sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 const sp<AudioFlinger::Client>& client,
7425 const sp<IEffectClient>& effectClient,
7426 int32_t priority,
7427 int sessionId,
7428 effect_descriptor_t *desc,
7429 int *enabled,
7430 status_t *status
7431 )
7432{
7433 sp<EffectModule> effect;
7434 sp<EffectHandle> handle;
7435 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007437 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438 bool effectCreated = false;
7439 bool effectRegistered = false;
7440
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007441 lStatus = initCheck();
7442 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007443 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444 goto Exit;
7445 }
7446
7447 // Do not allow effects with session ID 0 on direct output or duplicating threads
7448 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007449 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007450 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007451 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 lStatus = BAD_VALUE;
7453 goto Exit;
7454 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007455 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007456 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007457 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007458 desc->name, desc->flags, mType);
7459 lStatus = BAD_VALUE;
7460 goto Exit;
7461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462
Steve Block3856b092011-10-20 11:56:00 +01007463 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007464
7465 { // scope for mLock
7466 Mutex::Autolock _l(mLock);
7467
7468 // check for existing effect chain with the requested audio session
7469 chain = getEffectChain_l(sessionId);
7470 if (chain == 0) {
7471 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007472 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473 chain = new EffectChain(this, sessionId);
7474 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007475 chain->setStrategy(getStrategyForSession_l(sessionId));
7476 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007477 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007478 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479 }
7480
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007481 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007482
7483 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007484 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007486 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487 if (lStatus != NO_ERROR) {
7488 goto Exit;
7489 }
7490 effectRegistered = true;
7491 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007492 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007493 lStatus = effect->status();
7494 if (lStatus != NO_ERROR) {
7495 goto Exit;
7496 }
Eric Laurentcab11242010-07-15 12:50:15 -07007497 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007498 if (lStatus != NO_ERROR) {
7499 goto Exit;
7500 }
7501 effectCreated = true;
7502
7503 effect->setDevice(mDevice);
7504 effect->setMode(mAudioFlinger->getMode());
7505 }
7506 // create effect handle and connect it to effect module
7507 handle = new EffectHandle(effect, client, effectClient, priority);
7508 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007509 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007510 *enabled = (int)effect->isEnabled();
7511 }
7512 }
7513
7514Exit:
7515 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007516 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007517 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007518 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519 }
7520 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007521 AudioSystem::unregisterEffect(effect->id());
7522 }
7523 if (chainCreated) {
7524 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525 }
7526 handle.clear();
7527 }
7528
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007529 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007530 *status = lStatus;
7531 }
7532 return handle;
7533}
7534
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007535sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7536{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007537 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007538 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007539}
7540
Eric Laurentde070132010-07-13 04:45:46 -07007541// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7542// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007543status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007544{
7545 // check for existing effect chain with the requested audio session
7546 int sessionId = effect->sessionId();
7547 sp<EffectChain> chain = getEffectChain_l(sessionId);
7548 bool chainCreated = false;
7549
7550 if (chain == 0) {
7551 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007552 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007553 chain = new EffectChain(this, sessionId);
7554 addEffectChain_l(chain);
7555 chain->setStrategy(getStrategyForSession_l(sessionId));
7556 chainCreated = true;
7557 }
Steve Block3856b092011-10-20 11:56:00 +01007558 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007559
7560 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007561 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007562 this, effect->desc().name, chain.get());
7563 return BAD_VALUE;
7564 }
7565
7566 status_t status = chain->addEffect_l(effect);
7567 if (status != NO_ERROR) {
7568 if (chainCreated) {
7569 removeEffectChain_l(chain);
7570 }
7571 return status;
7572 }
7573
7574 effect->setDevice(mDevice);
7575 effect->setMode(mAudioFlinger->getMode());
7576 return NO_ERROR;
7577}
7578
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007579void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007580
Steve Block3856b092011-10-20 11:56:00 +01007581 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007583 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7584 detachAuxEffect_l(effect->id());
7585 }
7586
7587 sp<EffectChain> chain = effect->chain().promote();
7588 if (chain != 0) {
7589 // remove effect chain if removing last effect
7590 if (chain->removeEffect_l(effect) == 0) {
7591 removeEffectChain_l(chain);
7592 }
7593 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007594 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007595 }
7596}
7597
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007598void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007599 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007600{
7601 effectChains = mEffectChains;
7602 for (size_t i = 0; i < mEffectChains.size(); i++) {
7603 mEffectChains[i]->lock();
7604 }
7605}
7606
7607void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007608 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007609{
7610 for (size_t i = 0; i < effectChains.size(); i++) {
7611 effectChains[i]->unlock();
7612 }
7613}
7614
7615sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7616{
7617 Mutex::Autolock _l(mLock);
7618 return getEffectChain_l(sessionId);
7619}
7620
7621sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7622{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007623 size_t size = mEffectChains.size();
7624 for (size_t i = 0; i < size; i++) {
7625 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007626 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007627 }
7628 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007629 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007630}
7631
Glenn Kastenf78aee72012-01-04 11:00:47 -08007632void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007633{
7634 Mutex::Autolock _l(mLock);
7635 size_t size = mEffectChains.size();
7636 for (size_t i = 0; i < size; i++) {
7637 mEffectChains[i]->setMode_l(mode);
7638 }
7639}
7640
7641void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007642 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007643 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007644
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007646 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647 // delete the effect module if removing last handle on it
7648 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007649 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007650 removeEffect_l(effect);
7651 AudioSystem::unregisterEffect(effect->id());
7652 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007653 }
7654}
7655
7656status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7657{
7658 int session = chain->sessionId();
7659 int16_t *buffer = mMixBuffer;
7660 bool ownsBuffer = false;
7661
Steve Block3856b092011-10-20 11:56:00 +01007662 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 if (session > 0) {
7664 // Only one effect chain can be present in direct output thread and it uses
7665 // the mix buffer as input
7666 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007667 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007668 buffer = new int16_t[numSamples];
7669 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007670 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671 ownsBuffer = true;
7672 }
7673
7674 // Attach all tracks with same session ID to this chain.
7675 for (size_t i = 0; i < mTracks.size(); ++i) {
7676 sp<Track> track = mTracks[i];
7677 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007678 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007680 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007681 }
7682 }
7683
7684 // indicate all active tracks in the chain
7685 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7686 sp<Track> track = mActiveTracks[i].promote();
7687 if (track == 0) continue;
7688 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007689 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007690 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691 }
7692 }
7693 }
7694
7695 chain->setInBuffer(buffer, ownsBuffer);
7696 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007697 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007698 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007699 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7700 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007702 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7703 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007704 // Effect chain for other sessions are inserted at beginning of effect
7705 // chains list to be processed before output mix effects. Relative order between other
7706 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 size_t size = mEffectChains.size();
7708 size_t i = 0;
7709 for (i = 0; i < size; i++) {
7710 if (mEffectChains[i]->sessionId() < session) break;
7711 }
7712 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007713 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007714
7715 return NO_ERROR;
7716}
7717
7718size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7719{
7720 int session = chain->sessionId();
7721
Steve Block3856b092011-10-20 11:56:00 +01007722 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007723
7724 for (size_t i = 0; i < mEffectChains.size(); i++) {
7725 if (chain == mEffectChains[i]) {
7726 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007727 // detach all active tracks from the chain
7728 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7729 sp<Track> track = mActiveTracks[i].promote();
7730 if (track == 0) continue;
7731 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007732 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007733 chain.get(), session);
7734 chain->decActiveTrackCnt();
7735 }
7736 }
7737
Mathias Agopian65ab4712010-07-14 17:59:35 -07007738 // detach all tracks with same session ID from this chain
7739 for (size_t i = 0; i < mTracks.size(); ++i) {
7740 sp<Track> track = mTracks[i];
7741 if (session == track->sessionId()) {
7742 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007743 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 }
7745 }
Eric Laurentde070132010-07-13 04:45:46 -07007746 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007747 }
7748 }
7749 return mEffectChains.size();
7750}
7751
Eric Laurentde070132010-07-13 04:45:46 -07007752status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7753 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754{
7755 Mutex::Autolock _l(mLock);
7756 return attachAuxEffect_l(track, EffectId);
7757}
7758
Eric Laurentde070132010-07-13 04:45:46 -07007759status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7760 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761{
7762 status_t status = NO_ERROR;
7763
7764 if (EffectId == 0) {
7765 track->setAuxBuffer(0, NULL);
7766 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007767 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7768 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769 if (effect != 0) {
7770 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7771 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7772 } else {
7773 status = INVALID_OPERATION;
7774 }
7775 } else {
7776 status = BAD_VALUE;
7777 }
7778 }
7779 return status;
7780}
7781
7782void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7783{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007784 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785 sp<Track> track = mTracks[i];
7786 if (track->auxEffectId() == effectId) {
7787 attachAuxEffect_l(track, 0);
7788 }
7789 }
7790}
7791
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007792status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7793{
7794 // only one chain per input thread
7795 if (mEffectChains.size() != 0) {
7796 return INVALID_OPERATION;
7797 }
Steve Block3856b092011-10-20 11:56:00 +01007798 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007799
7800 chain->setInBuffer(NULL);
7801 chain->setOutBuffer(NULL);
7802
Eric Laurent59255e42011-07-27 19:49:51 -07007803 checkSuspendOnAddEffectChain_l(chain);
7804
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007805 mEffectChains.add(chain);
7806
7807 return NO_ERROR;
7808}
7809
7810size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7811{
Steve Block3856b092011-10-20 11:56:00 +01007812 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007813 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007814 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7815 chain.get(), mEffectChains.size(), this);
7816 if (mEffectChains.size() == 1) {
7817 mEffectChains.removeAt(0);
7818 }
7819 return 0;
7820}
7821
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822// ----------------------------------------------------------------------------
7823// EffectModule implementation
7824// ----------------------------------------------------------------------------
7825
7826#undef LOG_TAG
7827#define LOG_TAG "AudioFlinger::EffectModule"
7828
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007829AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007830 const wp<AudioFlinger::EffectChain>& chain,
7831 effect_descriptor_t *desc,
7832 int id,
7833 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007834 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007835 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836{
Steve Block3856b092011-10-20 11:56:00 +01007837 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007839 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007840 return;
7841 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842
7843 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7844
7845 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007846 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007847
7848 if (mStatus != NO_ERROR) {
7849 return;
7850 }
7851 lStatus = init();
7852 if (lStatus < 0) {
7853 mStatus = lStatus;
7854 goto Error;
7855 }
7856
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007857 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7858 mPinned = true;
7859 }
Steve Block3856b092011-10-20 11:56:00 +01007860 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 return;
7862Error:
7863 EffectRelease(mEffectInterface);
7864 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007865 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866}
7867
7868AudioFlinger::EffectModule::~EffectModule()
7869{
Steve Block3856b092011-10-20 11:56:00 +01007870 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007872 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7873 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7874 sp<ThreadBase> thread = mThread.promote();
7875 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007876 audio_stream_t *stream = thread->stream();
7877 if (stream != NULL) {
7878 stream->remove_audio_effect(stream, mEffectInterface);
7879 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007880 }
7881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882 // release effect engine
7883 EffectRelease(mEffectInterface);
7884 }
7885}
7886
Glenn Kasten435dbe62012-01-30 10:15:48 -08007887status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007888{
7889 status_t status;
7890
7891 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892 int priority = handle->priority();
7893 size_t size = mHandles.size();
7894 sp<EffectHandle> h;
7895 size_t i;
7896 for (i = 0; i < size; i++) {
7897 h = mHandles[i].promote();
7898 if (h == 0) continue;
7899 if (h->priority() <= priority) break;
7900 }
7901 // if inserted in first place, move effect control from previous owner to this handle
7902 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007903 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007905 enabled = h->enabled();
7906 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907 }
Eric Laurent59255e42011-07-27 19:49:51 -07007908 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909 status = NO_ERROR;
7910 } else {
7911 status = ALREADY_EXISTS;
7912 }
Steve Block3856b092011-10-20 11:56:00 +01007913 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 mHandles.insertAt(handle, i);
7915 return status;
7916}
7917
7918size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7919{
7920 Mutex::Autolock _l(mLock);
7921 size_t size = mHandles.size();
7922 size_t i;
7923 for (i = 0; i < size; i++) {
7924 if (mHandles[i] == handle) break;
7925 }
7926 if (i == size) {
7927 return size;
7928 }
Steve Block3856b092011-10-20 11:56:00 +01007929 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007930
7931 bool enabled = false;
7932 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007933 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007934 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007935 enabled = hdl->enabled();
7936 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937 mHandles.removeAt(i);
7938 size = mHandles.size();
7939 // if removed from first place, move effect control from this handle to next in line
7940 if (i == 0 && size != 0) {
7941 sp<EffectHandle> h = mHandles[0].promote();
7942 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007943 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 }
7945 }
7946
Eric Laurentec437d82011-07-26 20:54:46 -07007947 // Prevent calls to process() and other functions on effect interface from now on.
7948 // The effect engine will be released by the destructor when the last strong reference on
7949 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007950 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007951 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007952 }
7953
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954 return size;
7955}
7956
Eric Laurent59255e42011-07-27 19:49:51 -07007957sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7958{
7959 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007960 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007961}
7962
Glenn Kasten58123c32012-02-03 10:32:24 -08007963void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007965 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007966 // keep a strong reference on this EffectModule to avoid calling the
7967 // destructor before we exit
7968 sp<EffectModule> keep(this);
7969 {
7970 sp<ThreadBase> thread = mThread.promote();
7971 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007972 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007973 }
7974 }
7975}
7976
7977void AudioFlinger::EffectModule::updateState() {
7978 Mutex::Autolock _l(mLock);
7979
7980 switch (mState) {
7981 case RESTART:
7982 reset_l();
7983 // FALL THROUGH
7984
7985 case STARTING:
7986 // clear auxiliary effect input buffer for next accumulation
7987 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7988 memset(mConfig.inputCfg.buffer.raw,
7989 0,
7990 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7991 }
7992 start_l();
7993 mState = ACTIVE;
7994 break;
7995 case STOPPING:
7996 stop_l();
7997 mDisableWaitCnt = mMaxDisableWaitCnt;
7998 mState = STOPPED;
7999 break;
8000 case STOPPED:
8001 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8002 // turn off sequence.
8003 if (--mDisableWaitCnt == 0) {
8004 reset_l();
8005 mState = IDLE;
8006 }
8007 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008008 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009 break;
8010 }
8011}
8012
8013void AudioFlinger::EffectModule::process()
8014{
8015 Mutex::Autolock _l(mLock);
8016
Eric Laurentec437d82011-07-26 20:54:46 -07008017 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 mConfig.inputCfg.buffer.raw == NULL ||
8019 mConfig.outputCfg.buffer.raw == NULL) {
8020 return;
8021 }
8022
Eric Laurent8f45bd72010-08-31 13:50:07 -07008023 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8025 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008026 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008028 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008029 }
8030
8031 // do the actual processing in the effect engine
8032 int ret = (*mEffectInterface)->process(mEffectInterface,
8033 &mConfig.inputCfg.buffer,
8034 &mConfig.outputCfg.buffer);
8035
8036 // force transition to IDLE state when engine is ready
8037 if (mState == STOPPED && ret == -ENODATA) {
8038 mDisableWaitCnt = 1;
8039 }
8040
8041 // clear auxiliary effect input buffer for next accumulation
8042 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008043 memset(mConfig.inputCfg.buffer.raw, 0,
8044 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045 }
8046 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008047 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8048 // If an insert effect is idle and input buffer is different from output buffer,
8049 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008050 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008051 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008052 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8053 int16_t *in = mConfig.inputCfg.buffer.s16;
8054 int16_t *out = mConfig.outputCfg.buffer.s16;
8055 for (size_t i = 0; i < frameCnt; i++) {
8056 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008058 }
8059 }
8060}
8061
8062void AudioFlinger::EffectModule::reset_l()
8063{
8064 if (mEffectInterface == NULL) {
8065 return;
8066 }
8067 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8068}
8069
8070status_t AudioFlinger::EffectModule::configure()
8071{
8072 uint32_t channels;
8073 if (mEffectInterface == NULL) {
8074 return NO_INIT;
8075 }
8076
8077 sp<ThreadBase> thread = mThread.promote();
8078 if (thread == 0) {
8079 return DEAD_OBJECT;
8080 }
8081
8082 // TODO: handle configuration of effects replacing track process
8083 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008084 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008085 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008086 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008087 }
8088
8089 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008090 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091 } else {
8092 mConfig.inputCfg.channels = channels;
8093 }
8094 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008095 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8096 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008097 mConfig.inputCfg.samplingRate = thread->sampleRate();
8098 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8099 mConfig.inputCfg.bufferProvider.cookie = NULL;
8100 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8101 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8102 mConfig.outputCfg.bufferProvider.cookie = NULL;
8103 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8104 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8105 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8106 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008107 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008108 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008109 // - in other sessions:
8110 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8111 // other effect: overwrites output buffer: input buffer == output buffer
8112 // Auxiliary effect:
8113 // accumulates in output buffer: input buffer != output buffer
8114 // Therefore: accumulate <=> input buffer != output buffer
8115 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8116 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8117 } else {
8118 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8119 }
8120 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8121 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8122 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8123 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8124
Steve Block3856b092011-10-20 11:56:00 +01008125 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008126 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8127
Mathias Agopian65ab4712010-07-14 17:59:35 -07008128 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008129 uint32_t size = sizeof(int);
8130 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008131 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008132 sizeof(effect_config_t),
8133 &mConfig,
8134 &size,
8135 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008136 if (status == 0) {
8137 status = cmdStatus;
8138 }
8139
8140 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8141 (1000 * mConfig.outputCfg.buffer.frameCount);
8142
8143 return status;
8144}
8145
8146status_t AudioFlinger::EffectModule::init()
8147{
8148 Mutex::Autolock _l(mLock);
8149 if (mEffectInterface == NULL) {
8150 return NO_INIT;
8151 }
8152 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008153 uint32_t size = sizeof(status_t);
8154 status_t status = (*mEffectInterface)->command(mEffectInterface,
8155 EFFECT_CMD_INIT,
8156 0,
8157 NULL,
8158 &size,
8159 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008160 if (status == 0) {
8161 status = cmdStatus;
8162 }
8163 return status;
8164}
8165
Eric Laurentec35a142011-10-05 17:42:25 -07008166status_t AudioFlinger::EffectModule::start()
8167{
8168 Mutex::Autolock _l(mLock);
8169 return start_l();
8170}
8171
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172status_t AudioFlinger::EffectModule::start_l()
8173{
8174 if (mEffectInterface == NULL) {
8175 return NO_INIT;
8176 }
8177 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008178 uint32_t size = sizeof(status_t);
8179 status_t status = (*mEffectInterface)->command(mEffectInterface,
8180 EFFECT_CMD_ENABLE,
8181 0,
8182 NULL,
8183 &size,
8184 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185 if (status == 0) {
8186 status = cmdStatus;
8187 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008188 if (status == 0 &&
8189 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8190 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8191 sp<ThreadBase> thread = mThread.promote();
8192 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008193 audio_stream_t *stream = thread->stream();
8194 if (stream != NULL) {
8195 stream->add_audio_effect(stream, mEffectInterface);
8196 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008197 }
8198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199 return status;
8200}
8201
Eric Laurentec437d82011-07-26 20:54:46 -07008202status_t AudioFlinger::EffectModule::stop()
8203{
8204 Mutex::Autolock _l(mLock);
8205 return stop_l();
8206}
8207
Mathias Agopian65ab4712010-07-14 17:59:35 -07008208status_t AudioFlinger::EffectModule::stop_l()
8209{
8210 if (mEffectInterface == NULL) {
8211 return NO_INIT;
8212 }
8213 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008214 uint32_t size = sizeof(status_t);
8215 status_t status = (*mEffectInterface)->command(mEffectInterface,
8216 EFFECT_CMD_DISABLE,
8217 0,
8218 NULL,
8219 &size,
8220 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008221 if (status == 0) {
8222 status = cmdStatus;
8223 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008224 if (status == 0 &&
8225 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8226 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8227 sp<ThreadBase> thread = mThread.promote();
8228 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008229 audio_stream_t *stream = thread->stream();
8230 if (stream != NULL) {
8231 stream->remove_audio_effect(stream, mEffectInterface);
8232 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008233 }
8234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235 return status;
8236}
8237
Eric Laurent25f43952010-07-28 05:40:18 -07008238status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8239 uint32_t cmdSize,
8240 void *pCmdData,
8241 uint32_t *replySize,
8242 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008243{
8244 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008245// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008246
Eric Laurentec437d82011-07-26 20:54:46 -07008247 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008248 return NO_INIT;
8249 }
Eric Laurent25f43952010-07-28 05:40:18 -07008250 status_t status = (*mEffectInterface)->command(mEffectInterface,
8251 cmdCode,
8252 cmdSize,
8253 pCmdData,
8254 replySize,
8255 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008257 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008258 for (size_t i = 1; i < mHandles.size(); i++) {
8259 sp<EffectHandle> h = mHandles[i].promote();
8260 if (h != 0) {
8261 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8262 }
8263 }
8264 }
8265 return status;
8266}
8267
8268status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8269{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008270
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008272 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008273
8274 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008275 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8276 if (enabled && status != NO_ERROR) {
8277 return status;
8278 }
8279
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280 switch (mState) {
8281 // going from disabled to enabled
8282 case IDLE:
8283 mState = STARTING;
8284 break;
8285 case STOPPED:
8286 mState = RESTART;
8287 break;
8288 case STOPPING:
8289 mState = ACTIVE;
8290 break;
8291
8292 // going from enabled to disabled
8293 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008294 mState = STOPPED;
8295 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008296 case STARTING:
8297 mState = IDLE;
8298 break;
8299 case ACTIVE:
8300 mState = STOPPING;
8301 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008302 case DESTROYED:
8303 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304 }
8305 for (size_t i = 1; i < mHandles.size(); i++) {
8306 sp<EffectHandle> h = mHandles[i].promote();
8307 if (h != 0) {
8308 h->setEnabled(enabled);
8309 }
8310 }
8311 }
8312 return NO_ERROR;
8313}
8314
Glenn Kastenc59c0042012-02-02 14:06:11 -08008315bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008316{
8317 switch (mState) {
8318 case RESTART:
8319 case STARTING:
8320 case ACTIVE:
8321 return true;
8322 case IDLE:
8323 case STOPPING:
8324 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008325 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008326 default:
8327 return false;
8328 }
8329}
8330
Glenn Kastenc59c0042012-02-02 14:06:11 -08008331bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008332{
8333 switch (mState) {
8334 case RESTART:
8335 case ACTIVE:
8336 case STOPPING:
8337 case STOPPED:
8338 return true;
8339 case IDLE:
8340 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008341 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008342 default:
8343 return false;
8344 }
8345}
8346
Mathias Agopian65ab4712010-07-14 17:59:35 -07008347status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8348{
8349 Mutex::Autolock _l(mLock);
8350 status_t status = NO_ERROR;
8351
8352 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8353 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008354 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008355 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8356 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 status_t cmdStatus;
8358 uint32_t volume[2];
8359 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008360 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008361 volume[0] = *left;
8362 volume[1] = *right;
8363 if (controller) {
8364 pVolume = volume;
8365 }
Eric Laurent25f43952010-07-28 05:40:18 -07008366 status = (*mEffectInterface)->command(mEffectInterface,
8367 EFFECT_CMD_SET_VOLUME,
8368 size,
8369 volume,
8370 &size,
8371 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008372 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8373 *left = volume[0];
8374 *right = volume[1];
8375 }
8376 }
8377 return status;
8378}
8379
8380status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8381{
8382 Mutex::Autolock _l(mLock);
8383 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008384 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8385 // audio pre processing modules on RecordThread can receive both output and
8386 // input device indication in the same call
8387 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8388 if (dev) {
8389 status_t cmdStatus;
8390 uint32_t size = sizeof(status_t);
8391
8392 status = (*mEffectInterface)->command(mEffectInterface,
8393 EFFECT_CMD_SET_DEVICE,
8394 sizeof(uint32_t),
8395 &dev,
8396 &size,
8397 &cmdStatus);
8398 if (status == NO_ERROR) {
8399 status = cmdStatus;
8400 }
8401 }
8402 dev = device & AUDIO_DEVICE_IN_ALL;
8403 if (dev) {
8404 status_t cmdStatus;
8405 uint32_t size = sizeof(status_t);
8406
8407 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8408 EFFECT_CMD_SET_INPUT_DEVICE,
8409 sizeof(uint32_t),
8410 &dev,
8411 &size,
8412 &cmdStatus);
8413 if (status2 == NO_ERROR) {
8414 status2 = cmdStatus;
8415 }
8416 if (status == NO_ERROR) {
8417 status = status2;
8418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008419 }
8420 }
8421 return status;
8422}
8423
Glenn Kastenf78aee72012-01-04 11:00:47 -08008424status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425{
8426 Mutex::Autolock _l(mLock);
8427 status_t status = NO_ERROR;
8428 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008429 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008430 uint32_t size = sizeof(status_t);
8431 status = (*mEffectInterface)->command(mEffectInterface,
8432 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008433 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008434 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008435 &size,
8436 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008437 if (status == NO_ERROR) {
8438 status = cmdStatus;
8439 }
8440 }
8441 return status;
8442}
8443
Eric Laurent59255e42011-07-27 19:49:51 -07008444void AudioFlinger::EffectModule::setSuspended(bool suspended)
8445{
8446 Mutex::Autolock _l(mLock);
8447 mSuspended = suspended;
8448}
Glenn Kastena3a85482012-01-04 11:01:11 -08008449
8450bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008451{
8452 Mutex::Autolock _l(mLock);
8453 return mSuspended;
8454}
8455
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8457{
8458 const size_t SIZE = 256;
8459 char buffer[SIZE];
8460 String8 result;
8461
8462 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8463 result.append(buffer);
8464
8465 bool locked = tryLock(mLock);
8466 // failed to lock - AudioFlinger is probably deadlocked
8467 if (!locked) {
8468 result.append("\t\tCould not lock Fx mutex:\n");
8469 }
8470
8471 result.append("\t\tSession Status State Engine:\n");
8472 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8473 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8474 result.append(buffer);
8475
8476 result.append("\t\tDescriptor:\n");
8477 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8478 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8479 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8480 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8481 result.append(buffer);
8482 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8483 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8484 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8485 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8486 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008487 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008488 mDescriptor.apiVersion,
8489 mDescriptor.flags);
8490 result.append(buffer);
8491 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8492 mDescriptor.name);
8493 result.append(buffer);
8494 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8495 mDescriptor.implementor);
8496 result.append(buffer);
8497
8498 result.append("\t\t- Input configuration:\n");
8499 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8500 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8501 (uint32_t)mConfig.inputCfg.buffer.raw,
8502 mConfig.inputCfg.buffer.frameCount,
8503 mConfig.inputCfg.samplingRate,
8504 mConfig.inputCfg.channels,
8505 mConfig.inputCfg.format);
8506 result.append(buffer);
8507
8508 result.append("\t\t- Output configuration:\n");
8509 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8510 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8511 (uint32_t)mConfig.outputCfg.buffer.raw,
8512 mConfig.outputCfg.buffer.frameCount,
8513 mConfig.outputCfg.samplingRate,
8514 mConfig.outputCfg.channels,
8515 mConfig.outputCfg.format);
8516 result.append(buffer);
8517
8518 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8519 result.append(buffer);
8520 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8521 for (size_t i = 0; i < mHandles.size(); ++i) {
8522 sp<EffectHandle> handle = mHandles[i].promote();
8523 if (handle != 0) {
8524 handle->dump(buffer, SIZE);
8525 result.append(buffer);
8526 }
8527 }
8528
8529 result.append("\n");
8530
8531 write(fd, result.string(), result.length());
8532
8533 if (locked) {
8534 mLock.unlock();
8535 }
8536
8537 return NO_ERROR;
8538}
8539
8540// ----------------------------------------------------------------------------
8541// EffectHandle implementation
8542// ----------------------------------------------------------------------------
8543
8544#undef LOG_TAG
8545#define LOG_TAG "AudioFlinger::EffectHandle"
8546
8547AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8548 const sp<AudioFlinger::Client>& client,
8549 const sp<IEffectClient>& effectClient,
8550 int32_t priority)
8551 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008552 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008553 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008554{
Steve Block3856b092011-10-20 11:56:00 +01008555 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008556
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008557 if (client == 0) {
8558 return;
8559 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8561 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8562 if (mCblkMemory != 0) {
8563 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8564
Glenn Kastena0d68332012-01-27 16:47:15 -08008565 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008566 new(mCblk) effect_param_cblk_t();
8567 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008570 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571 return;
8572 }
8573}
8574
8575AudioFlinger::EffectHandle::~EffectHandle()
8576{
Steve Block3856b092011-10-20 11:56:00 +01008577 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008578 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008579 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008580}
8581
8582status_t AudioFlinger::EffectHandle::enable()
8583{
Steve Block3856b092011-10-20 11:56:00 +01008584 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008585 if (!mHasControl) return INVALID_OPERATION;
8586 if (mEffect == 0) return DEAD_OBJECT;
8587
Eric Laurentdb7c0792011-08-10 10:37:50 -07008588 if (mEnabled) {
8589 return NO_ERROR;
8590 }
8591
Eric Laurent59255e42011-07-27 19:49:51 -07008592 mEnabled = true;
8593
8594 sp<ThreadBase> thread = mEffect->thread().promote();
8595 if (thread != 0) {
8596 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8597 }
8598
8599 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8600 if (mEffect->suspended()) {
8601 return NO_ERROR;
8602 }
8603
Eric Laurentdb7c0792011-08-10 10:37:50 -07008604 status_t status = mEffect->setEnabled(true);
8605 if (status != NO_ERROR) {
8606 if (thread != 0) {
8607 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8608 }
8609 mEnabled = false;
8610 }
8611 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612}
8613
8614status_t AudioFlinger::EffectHandle::disable()
8615{
Steve Block3856b092011-10-20 11:56:00 +01008616 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008617 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008618 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008619
Eric Laurentdb7c0792011-08-10 10:37:50 -07008620 if (!mEnabled) {
8621 return NO_ERROR;
8622 }
Eric Laurent59255e42011-07-27 19:49:51 -07008623 mEnabled = false;
8624
8625 if (mEffect->suspended()) {
8626 return NO_ERROR;
8627 }
8628
8629 status_t status = mEffect->setEnabled(false);
8630
8631 sp<ThreadBase> thread = mEffect->thread().promote();
8632 if (thread != 0) {
8633 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8634 }
8635
8636 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008637}
8638
8639void AudioFlinger::EffectHandle::disconnect()
8640{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008641 disconnect(true);
8642}
8643
Glenn Kasten58123c32012-02-03 10:32:24 -08008644void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008645{
Glenn Kasten58123c32012-02-03 10:32:24 -08008646 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008647 if (mEffect == 0) {
8648 return;
8649 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008650 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008651
Eric Laurenta85a74a2011-10-19 11:44:54 -07008652 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008653 sp<ThreadBase> thread = mEffect->thread().promote();
8654 if (thread != 0) {
8655 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8656 }
Eric Laurent59255e42011-07-27 19:49:51 -07008657 }
8658
Mathias Agopian65ab4712010-07-14 17:59:35 -07008659 // release sp on module => module destructor can be called now
8660 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008661 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008662 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008663 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008664 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8665 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008666 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008667 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008668 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8669 mClient.clear();
8670 }
8671}
8672
Eric Laurent25f43952010-07-28 05:40:18 -07008673status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8674 uint32_t cmdSize,
8675 void *pCmdData,
8676 uint32_t *replySize,
8677 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008678{
Steve Block3856b092011-10-20 11:56:00 +01008679// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008680// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008681
8682 // only get parameter command is permitted for applications not controlling the effect
8683 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8684 return INVALID_OPERATION;
8685 }
8686 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008687 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008688
8689 // handle commands that are not forwarded transparently to effect engine
8690 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8691 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8692 // no risk to block the whole media server process or mixer threads is we are stuck here
8693 Mutex::Autolock _l(mCblk->lock);
8694 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8695 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8696 mCblk->serverIndex = 0;
8697 mCblk->clientIndex = 0;
8698 return BAD_VALUE;
8699 }
8700 status_t status = NO_ERROR;
8701 while (mCblk->serverIndex < mCblk->clientIndex) {
8702 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008703 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008704 int *p = (int *)(mBuffer + mCblk->serverIndex);
8705 int size = *p++;
8706 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008707 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008708 break;
8709 }
8710 effect_param_t *param = (effect_param_t *)p;
8711 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008712 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008713 mCblk->serverIndex += size;
8714 continue;
8715 }
Eric Laurent25f43952010-07-28 05:40:18 -07008716 uint32_t psize = sizeof(effect_param_t) +
8717 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8718 param->vsize;
8719 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8720 psize,
8721 p,
8722 &rsize,
8723 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008724 // stop at first error encountered
8725 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008726 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008727 *(int *)pReplyData = reply;
8728 break;
8729 } else if (reply != NO_ERROR) {
8730 *(int *)pReplyData = reply;
8731 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008732 }
8733 mCblk->serverIndex += size;
8734 }
8735 mCblk->serverIndex = 0;
8736 mCblk->clientIndex = 0;
8737 return status;
8738 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008739 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008740 return enable();
8741 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008742 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743 return disable();
8744 }
8745
8746 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8747}
8748
Eric Laurent59255e42011-07-27 19:49:51 -07008749void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008750{
Steve Block3856b092011-10-20 11:56:00 +01008751 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752
8753 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008754 mEnabled = enabled;
8755
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756 if (signal && mEffectClient != 0) {
8757 mEffectClient->controlStatusChanged(hasControl);
8758 }
8759}
8760
Eric Laurent25f43952010-07-28 05:40:18 -07008761void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8762 uint32_t cmdSize,
8763 void *pCmdData,
8764 uint32_t replySize,
8765 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008766{
8767 if (mEffectClient != 0) {
8768 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8769 }
8770}
8771
8772
8773
8774void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8775{
8776 if (mEffectClient != 0) {
8777 mEffectClient->enableStatusChanged(enabled);
8778 }
8779}
8780
8781status_t AudioFlinger::EffectHandle::onTransact(
8782 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8783{
8784 return BnEffect::onTransact(code, data, reply, flags);
8785}
8786
8787
8788void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8789{
Glenn Kastena0d68332012-01-27 16:47:15 -08008790 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008791
8792 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008793 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008794 mPriority,
8795 mHasControl,
8796 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008797 mCblk ? mCblk->clientIndex : 0,
8798 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008799 );
8800
8801 if (locked) {
8802 mCblk->lock.unlock();
8803 }
8804}
8805
8806#undef LOG_TAG
8807#define LOG_TAG "AudioFlinger::EffectChain"
8808
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008809AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008811 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008812 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8813 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008814{
Dima Zavinfce7a472011-04-19 22:30:36 -07008815 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008816 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008817 return;
8818 }
8819 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8820 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821}
8822
8823AudioFlinger::EffectChain::~EffectChain()
8824{
8825 if (mOwnInBuffer) {
8826 delete mInBuffer;
8827 }
8828
8829}
8830
Eric Laurent59255e42011-07-27 19:49:51 -07008831// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008832sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008833{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008834 size_t size = mEffects.size();
8835
8836 for (size_t i = 0; i < size; i++) {
8837 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008838 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008839 }
8840 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008841 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008842}
8843
Eric Laurent59255e42011-07-27 19:49:51 -07008844// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008845sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008846{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008847 size_t size = mEffects.size();
8848
8849 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008850 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8851 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008852 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008853 }
8854 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008855 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008856}
8857
Eric Laurent59255e42011-07-27 19:49:51 -07008858// getEffectFromType_l() must be called with ThreadBase::mLock held
8859sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8860 const effect_uuid_t *type)
8861{
Eric Laurent59255e42011-07-27 19:49:51 -07008862 size_t size = mEffects.size();
8863
8864 for (size_t i = 0; i < size; i++) {
8865 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008866 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008867 }
8868 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008869 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008870}
8871
Mathias Agopian65ab4712010-07-14 17:59:35 -07008872// Must be called with EffectChain::mLock locked
8873void AudioFlinger::EffectChain::process_l()
8874{
Eric Laurentdac69112010-09-28 14:09:57 -07008875 sp<ThreadBase> thread = mThread.promote();
8876 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008877 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008878 return;
8879 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008880 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8881 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008882 // always process effects unless no more tracks are on the session and the effect tail
8883 // has been rendered
8884 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008885 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008886 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008887
Eric Laurent544fe9b2011-11-11 15:42:52 -08008888 if (!tracksOnSession && mTailBufferCount == 0) {
8889 doProcess = false;
8890 }
8891
8892 if (activeTrackCnt() == 0) {
8893 // if no track is active and the effect tail has not been rendered,
8894 // the input buffer must be cleared here as the mixer process will not do it
8895 if (tracksOnSession || mTailBufferCount > 0) {
8896 size_t numSamples = thread->frameCount() * thread->channelCount();
8897 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8898 if (mTailBufferCount > 0) {
8899 mTailBufferCount--;
8900 }
8901 }
8902 }
Eric Laurentdac69112010-09-28 14:09:57 -07008903 }
8904
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008906 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008907 for (size_t i = 0; i < size; i++) {
8908 mEffects[i]->process();
8909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008910 }
8911 for (size_t i = 0; i < size; i++) {
8912 mEffects[i]->updateState();
8913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914}
8915
Eric Laurentcab11242010-07-15 12:50:15 -07008916// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008917status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008918{
8919 effect_descriptor_t desc = effect->desc();
8920 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8921
8922 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008923 effect->setChain(this);
8924 sp<ThreadBase> thread = mThread.promote();
8925 if (thread == 0) {
8926 return NO_INIT;
8927 }
8928 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929
8930 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8931 // Auxiliary effects are inserted at the beginning of mEffects vector as
8932 // they are processed first and accumulated in chain input buffer
8933 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008934
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935 // the input buffer for auxiliary effect contains mono samples in
8936 // 32 bit format. This is to avoid saturation in AudoMixer
8937 // accumulation stage. Saturation is done in EffectModule::process() before
8938 // calling the process in effect engine
8939 size_t numSamples = thread->frameCount();
8940 int32_t *buffer = new int32_t[numSamples];
8941 memset(buffer, 0, numSamples * sizeof(int32_t));
8942 effect->setInBuffer((int16_t *)buffer);
8943 // auxiliary effects output samples to chain input buffer for further processing
8944 // by insert effects
8945 effect->setOutBuffer(mInBuffer);
8946 } else {
8947 // Insert effects are inserted at the end of mEffects vector as they are processed
8948 // after track and auxiliary effects.
8949 // Insert effect order as a function of indicated preference:
8950 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8951 // another effect is present
8952 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8953 // last effect claiming first position
8954 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8955 // first effect claiming last position
8956 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8957 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8958 // already present
8959
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008960 size_t size = mEffects.size();
8961 size_t idx_insert = size;
8962 ssize_t idx_insert_first = -1;
8963 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008964
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008965 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008966 effect_descriptor_t d = mEffects[i]->desc();
8967 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8968 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8969 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8970 // check invalid effect chaining combinations
8971 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8972 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008973 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974 return INVALID_OPERATION;
8975 }
8976 // remember position of first insert effect and by default
8977 // select this as insert position for new effect
8978 if (idx_insert == size) {
8979 idx_insert = i;
8980 }
8981 // remember position of last insert effect claiming
8982 // first position
8983 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8984 idx_insert_first = i;
8985 }
8986 // remember position of first insert effect claiming
8987 // last position
8988 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8989 idx_insert_last == -1) {
8990 idx_insert_last = i;
8991 }
8992 }
8993 }
8994
8995 // modify idx_insert from first position if needed
8996 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8997 if (idx_insert_last != -1) {
8998 idx_insert = idx_insert_last;
8999 } else {
9000 idx_insert = size;
9001 }
9002 } else {
9003 if (idx_insert_first != -1) {
9004 idx_insert = idx_insert_first + 1;
9005 }
9006 }
9007
9008 // always read samples from chain input buffer
9009 effect->setInBuffer(mInBuffer);
9010
9011 // if last effect in the chain, output samples to chain
9012 // output buffer, otherwise to chain input buffer
9013 if (idx_insert == size) {
9014 if (idx_insert != 0) {
9015 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9016 mEffects[idx_insert-1]->configure();
9017 }
9018 effect->setOutBuffer(mOutBuffer);
9019 } else {
9020 effect->setOutBuffer(mInBuffer);
9021 }
9022 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023
Steve Block3856b092011-10-20 11:56:00 +01009024 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025 }
9026 effect->configure();
9027 return NO_ERROR;
9028}
9029
Eric Laurentcab11242010-07-15 12:50:15 -07009030// removeEffect_l() must be called with PlaybackThread::mLock held
9031size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032{
9033 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009034 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009035 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9036
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009037 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009039 // calling stop here will remove pre-processing effect from the audio HAL.
9040 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9041 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009042 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9043 mEffects[i]->state() == EffectModule::STOPPING) {
9044 mEffects[i]->stop();
9045 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009046 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9047 delete[] effect->inBuffer();
9048 } else {
9049 if (i == size - 1 && i != 0) {
9050 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9051 mEffects[i - 1]->configure();
9052 }
9053 }
9054 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009055 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056 break;
9057 }
9058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009059
9060 return mEffects.size();
9061}
9062
Eric Laurentcab11242010-07-15 12:50:15 -07009063// setDevice_l() must be called with PlaybackThread::mLock held
9064void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009065{
9066 size_t size = mEffects.size();
9067 for (size_t i = 0; i < size; i++) {
9068 mEffects[i]->setDevice(device);
9069 }
9070}
9071
Eric Laurentcab11242010-07-15 12:50:15 -07009072// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009073void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009074{
9075 size_t size = mEffects.size();
9076 for (size_t i = 0; i < size; i++) {
9077 mEffects[i]->setMode(mode);
9078 }
9079}
9080
Eric Laurentcab11242010-07-15 12:50:15 -07009081// setVolume_l() must be called with PlaybackThread::mLock held
9082bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009083{
9084 uint32_t newLeft = *left;
9085 uint32_t newRight = *right;
9086 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009087 int ctrlIdx = -1;
9088 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009089
Eric Laurentcab11242010-07-15 12:50:15 -07009090 // first update volume controller
9091 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009092 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009093 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9094 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009095 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009096 break;
9097 }
9098 }
9099
9100 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009101 if (hasControl) {
9102 *left = mNewLeftVolume;
9103 *right = mNewRightVolume;
9104 }
9105 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009106 }
9107
9108 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009109 mLeftVolume = newLeft;
9110 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009111
9112 // second get volume update from volume controller
9113 if (ctrlIdx >= 0) {
9114 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009115 mNewLeftVolume = newLeft;
9116 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009117 }
9118 // then indicate volume to all other effects in chain.
9119 // Pass altered volume to effects before volume controller
9120 // and requested volume to effects after controller
9121 uint32_t lVol = newLeft;
9122 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009123
Mathias Agopian65ab4712010-07-14 17:59:35 -07009124 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009125 if ((int)i == ctrlIdx) continue;
9126 // this also works for ctrlIdx == -1 when there is no volume controller
9127 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128 lVol = *left;
9129 rVol = *right;
9130 }
9131 mEffects[i]->setVolume(&lVol, &rVol, false);
9132 }
9133 *left = newLeft;
9134 *right = newRight;
9135
9136 return hasControl;
9137}
9138
Mathias Agopian65ab4712010-07-14 17:59:35 -07009139status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9140{
9141 const size_t SIZE = 256;
9142 char buffer[SIZE];
9143 String8 result;
9144
9145 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9146 result.append(buffer);
9147
9148 bool locked = tryLock(mLock);
9149 // failed to lock - AudioFlinger is probably deadlocked
9150 if (!locked) {
9151 result.append("\tCould not lock mutex:\n");
9152 }
9153
Eric Laurentcab11242010-07-15 12:50:15 -07009154 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9155 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009156 mEffects.size(),
9157 (uint32_t)mInBuffer,
9158 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009159 mActiveTrackCnt);
9160 result.append(buffer);
9161 write(fd, result.string(), result.size());
9162
9163 for (size_t i = 0; i < mEffects.size(); ++i) {
9164 sp<EffectModule> effect = mEffects[i];
9165 if (effect != 0) {
9166 effect->dump(fd, args);
9167 }
9168 }
9169
9170 if (locked) {
9171 mLock.unlock();
9172 }
9173
9174 return NO_ERROR;
9175}
9176
Eric Laurent59255e42011-07-27 19:49:51 -07009177// must be called with ThreadBase::mLock held
9178void AudioFlinger::EffectChain::setEffectSuspended_l(
9179 const effect_uuid_t *type, bool suspend)
9180{
9181 sp<SuspendedEffectDesc> desc;
9182 // use effect type UUID timelow as key as there is no real risk of identical
9183 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009184 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009185 if (suspend) {
9186 if (index >= 0) {
9187 desc = mSuspendedEffects.valueAt(index);
9188 } else {
9189 desc = new SuspendedEffectDesc();
9190 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9191 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009192 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009193 }
9194 if (desc->mRefCount++ == 0) {
9195 sp<EffectModule> effect = getEffectIfEnabled(type);
9196 if (effect != 0) {
9197 desc->mEffect = effect;
9198 effect->setSuspended(true);
9199 effect->setEnabled(false);
9200 }
9201 }
9202 } else {
9203 if (index < 0) {
9204 return;
9205 }
9206 desc = mSuspendedEffects.valueAt(index);
9207 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009208 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009209 desc->mRefCount = 1;
9210 }
9211 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009212 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009213 if (desc->mEffect != 0) {
9214 sp<EffectModule> effect = desc->mEffect.promote();
9215 if (effect != 0) {
9216 effect->setSuspended(false);
9217 sp<EffectHandle> handle = effect->controlHandle();
9218 if (handle != 0) {
9219 effect->setEnabled(handle->enabled());
9220 }
9221 }
9222 desc->mEffect.clear();
9223 }
9224 mSuspendedEffects.removeItemsAt(index);
9225 }
9226 }
9227}
9228
9229// must be called with ThreadBase::mLock held
9230void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9231{
9232 sp<SuspendedEffectDesc> desc;
9233
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009234 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009235 if (suspend) {
9236 if (index >= 0) {
9237 desc = mSuspendedEffects.valueAt(index);
9238 } else {
9239 desc = new SuspendedEffectDesc();
9240 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009241 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009242 }
9243 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009244 Vector< sp<EffectModule> > effects;
9245 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009246 for (size_t i = 0; i < effects.size(); i++) {
9247 setEffectSuspended_l(&effects[i]->desc().type, true);
9248 }
9249 }
9250 } else {
9251 if (index < 0) {
9252 return;
9253 }
9254 desc = mSuspendedEffects.valueAt(index);
9255 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009256 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009257 desc->mRefCount = 1;
9258 }
9259 if (--desc->mRefCount == 0) {
9260 Vector<const effect_uuid_t *> types;
9261 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9262 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9263 continue;
9264 }
9265 types.add(&mSuspendedEffects.valueAt(i)->mType);
9266 }
9267 for (size_t i = 0; i < types.size(); i++) {
9268 setEffectSuspended_l(types[i], false);
9269 }
Steve Block3856b092011-10-20 11:56:00 +01009270 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009271 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9272 }
9273 }
9274}
9275
Eric Laurent6bffdb82011-09-23 08:40:41 -07009276
9277// The volume effect is used for automated tests only
9278#ifndef OPENSL_ES_H_
9279static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9280 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9281const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9282#endif //OPENSL_ES_H_
9283
Eric Laurentdb7c0792011-08-10 10:37:50 -07009284bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9285{
9286 // auxiliary effects and visualizer are never suspended on output mix
9287 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9288 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009289 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9290 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009291 return false;
9292 }
9293 return true;
9294}
9295
Glenn Kastend0539712012-01-30 12:56:03 -08009296void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009297{
Glenn Kastend0539712012-01-30 12:56:03 -08009298 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009299 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009300 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9301 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009302 }
Eric Laurent59255e42011-07-27 19:49:51 -07009303 }
Eric Laurent59255e42011-07-27 19:49:51 -07009304}
9305
9306sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9307 const effect_uuid_t *type)
9308{
Glenn Kasten090f0192012-01-30 13:00:02 -08009309 sp<EffectModule> effect = getEffectFromType_l(type);
9310 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009311}
9312
9313void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9314 bool enabled)
9315{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009316 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009317 if (enabled) {
9318 if (index < 0) {
9319 // if the effect is not suspend check if all effects are suspended
9320 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9321 if (index < 0) {
9322 return;
9323 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009324 if (!isEffectEligibleForSuspend(effect->desc())) {
9325 return;
9326 }
Eric Laurent59255e42011-07-27 19:49:51 -07009327 setEffectSuspended_l(&effect->desc().type, enabled);
9328 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009329 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009330 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009331 return;
9332 }
Eric Laurent59255e42011-07-27 19:49:51 -07009333 }
Steve Block3856b092011-10-20 11:56:00 +01009334 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009335 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009336 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9337 // if effect is requested to suspended but was not yet enabled, supend it now.
9338 if (desc->mEffect == 0) {
9339 desc->mEffect = effect;
9340 effect->setEnabled(false);
9341 effect->setSuspended(true);
9342 }
9343 } else {
9344 if (index < 0) {
9345 return;
9346 }
Steve Block3856b092011-10-20 11:56:00 +01009347 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009348 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009349 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9350 desc->mEffect.clear();
9351 effect->setSuspended(false);
9352 }
9353}
9354
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355#undef LOG_TAG
9356#define LOG_TAG "AudioFlinger"
9357
9358// ----------------------------------------------------------------------------
9359
9360status_t AudioFlinger::onTransact(
9361 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9362{
9363 return BnAudioFlinger::onTransact(code, data, reply, flags);
9364}
9365
Mathias Agopian65ab4712010-07-14 17:59:35 -07009366}; // namespace android