blob: 77b2bc8eceb59c8941d75513f871de72ca6c5094 [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;
145
John Grossman4ff14ba2012-02-08 16:37:41 -0800146nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800147
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700148// Whether to use fast mixer
149static const enum {
150 FastMixer_Never, // never initialize or use: for debugging only
151 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
152 // normal mixer multiplier is 1
153 FastMixer_Static, // initialize if needed, then use all the time if initialized,
154 // multipler is calculated based on minimum normal mixer buffer size
155 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
156 // multipler is calculated based on minimum normal mixer buffer size
157 // FIXME for FastMixer_Dynamic:
158 // Supporting this option will require fixing HALs that can't handle large writes.
159 // For example, one HAL implementation returns an error from a large write,
160 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
161 // We could either fix the HAL implementations, or provide a wrapper that breaks
162 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
163} kUseFastMixer = FastMixer_Static;
164
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165// ----------------------------------------------------------------------------
166
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700167#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800168// To collect the amplifier usage
169static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800170 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
171 if (service == NULL) {
172 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800173 return;
174 }
175
176 service->addBatteryData(params);
177}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700178#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800179
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700180static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700181{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700182 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 int rc;
184
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700185 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
186 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
187 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
188 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700189 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700190 }
191 rc = audio_hw_device_open(mod, dev);
192 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
193 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
194 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700196 }
197 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
198 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
199 rc = BAD_VALUE;
200 goto out;
201 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return 0;
203
204out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 *dev = NULL;
206 return rc;
207}
208
Mathias Agopian65ab4712010-07-14 17:59:35 -0700209// ----------------------------------------------------------------------------
210
211AudioFlinger::AudioFlinger()
212 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800213 mPrimaryHardwareDev(NULL),
214 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
215 mMasterVolume(1.0f),
216 mMasterVolumeSupportLvl(MVS_NONE),
217 mMasterMute(false),
218 mNextUniqueId(1),
219 mMode(AUDIO_MODE_INVALID),
220 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700222}
223
224void AudioFlinger::onFirstRef()
225{
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700227
Eric Laurent93575202011-01-18 18:39:02 -0800228 Mutex::Autolock _l(mLock);
229
Dima Zavin799a70e2011-04-18 16:57:27 -0700230 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800231 char val_str[PROPERTY_VALUE_MAX] = { 0 };
232 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
233 uint32_t int_val;
234 if (1 == sscanf(val_str, "%u", &int_val)) {
235 mStandbyTimeInNsecs = milliseconds(int_val);
236 ALOGI("Using %u mSec as standby time.", int_val);
237 } else {
238 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
239 ALOGI("Using default %u mSec as standby time.",
240 (uint32_t)(mStandbyTimeInNsecs / 1000000));
241 }
242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243
Eric Laurenta4c5a552012-03-29 10:12:40 -0700244 mMode = AUDIO_MODE_NORMAL;
245 mMasterVolumeSW = 1.0;
246 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800247 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248}
249
250AudioFlinger::~AudioFlinger()
251{
Dima Zavin799a70e2011-04-18 16:57:27 -0700252
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253 while (!mRecordThreads.isEmpty()) {
254 // closeInput() will remove first entry from mRecordThreads
255 closeInput(mRecordThreads.keyAt(0));
256 }
257 while (!mPlaybackThreads.isEmpty()) {
258 // closeOutput() will remove first entry from mPlaybackThreads
259 closeOutput(mPlaybackThreads.keyAt(0));
260 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700261
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800262 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
263 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700264 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
265 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266 }
267}
268
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269static const char * const audio_interfaces[] = {
270 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
271 AUDIO_HARDWARE_MODULE_ID_A2DP,
272 AUDIO_HARDWARE_MODULE_ID_USB,
273};
274#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
275
276audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700277{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278 // if module is 0, the request comes from an old policy manager and we should load
279 // well known modules
280 if (module == 0) {
281 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283 loadHwModule_l(audio_interfaces[i]);
284 }
285 } else {
286 // check a match for the requested module handle
287 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
288 if (audioHwdevice != NULL) {
289 return audioHwdevice->hwDevice();
290 }
291 }
292 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700293 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700294 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 if ((dev->get_supported_devices(dev) & devices) == devices)
296 return dev;
297 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700298
Dima Zavin799a70e2011-04-18 16:57:27 -0700299 return NULL;
300}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301
302status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307
308 result.append("Clients:\n");
309 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800310 sp<Client> client = mClients.valueAt(i).promote();
311 if (client != 0) {
312 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
313 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314 }
315 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700316
317 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800318 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700319 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
320 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800321 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700322 result.append(buffer);
323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 write(fd, result.string(), result.size());
325 return NO_ERROR;
326}
327
328
329status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
330{
331 const size_t SIZE = 256;
332 char buffer[SIZE];
333 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800334 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335
John Grossman4ff14ba2012-02-08 16:37:41 -0800336 snprintf(buffer, SIZE, "Hardware status: %d\n"
337 "Standby Time mSec: %u\n",
338 hardwareStatus,
339 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340 result.append(buffer);
341 write(fd, result.string(), result.size());
342 return NO_ERROR;
343}
344
345status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
346{
347 const size_t SIZE = 256;
348 char buffer[SIZE];
349 String8 result;
350 snprintf(buffer, SIZE, "Permission Denial: "
351 "can't dump AudioFlinger from pid=%d, uid=%d\n",
352 IPCThreadState::self()->getCallingPid(),
353 IPCThreadState::self()->getCallingUid());
354 result.append(buffer);
355 write(fd, result.string(), result.size());
356 return NO_ERROR;
357}
358
359static bool tryLock(Mutex& mutex)
360{
361 bool locked = false;
362 for (int i = 0; i < kDumpLockRetries; ++i) {
363 if (mutex.tryLock() == NO_ERROR) {
364 locked = true;
365 break;
366 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800367 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700368 }
369 return locked;
370}
371
372status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
373{
Glenn Kasten44deb052012-02-05 18:09:08 -0800374 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 dumpPermissionDenial(fd, args);
376 } else {
377 // get state of hardware lock
378 bool hardwareLocked = tryLock(mHardwareLock);
379 if (!hardwareLocked) {
380 String8 result(kHardwareLockedString);
381 write(fd, result.string(), result.size());
382 } else {
383 mHardwareLock.unlock();
384 }
385
386 bool locked = tryLock(mLock);
387
388 // failed to lock - AudioFlinger is probably deadlocked
389 if (!locked) {
390 String8 result(kDeadlockedString);
391 write(fd, result.string(), result.size());
392 }
393
394 dumpClients(fd, args);
395 dumpInternals(fd, args);
396
397 // dump playback threads
398 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
399 mPlaybackThreads.valueAt(i)->dump(fd, args);
400 }
401
402 // dump record threads
403 for (size_t i = 0; i < mRecordThreads.size(); i++) {
404 mRecordThreads.valueAt(i)->dump(fd, args);
405 }
406
Dima Zavin799a70e2011-04-18 16:57:27 -0700407 // dump all hardware devs
408 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700409 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700410 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 }
412 if (locked) mLock.unlock();
413 }
414 return NO_ERROR;
415}
416
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800417sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
418{
419 // If pid is already in the mClients wp<> map, then use that entry
420 // (for which promote() is always != 0), otherwise create a new entry and Client.
421 sp<Client> client = mClients.valueFor(pid).promote();
422 if (client == 0) {
423 client = new Client(this, pid);
424 mClients.add(pid, client);
425 }
426
427 return client;
428}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429
430// IAudioFlinger interface
431
432
433sp<IAudioTrack> AudioFlinger::createTrack(
434 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800435 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800437 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700438 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800440 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800442 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800443 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 int *sessionId,
445 status_t *status)
446{
447 sp<PlaybackThread::Track> track;
448 sp<TrackHandle> trackHandle;
449 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 status_t lStatus;
451 int lSessionId;
452
Glenn Kasten263709e2012-01-06 08:40:01 -0800453 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
454 // but if someone uses binder directly they could bypass that and cause us to crash
455 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000456 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 lStatus = BAD_VALUE;
458 goto Exit;
459 }
460
461 {
462 Mutex::Autolock _l(mLock);
463 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700464 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000466 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 lStatus = BAD_VALUE;
468 goto Exit;
469 }
470
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800471 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472
Steve Block3856b092011-10-20 11:56:00 +0100473 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700474 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700476 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
477 if (mPlaybackThreads.keyAt(i) != output) {
478 // prevent same audio session on different output threads
479 uint32_t sessions = t->hasAudioSession(*sessionId);
480 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000481 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 lStatus = BAD_VALUE;
483 goto Exit;
484 }
485 // check if an effect with same session ID is waiting for a track to be created
486 if (sessions & PlaybackThread::EFFECT_SESSION) {
487 effectThread = t.get();
488 }
Eric Laurentde070132010-07-13 04:45:46 -0700489 }
490 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 lSessionId = *sessionId;
492 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700493 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700494 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 if (sessionId != NULL) {
496 *sessionId = lSessionId;
497 }
498 }
Steve Block3856b092011-10-20 11:56:00 +0100499 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500
501 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800502 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700503
504 // move effect chain to this output thread if an effect on same session was waiting
505 // for a track to be created
506 if (lStatus == NO_ERROR && effectThread != NULL) {
507 Mutex::Autolock _dl(thread->mLock);
508 Mutex::Autolock _sl(effectThread->mLock);
509 moveEffectChain_l(lSessionId, effectThread, thread, true);
510 }
Eric Laurenta011e352012-03-29 15:51:43 -0700511
512 // Look for sync events awaiting for a session to be used.
513 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
514 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
515 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
516 track->setSyncEvent(mPendingSyncEvents[i]);
517 mPendingSyncEvents.removeAt(i);
518 i--;
519 }
520 }
521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700522 }
523 if (lStatus == NO_ERROR) {
524 trackHandle = new TrackHandle(track);
525 } else {
526 // remove local strong reference to Client before deleting the Track so that the Client
527 // destructor is called by the TrackBase destructor with mLock held
528 client.clear();
529 track.clear();
530 }
531
532Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700533 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 *status = lStatus;
535 }
536 return trackHandle;
537}
538
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800539uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540{
541 Mutex::Autolock _l(mLock);
542 PlaybackThread *thread = checkPlaybackThread_l(output);
543 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000544 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 return 0;
546 }
547 return thread->sampleRate();
548}
549
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800550int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551{
552 Mutex::Autolock _l(mLock);
553 PlaybackThread *thread = checkPlaybackThread_l(output);
554 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000555 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 return 0;
557 }
558 return thread->channelCount();
559}
560
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800561audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562{
563 Mutex::Autolock _l(mLock);
564 PlaybackThread *thread = checkPlaybackThread_l(output);
565 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000566 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800567 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 }
569 return thread->format();
570}
571
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800572size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573{
574 Mutex::Autolock _l(mLock);
575 PlaybackThread *thread = checkPlaybackThread_l(output);
576 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000577 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return 0;
579 }
Glenn Kasten58912562012-04-03 10:45:00 -0700580 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
581 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 return thread->frameCount();
583}
584
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800585uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586{
587 Mutex::Autolock _l(mLock);
588 PlaybackThread *thread = checkPlaybackThread_l(output);
589 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000590 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591 return 0;
592 }
593 return thread->latency();
594}
595
596status_t AudioFlinger::setMasterVolume(float value)
597{
Eric Laurenta1884f92011-08-23 08:25:03 -0700598 status_t ret = initCheck();
599 if (ret != NO_ERROR) {
600 return ret;
601 }
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
John Grossman4ff14ba2012-02-08 16:37:41 -0800608 float swmv = value;
609
Eric Laurenta4c5a552012-03-29 10:12:40 -0700610 Mutex::Autolock _l(mLock);
611
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800613 if (MVS_NONE != mMasterVolumeSupportLvl) {
614 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
615 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700616 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800617
618 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
619 if (NULL != dev->set_master_volume) {
620 dev->set_master_volume(dev, value);
621 }
622 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800623 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800624
625 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627
John Grossman4ff14ba2012-02-08 16:37:41 -0800628 mMasterVolume = value;
629 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800630 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700631 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632
633 return NO_ERROR;
634}
635
Glenn Kastenf78aee72012-01-04 11:00:47 -0800636status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637{
Eric Laurenta1884f92011-08-23 08:25:03 -0700638 status_t ret = initCheck();
639 if (ret != NO_ERROR) {
640 return ret;
641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642
643 // check calling permissions
644 if (!settingsAllowed()) {
645 return PERMISSION_DENIED;
646 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800647 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000648 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649 return BAD_VALUE;
650 }
651
652 { // scope for the lock
653 AutoMutex lock(mHardwareLock);
654 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700655 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 mHardwareStatus = AUDIO_HW_IDLE;
657 }
658
659 if (NO_ERROR == ret) {
660 Mutex::Autolock _l(mLock);
661 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800662 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700663 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 }
665
666 return ret;
667}
668
669status_t AudioFlinger::setMicMute(bool state)
670{
Eric Laurenta1884f92011-08-23 08:25:03 -0700671 status_t ret = initCheck();
672 if (ret != NO_ERROR) {
673 return ret;
674 }
675
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 // check calling permissions
677 if (!settingsAllowed()) {
678 return PERMISSION_DENIED;
679 }
680
681 AutoMutex lock(mHardwareLock);
682 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700683 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684 mHardwareStatus = AUDIO_HW_IDLE;
685 return ret;
686}
687
688bool AudioFlinger::getMicMute() const
689{
Eric Laurenta1884f92011-08-23 08:25:03 -0700690 status_t ret = initCheck();
691 if (ret != NO_ERROR) {
692 return false;
693 }
694
Dima Zavinfce7a472011-04-19 22:30:36 -0700695 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800696 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700698 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 mHardwareStatus = AUDIO_HW_IDLE;
700 return state;
701}
702
703status_t AudioFlinger::setMasterMute(bool muted)
704{
705 // check calling permissions
706 if (!settingsAllowed()) {
707 return PERMISSION_DENIED;
708 }
709
Eric Laurent93575202011-01-18 18:39:02 -0800710 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800711 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800713 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700714 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715
716 return NO_ERROR;
717}
718
719float AudioFlinger::masterVolume() const
720{
Glenn Kasten98067102011-12-13 11:47:54 -0800721 Mutex::Autolock _l(mLock);
722 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723}
724
John Grossman4ff14ba2012-02-08 16:37:41 -0800725float AudioFlinger::masterVolumeSW() const
726{
727 Mutex::Autolock _l(mLock);
728 return masterVolumeSW_l();
729}
730
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731bool AudioFlinger::masterMute() const
732{
Glenn Kasten98067102011-12-13 11:47:54 -0800733 Mutex::Autolock _l(mLock);
734 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735}
736
John Grossman4ff14ba2012-02-08 16:37:41 -0800737float AudioFlinger::masterVolume_l() const
738{
739 if (MVS_FULL == mMasterVolumeSupportLvl) {
740 float ret_val;
741 AutoMutex lock(mHardwareLock);
742
743 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800744 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
745 (NULL != mPrimaryHardwareDev->get_master_volume),
746 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800747
748 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
749 mHardwareStatus = AUDIO_HW_IDLE;
750 return ret_val;
751 }
752
753 return mMasterVolume;
754}
755
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800756status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
757 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758{
759 // check calling permissions
760 if (!settingsAllowed()) {
761 return PERMISSION_DENIED;
762 }
763
Glenn Kasten263709e2012-01-06 08:40:01 -0800764 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000765 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766 return BAD_VALUE;
767 }
768
769 AutoMutex lock(mLock);
770 PlaybackThread *thread = NULL;
771 if (output) {
772 thread = checkPlaybackThread_l(output);
773 if (thread == NULL) {
774 return BAD_VALUE;
775 }
776 }
777
778 mStreamTypes[stream].volume = value;
779
780 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800781 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700782 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 }
784 } else {
785 thread->setStreamVolume(stream, value);
786 }
787
788 return NO_ERROR;
789}
790
Glenn Kastenfff6d712012-01-12 16:38:12 -0800791status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792{
793 // check calling permissions
794 if (!settingsAllowed()) {
795 return PERMISSION_DENIED;
796 }
797
Glenn Kasten263709e2012-01-06 08:40:01 -0800798 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700799 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000800 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 return BAD_VALUE;
802 }
803
Eric Laurent93575202011-01-18 18:39:02 -0800804 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 mStreamTypes[stream].mute = muted;
806 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700807 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808
809 return NO_ERROR;
810}
811
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800812float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813{
Glenn Kasten263709e2012-01-06 08:40:01 -0800814 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return 0.0f;
816 }
817
818 AutoMutex lock(mLock);
819 float volume;
820 if (output) {
821 PlaybackThread *thread = checkPlaybackThread_l(output);
822 if (thread == NULL) {
823 return 0.0f;
824 }
825 volume = thread->streamVolume(stream);
826 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800827 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 }
829
830 return volume;
831}
832
Glenn Kastenfff6d712012-01-12 16:38:12 -0800833bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834{
Glenn Kasten263709e2012-01-06 08:40:01 -0800835 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return true;
837 }
838
Glenn Kasten6637baa2012-01-09 09:40:36 -0800839 AutoMutex lock(mLock);
840 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841}
842
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800843status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800845 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
847 // check calling permissions
848 if (!settingsAllowed()) {
849 return PERMISSION_DENIED;
850 }
851
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 // ioHandle == 0 means the parameters are global to the audio hardware interface
853 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700854 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700855 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800856 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700857 AutoMutex lock(mHardwareLock);
858 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
859 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
860 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
861 status_t result = dev->set_parameters(dev, keyValuePairs.string());
862 final_result = result ?: final_result;
863 }
864 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800865 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700866 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
867 AudioParameter param = AudioParameter(keyValuePairs);
868 String8 value;
869 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700870 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
871 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700872 for (size_t i = 0; i < mRecordThreads.size(); i++) {
873 sp<RecordThread> thread = mRecordThreads.valueAt(i);
874 RecordThread::RecordTrack *track = thread->track();
875 if (track != NULL) {
876 audio_devices_t device = (audio_devices_t)(
877 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700878 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700879 thread->setEffectSuspended(FX_IID_AEC,
880 suspend,
881 track->sessionId());
882 thread->setEffectSuspended(FX_IID_NS,
883 suspend,
884 track->sessionId());
885 }
886 }
Eric Laurentbee53372011-08-29 12:42:48 -0700887 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700888 }
889 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700890 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892
893 // hold a strong ref on thread in case closeOutput() or closeInput() is called
894 // and the thread is exited once the lock is released
895 sp<ThreadBase> thread;
896 {
897 Mutex::Autolock _l(mLock);
898 thread = checkPlaybackThread_l(ioHandle);
899 if (thread == NULL) {
900 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800901 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700902 // indicate output device change to all input threads for pre processing
903 AudioParameter param = AudioParameter(keyValuePairs);
904 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700905 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
906 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700907 for (size_t i = 0; i < mRecordThreads.size(); i++) {
908 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
909 }
910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911 }
912 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800913 if (thread != 0) {
914 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915 }
916 return BAD_VALUE;
917}
918
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800919String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800921// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
923
Eric Laurenta4c5a552012-03-29 10:12:40 -0700924 Mutex::Autolock _l(mLock);
925
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700927 String8 out_s8;
928
Dima Zavin799a70e2011-04-18 16:57:27 -0700929 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800930 char *s;
931 {
932 AutoMutex lock(mHardwareLock);
933 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700934 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800935 s = dev->get_parameters(dev, keys.string());
936 mHardwareStatus = AUDIO_HW_IDLE;
937 }
John Grossmanef7740b2012-02-09 11:28:36 -0800938 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700939 free(s);
940 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700941 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 }
943
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
945 if (playbackThread != NULL) {
946 return playbackThread->getParameters(keys);
947 }
948 RecordThread *recordThread = checkRecordThread_l(ioHandle);
949 if (recordThread != NULL) {
950 return recordThread->getParameters(keys);
951 }
952 return String8("");
953}
954
Glenn Kastenf587ba52012-01-26 16:25:10 -0800955size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956{
Eric Laurenta1884f92011-08-23 08:25:03 -0700957 status_t ret = initCheck();
958 if (ret != NO_ERROR) {
959 return 0;
960 }
961
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800962 AutoMutex lock(mHardwareLock);
963 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700964 struct audio_config config = {
965 sample_rate: sampleRate,
966 channel_mask: audio_channel_in_mask_from_count(channelCount),
967 format: format,
968 };
969 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800970 mHardwareStatus = AUDIO_HW_IDLE;
971 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972}
973
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800974unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975{
976 if (ioHandle == 0) {
977 return 0;
978 }
979
980 Mutex::Autolock _l(mLock);
981
982 RecordThread *recordThread = checkRecordThread_l(ioHandle);
983 if (recordThread != NULL) {
984 return recordThread->getInputFramesLost();
985 }
986 return 0;
987}
988
989status_t AudioFlinger::setVoiceVolume(float value)
990{
Eric Laurenta1884f92011-08-23 08:25:03 -0700991 status_t ret = initCheck();
992 if (ret != NO_ERROR) {
993 return ret;
994 }
995
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996 // check calling permissions
997 if (!settingsAllowed()) {
998 return PERMISSION_DENIED;
999 }
1000
1001 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001002 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001003 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004 mHardwareStatus = AUDIO_HW_IDLE;
1005
1006 return ret;
1007}
1008
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001009status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1010 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011{
1012 status_t status;
1013
1014 Mutex::Autolock _l(mLock);
1015
1016 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1017 if (playbackThread != NULL) {
1018 return playbackThread->getRenderPosition(halFrames, dspFrames);
1019 }
1020
1021 return BAD_VALUE;
1022}
1023
1024void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1025{
1026
1027 Mutex::Autolock _l(mLock);
1028
Glenn Kastenbb001922012-02-03 11:10:26 -08001029 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 if (mNotificationClients.indexOfKey(pid) < 0) {
1031 sp<NotificationClient> notificationClient = new NotificationClient(this,
1032 client,
1033 pid);
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035
1036 mNotificationClients.add(pid, notificationClient);
1037
1038 sp<IBinder> binder = client->asBinder();
1039 binder->linkToDeath(notificationClient);
1040
1041 // the config change is always sent from playback or record threads to avoid deadlock
1042 // with AudioSystem::gLock
1043 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1044 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1045 }
1046
1047 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1048 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1049 }
1050 }
1051}
1052
1053void AudioFlinger::removeNotificationClient(pid_t pid)
1054{
1055 Mutex::Autolock _l(mLock);
1056
Glenn Kastena3b09252012-01-20 09:19:01 -08001057 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001058
Steve Block3856b092011-10-20 11:56:00 +01001059 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001060 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001061 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001062 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001064 ALOGV(" pid %d @ %d", ref->mPid, i);
1065 if (ref->mPid == pid) {
1066 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 mAudioSessionRefs.removeAt(i);
1068 delete ref;
1069 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001071 } else {
1072 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 }
1074 }
1075 if (removed) {
1076 purgeStaleEffects_l();
1077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078}
1079
1080// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001081void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082{
1083 size_t size = mNotificationClients.size();
1084 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1086 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 }
1088}
1089
1090// removeClient_l() must be called with AudioFlinger::mLock held
1091void AudioFlinger::removeClient_l(pid_t pid)
1092{
Steve Block3856b092011-10-20 11:56:00 +01001093 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 mClients.removeItem(pid);
1095}
1096
1097
1098// ----------------------------------------------------------------------------
1099
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001100AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1101 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001103 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001104 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001105 // mChannelMask
1106 mChannelCount(0),
1107 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1108 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001109 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001110 mDevice(device),
1111 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112{
1113}
1114
1115AudioFlinger::ThreadBase::~ThreadBase()
1116{
1117 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001118 // do not lock the mutex in destructor
1119 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001120 if (mPowerManager != 0) {
1121 sp<IBinder> binder = mPowerManager->asBinder();
1122 binder->unlinkToDeath(mDeathRecipient);
1123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124}
1125
1126void AudioFlinger::ThreadBase::exit()
1127{
Steve Block3856b092011-10-20 11:56:00 +01001128 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001130 // This lock prevents the following race in thread (uniprocessor for illustration):
1131 // if (!exitPending()) {
1132 // // context switch from here to exit()
1133 // // exit() calls requestExit(), what exitPending() observes
1134 // // exit() calls signal(), which is dropped since no waiters
1135 // // context switch back from exit() to here
1136 // mWaitWorkCV.wait(...);
1137 // // now thread is hung
1138 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001139 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 requestExit();
1141 mWaitWorkCV.signal();
1142 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001143 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1144 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 requestExitAndWait();
1146}
1147
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1149{
1150 status_t status;
1151
Steve Block3856b092011-10-20 11:56:00 +01001152 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 Mutex::Autolock _l(mLock);
1154
1155 mNewParameters.add(keyValuePairs);
1156 mWaitWorkCV.signal();
1157 // wait condition with timeout in case the thread loop has exited
1158 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001159 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 status = mParamStatus;
1161 mWaitWorkCV.signal();
1162 } else {
1163 status = TIMED_OUT;
1164 }
1165 return status;
1166}
1167
1168void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1169{
1170 Mutex::Autolock _l(mLock);
1171 sendConfigEvent_l(event, param);
1172}
1173
1174// sendConfigEvent_l() must be called with ThreadBase::mLock held
1175void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1176{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001177 ConfigEvent configEvent;
1178 configEvent.mEvent = event;
1179 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001181 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 mWaitWorkCV.signal();
1183}
1184
1185void AudioFlinger::ThreadBase::processConfigEvents()
1186{
1187 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001188 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001190 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191 mConfigEvents.removeAt(0);
1192 // release mLock before locking AudioFlinger mLock: lock order is always
1193 // AudioFlinger then ThreadBase to avoid cross deadlock
1194 mLock.unlock();
1195 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001196 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 mLock.lock();
1199 }
1200 mLock.unlock();
1201}
1202
1203status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1204{
1205 const size_t SIZE = 256;
1206 char buffer[SIZE];
1207 String8 result;
1208
1209 bool locked = tryLock(mLock);
1210 if (!locked) {
1211 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1212 write(fd, buffer, strlen(buffer));
1213 }
1214
Eric Laurent612bbb52012-03-14 15:03:26 -07001215 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1216 result.append(buffer);
1217 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1218 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1220 result.append(buffer);
1221 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1222 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001223 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1224 result.append(buffer);
1225 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 result.append(buffer);
1227 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1228 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001229 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1230 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1232 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001233 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 result.append(buffer);
1235
1236 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1237 result.append(buffer);
1238 result.append(" Index Command");
1239 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1240 snprintf(buffer, SIZE, "\n %02d ", i);
1241 result.append(buffer);
1242 result.append(mNewParameters[i]);
1243 }
1244
1245 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1246 result.append(buffer);
1247 snprintf(buffer, SIZE, " Index event param\n");
1248 result.append(buffer);
1249 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001250 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251 result.append(buffer);
1252 }
1253 result.append("\n");
1254
1255 write(fd, result.string(), result.size());
1256
1257 if (locked) {
1258 mLock.unlock();
1259 }
1260 return NO_ERROR;
1261}
1262
Eric Laurent1d2bff02011-07-24 17:49:51 -07001263status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1264{
1265 const size_t SIZE = 256;
1266 char buffer[SIZE];
1267 String8 result;
1268
1269 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1270 write(fd, buffer, strlen(buffer));
1271
1272 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1273 sp<EffectChain> chain = mEffectChains[i];
1274 if (chain != 0) {
1275 chain->dump(fd, args);
1276 }
1277 }
1278 return NO_ERROR;
1279}
1280
Eric Laurentfeb0db62011-07-22 09:04:31 -07001281void AudioFlinger::ThreadBase::acquireWakeLock()
1282{
1283 Mutex::Autolock _l(mLock);
1284 acquireWakeLock_l();
1285}
1286
1287void AudioFlinger::ThreadBase::acquireWakeLock_l()
1288{
1289 if (mPowerManager == 0) {
1290 // use checkService() to avoid blocking if power service is not up yet
1291 sp<IBinder> binder =
1292 defaultServiceManager()->checkService(String16("power"));
1293 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001294 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001295 } else {
1296 mPowerManager = interface_cast<IPowerManager>(binder);
1297 binder->linkToDeath(mDeathRecipient);
1298 }
1299 }
1300 if (mPowerManager != 0) {
1301 sp<IBinder> binder = new BBinder();
1302 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1303 binder,
1304 String16(mName));
1305 if (status == NO_ERROR) {
1306 mWakeLockToken = binder;
1307 }
Steve Block3856b092011-10-20 11:56:00 +01001308 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001309 }
1310}
1311
1312void AudioFlinger::ThreadBase::releaseWakeLock()
1313{
1314 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001315 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001316}
1317
1318void AudioFlinger::ThreadBase::releaseWakeLock_l()
1319{
1320 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001322 if (mPowerManager != 0) {
1323 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1324 }
1325 mWakeLockToken.clear();
1326 }
1327}
1328
1329void AudioFlinger::ThreadBase::clearPowerManager()
1330{
1331 Mutex::Autolock _l(mLock);
1332 releaseWakeLock_l();
1333 mPowerManager.clear();
1334}
1335
1336void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1337{
1338 sp<ThreadBase> thread = mThread.promote();
1339 if (thread != 0) {
1340 thread->clearPowerManager();
1341 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001342 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001343}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001344
Eric Laurent59255e42011-07-27 19:49:51 -07001345void AudioFlinger::ThreadBase::setEffectSuspended(
1346 const effect_uuid_t *type, bool suspend, int sessionId)
1347{
1348 Mutex::Autolock _l(mLock);
1349 setEffectSuspended_l(type, suspend, sessionId);
1350}
1351
1352void AudioFlinger::ThreadBase::setEffectSuspended_l(
1353 const effect_uuid_t *type, bool suspend, int sessionId)
1354{
Glenn Kasten090f0192012-01-30 13:00:02 -08001355 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001356 if (chain != 0) {
1357 if (type != NULL) {
1358 chain->setEffectSuspended_l(type, suspend);
1359 } else {
1360 chain->setEffectSuspendedAll_l(suspend);
1361 }
1362 }
1363
1364 updateSuspendedSessions_l(type, suspend, sessionId);
1365}
1366
1367void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1368{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001369 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001370 if (index < 0) {
1371 return;
1372 }
1373
1374 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1375 mSuspendedSessions.editValueAt(index);
1376
1377 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001378 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001379 for (int j = 0; j < desc->mRefCount; j++) {
1380 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1381 chain->setEffectSuspendedAll_l(true);
1382 } else {
Steve Block3856b092011-10-20 11:56:00 +01001383 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001384 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001385 chain->setEffectSuspended_l(&desc->mType, true);
1386 }
1387 }
1388 }
1389}
1390
Eric Laurent59255e42011-07-27 19:49:51 -07001391void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1392 bool suspend,
1393 int sessionId)
1394{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001395 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001396
1397 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1398
1399 if (suspend) {
1400 if (index >= 0) {
1401 sessionEffects = mSuspendedSessions.editValueAt(index);
1402 } else {
1403 mSuspendedSessions.add(sessionId, sessionEffects);
1404 }
1405 } else {
1406 if (index < 0) {
1407 return;
1408 }
1409 sessionEffects = mSuspendedSessions.editValueAt(index);
1410 }
1411
1412
1413 int key = EffectChain::kKeyForSuspendAll;
1414 if (type != NULL) {
1415 key = type->timeLow;
1416 }
1417 index = sessionEffects.indexOfKey(key);
1418
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001419 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001420 if (suspend) {
1421 if (index >= 0) {
1422 desc = sessionEffects.valueAt(index);
1423 } else {
1424 desc = new SuspendedSessionDesc();
1425 if (type != NULL) {
1426 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1427 }
1428 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001429 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001430 }
1431 desc->mRefCount++;
1432 } else {
1433 if (index < 0) {
1434 return;
1435 }
1436 desc = sessionEffects.valueAt(index);
1437 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001438 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001439 sessionEffects.removeItemsAt(index);
1440 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001441 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001442 sessionId);
1443 mSuspendedSessions.removeItem(sessionId);
1444 }
1445 }
1446 }
1447 if (!sessionEffects.isEmpty()) {
1448 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1449 }
1450}
1451
1452void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1453 bool enabled,
1454 int sessionId)
1455{
1456 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001457 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1458}
Eric Laurent59255e42011-07-27 19:49:51 -07001459
Eric Laurenta85a74a2011-10-19 11:44:54 -07001460void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1461 bool enabled,
1462 int sessionId)
1463{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001464 if (mType != RECORD) {
1465 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1466 // another session. This gives the priority to well behaved effect control panels
1467 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001468 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1469 // global effects
1470 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001471 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1472 }
1473 }
Eric Laurent59255e42011-07-27 19:49:51 -07001474
1475 sp<EffectChain> chain = getEffectChain_l(sessionId);
1476 if (chain != 0) {
1477 chain->checkSuspendOnEffectEnabled(effect, enabled);
1478 }
1479}
1480
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481// ----------------------------------------------------------------------------
1482
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001483AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1484 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001485 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001486 uint32_t device,
1487 type_t type)
1488 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001489 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1490 // Assumes constructor is called by AudioFlinger with it's mLock held,
1491 // but it would be safer to explicitly pass initial masterMute as parameter
1492 mMasterMute(audioFlinger->masterMute_l()),
1493 // mStreamTypes[] initialized in constructor body
1494 mOutput(output),
1495 // Assumes constructor is called by AudioFlinger with it's mLock held,
1496 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001497 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001498 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001499 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001500 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001501 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten288ed212012-04-25 17:52:27 -07001502 // index 0 is reserved for normal mixer's submix
1503 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504{
Glenn Kasten480b4682012-02-28 12:30:08 -08001505 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001506
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 readOutputParameters();
1508
Glenn Kasten263709e2012-01-06 08:40:01 -08001509 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001510 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1511 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1512 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001513 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1514 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001516 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1517 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518}
1519
1520AudioFlinger::PlaybackThread::~PlaybackThread()
1521{
1522 delete [] mMixBuffer;
1523}
1524
1525status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1526{
1527 dumpInternals(fd, args);
1528 dumpTracks(fd, args);
1529 dumpEffectChains(fd, args);
1530 return NO_ERROR;
1531}
1532
1533status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1534{
1535 const size_t SIZE = 256;
1536 char buffer[SIZE];
1537 String8 result;
1538
Glenn Kasten58912562012-04-03 10:45:00 -07001539 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1540 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1541 const stream_type_t *st = &mStreamTypes[i];
1542 if (i > 0) {
1543 result.appendFormat(", ");
1544 }
1545 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1546 if (st->mute) {
1547 result.append("M");
1548 }
1549 }
1550 result.append("\n");
1551 write(fd, result.string(), result.length());
1552 result.clear();
1553
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1555 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001556 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 for (size_t i = 0; i < mTracks.size(); ++i) {
1558 sp<Track> track = mTracks[i];
1559 if (track != 0) {
1560 track->dump(buffer, SIZE);
1561 result.append(buffer);
1562 }
1563 }
1564
1565 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1566 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001567 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001569 sp<Track> track = mActiveTracks[i].promote();
1570 if (track != 0) {
1571 track->dump(buffer, SIZE);
1572 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 }
1574 }
1575 write(fd, result.string(), result.size());
1576 return NO_ERROR;
1577}
1578
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1580{
1581 const size_t SIZE = 256;
1582 char buffer[SIZE];
1583 String8 result;
1584
1585 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1586 result.append(buffer);
1587 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1588 result.append(buffer);
1589 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1590 result.append(buffer);
1591 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1592 result.append(buffer);
1593 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1596 result.append(buffer);
1597 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1598 result.append(buffer);
1599 write(fd, result.string(), result.size());
1600
1601 dumpBase(fd, args);
1602
1603 return NO_ERROR;
1604}
1605
1606// Thread virtuals
1607status_t AudioFlinger::PlaybackThread::readyToRun()
1608{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001609 status_t status = initCheck();
1610 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001611 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001612 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001613 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001615 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616}
1617
1618void AudioFlinger::PlaybackThread::onFirstRef()
1619{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001620 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621}
1622
1623// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001624sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001626 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001628 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001629 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 int frameCount,
1631 const sp<IMemory>& sharedBuffer,
1632 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001633 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001634 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 status_t *status)
1636{
1637 sp<Track> track;
1638 status_t lStatus;
1639
Glenn Kasten73d22752012-03-19 13:38:30 -07001640 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1641
1642 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001643 if (flags & IAudioFlinger::TRACK_FAST) {
1644 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001645 // not timed
1646 (!isTimed) &&
1647 // either of these use cases:
1648 (
1649 // use case 1: shared buffer with any frame count
1650 (
1651 (sharedBuffer != 0)
1652 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001653 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001654 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001655 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001656 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001657 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001658 )
1659 ) &&
1660 // PCM data
1661 audio_is_linear_pcm(format) &&
1662 // mono or stereo
1663 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1664 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001665#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001666 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001667 (sampleRate == mSampleRate) &&
1668#endif
1669 // normal mixer has an associated fast mixer
1670 hasFastMixer() &&
1671 // there are sufficient fast track slots available
1672 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001673 // FIXME test that MixerThread for this fast track has a capable output HAL
1674 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001675 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001676 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1677 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001678 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001679 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001680 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001681 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 } else {
1683 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001684 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1685 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1686 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1687 audio_is_linear_pcm(format),
1688 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001689 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001690 // For compatibility with AudioTrack calculation, buffer depth is forced
1691 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1692 // This is probably too conservative, but legacy application code may depend on it.
1693 // If you change this calculation, also review the start threshold which is related.
1694 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1695 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1696 if (minBufCount < 2) {
1697 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001698 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001699 int minFrameCount = mNormalFrameCount * minBufCount;
1700 if (frameCount < minFrameCount) {
1701 frameCount = minFrameCount;
1702 }
1703 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001704 }
1705
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001707 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1708 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001709 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001710 "for output %p with format %d",
1711 sampleRate, format, channelMask, mOutput, mFormat);
1712 lStatus = BAD_VALUE;
1713 goto Exit;
1714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 }
1716 } else {
1717 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1718 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001719 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 lStatus = BAD_VALUE;
1721 goto Exit;
1722 }
1723 }
1724
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001725 lStatus = initCheck();
1726 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001727 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 goto Exit;
1729 }
1730
1731 { // scope for mLock
1732 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001733
1734 // all tracks in same audio session must share the same routing strategy otherwise
1735 // conflicts will happen when tracks are moved from one output to another by audio policy
1736 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001737 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001738 for (size_t i = 0; i < mTracks.size(); ++i) {
1739 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001740 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001741 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001742 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001743 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001744 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001745 lStatus = BAD_VALUE;
1746 goto Exit;
1747 }
1748 }
1749 }
1750
John Grossman4ff14ba2012-02-08 16:37:41 -08001751 if (!isTimed) {
1752 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001753 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001754 } else {
1755 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1756 channelMask, frameCount, sharedBuffer, sessionId);
1757 }
1758 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 lStatus = NO_MEMORY;
1760 goto Exit;
1761 }
1762 mTracks.add(track);
1763
1764 sp<EffectChain> chain = getEffectChain_l(sessionId);
1765 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001766 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001768 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001769 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770 }
1771 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001772
1773#ifdef HAVE_REQUEST_PRIORITY
1774 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1775 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1776 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1777 // so ask activity manager to do this on our behalf
1778 int err = requestPriority(callingPid, tid, 1);
1779 if (err != 0) {
1780 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1781 1, callingPid, tid, err);
1782 }
1783 }
1784#endif
1785
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 lStatus = NO_ERROR;
1787
1788Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001789 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790 *status = lStatus;
1791 }
1792 return track;
1793}
1794
1795uint32_t AudioFlinger::PlaybackThread::latency() const
1796{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001797 Mutex::Autolock _l(mLock);
1798 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001799 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001800 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 return 0;
1802 }
1803}
1804
Glenn Kasten6637baa2012-01-09 09:40:36 -08001805void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001807 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809}
1810
Glenn Kasten6637baa2012-01-09 09:40:36 -08001811void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001813 Mutex::Autolock _l(mLock);
1814 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815}
1816
Glenn Kasten6637baa2012-01-09 09:40:36 -08001817void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001819 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821}
1822
Glenn Kasten6637baa2012-01-09 09:40:36 -08001823void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
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].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827}
1828
Glenn Kastenfff6d712012-01-12 16:38:12 -08001829float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
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 return mStreamTypes[stream].volume;
1833}
1834
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835// addTrack_l() must be called with ThreadBase::mLock held
1836status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1837{
1838 status_t status = ALREADY_EXISTS;
1839
1840 // set retry count for buffer fill
1841 track->mRetryCount = kMaxTrackStartupRetries;
1842 if (mActiveTracks.indexOf(track) < 0) {
1843 // the track is newly added, make sure it fills up all its
1844 // buffers before playing. This is to ensure the client will
1845 // effectively get the latency it requested.
1846 track->mFillingUpStatus = Track::FS_FILLING;
1847 track->mResetDone = false;
1848 mActiveTracks.add(track);
1849 if (track->mainBuffer() != mMixBuffer) {
1850 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1851 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001852 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001853 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 }
1855 }
1856
1857 status = NO_ERROR;
1858 }
1859
Steve Block3856b092011-10-20 11:56:00 +01001860 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 mWaitWorkCV.broadcast();
1862
1863 return status;
1864}
1865
1866// destroyTrack_l() must be called with ThreadBase::mLock held
1867void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1868{
1869 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001870 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001872 removeTrack_l(track);
1873 }
1874}
1875
1876void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1877{
1878 mTracks.remove(track);
1879 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001880 // redundant as track is about to be destroyed, for dumpsys only
1881 track->mName = -1;
1882 if (track->isFastTrack()) {
1883 int index = track->mFastIndex;
1884 ALOG_ASSERT(0 < index && index < FastMixerState::kMaxFastTracks);
1885 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1886 mFastTrackAvailMask |= 1 << index;
1887 // redundant as track is about to be destroyed, for dumpsys only
1888 track->mFastIndex = -1;
1889 }
Eric Laurentb469b942011-05-09 12:09:06 -07001890 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1891 if (chain != 0) {
1892 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894}
1895
1896String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1897{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001898 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001899 char *s;
1900
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001901 Mutex::Autolock _l(mLock);
1902 if (initCheck() != NO_ERROR) {
1903 return out_s8;
1904 }
1905
Dima Zavin799a70e2011-04-18 16:57:27 -07001906 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001907 out_s8 = String8(s);
1908 free(s);
1909 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910}
1911
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001912// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1914 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001915 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916
Steve Block3856b092011-10-20 11:56:00 +01001917 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918
1919 switch (event) {
1920 case AudioSystem::OUTPUT_OPENED:
1921 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001922 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 desc.samplingRate = mSampleRate;
1924 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001925 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 desc.latency = latency();
1927 param2 = &desc;
1928 break;
1929
1930 case AudioSystem::STREAM_CONFIG_CHANGED:
1931 param2 = &param;
1932 case AudioSystem::OUTPUT_CLOSED:
1933 default:
1934 break;
1935 }
1936 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1937}
1938
1939void AudioFlinger::PlaybackThread::readOutputParameters()
1940{
Dima Zavin799a70e2011-04-18 16:57:27 -07001941 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001942 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1943 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001944 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001945 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001946 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001947 if (mFrameCount & 15) {
1948 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1949 mFrameCount);
1950 }
1951
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001952 // Calculate size of normal mix buffer relative to the HAL output buffer size
1953 uint32_t multiple = 1;
1954 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001955 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001956 multiple = (minNormalFrameCount + mFrameCount - 1) / mFrameCount;
1957 // force multiple to be even, for compatibility with doubling of fast tracks due to HAL SRC
1958 // (it would be unusual for the normal mix buffer size to not be a multiple of fast track)
1959 // FIXME this rounding up should not be done if no HAL SRC
1960 if ((multiple > 2) && (multiple & 1)) {
1961 ++multiple;
Glenn Kasten58912562012-04-03 10:45:00 -07001962 }
Glenn Kasten58912562012-04-03 10:45:00 -07001963 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001964 mNormalFrameCount = multiple * mFrameCount;
Glenn Kasten58912562012-04-03 10:45:00 -07001965 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966
1967 // FIXME - Current mixer implementation only supports stereo output: Always
1968 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001969 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001970 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1971 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972
Eric Laurentde070132010-07-13 04:45:46 -07001973 // force reconfiguration of effect chains and engines to take new buffer size and audio
1974 // parameters into account
1975 // Note that mLock is not held when readOutputParameters() is called from the constructor
1976 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1977 // matter.
1978 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1979 Vector< sp<EffectChain> > effectChains = mEffectChains;
1980 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001981 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001982 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983}
1984
1985status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1986{
Glenn Kastena0d68332012-01-27 16:47:15 -08001987 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 return BAD_VALUE;
1989 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001990 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001991 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 return INVALID_OPERATION;
1993 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001994 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995
Dima Zavin799a70e2011-04-18 16:57:27 -07001996 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997}
1998
Eric Laurent39e94f82010-07-28 01:32:47 -07001999uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000{
2001 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002002 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002004 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 }
2006
2007 for (size_t i = 0; i < mTracks.size(); ++i) {
2008 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002009 if (sessionId == track->sessionId() &&
2010 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002011 result |= TRACK_SESSION;
2012 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 }
2014 }
2015
Eric Laurent39e94f82010-07-28 01:32:47 -07002016 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017}
2018
Eric Laurentde070132010-07-13 04:45:46 -07002019uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2020{
Dima Zavinfce7a472011-04-19 22:30:36 -07002021 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002022 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002023 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2024 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002025 }
2026 for (size_t i = 0; i < mTracks.size(); i++) {
2027 sp<Track> track = mTracks[i];
2028 if (sessionId == track->sessionId() &&
2029 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002030 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002031 }
2032 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002033 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002034}
2035
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036
Glenn Kastenaed850d2012-01-26 09:46:34 -08002037AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002038{
2039 Mutex::Autolock _l(mLock);
2040 return mOutput;
2041}
2042
2043AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2044{
2045 Mutex::Autolock _l(mLock);
2046 AudioStreamOut *output = mOutput;
2047 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002048 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2049 // must push a NULL and wait for ack
2050 mOutputSink.clear();
2051 mPipeSink.clear();
2052 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002053 return output;
2054}
2055
2056// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002057audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002058{
2059 if (mOutput == NULL) {
2060 return NULL;
2061 }
2062 return &mOutput->stream->common;
2063}
2064
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002065uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002066{
2067 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2068 // decoding and transfer time. So sleeping for half of the latency would likely cause
2069 // underruns
2070 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002071 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002072 } else {
2073 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2074 }
2075}
2076
Eric Laurenta011e352012-03-29 15:51:43 -07002077status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2078{
2079 if (!isValidSyncEvent(event)) {
2080 return BAD_VALUE;
2081 }
2082
2083 Mutex::Autolock _l(mLock);
2084
2085 for (size_t i = 0; i < mTracks.size(); ++i) {
2086 sp<Track> track = mTracks[i];
2087 if (event->triggerSession() == track->sessionId()) {
2088 track->setSyncEvent(event);
2089 return NO_ERROR;
2090 }
2091 }
2092
2093 return NAME_NOT_FOUND;
2094}
2095
2096bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2097{
2098 switch (event->type()) {
2099 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2100 return true;
2101 default:
2102 break;
2103 }
2104 return false;
2105}
2106
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107// ----------------------------------------------------------------------------
2108
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002109AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002110 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002111 : PlaybackThread(audioFlinger, output, id, device, type),
2112 // mAudioMixer below
2113#ifdef SOAKER
2114 mSoaker(NULL),
2115#endif
2116 // mFastMixer below
2117 mFastMixerFutex(0)
2118 // mOutputSink below
2119 // mPipeSink below
2120 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121{
Glenn Kasten58912562012-04-03 10:45:00 -07002122 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2123 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2124 "mFrameCount=%d, mNormalFrameCount=%d",
2125 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2126 mNormalFrameCount);
2127 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2128
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 // FIXME - Current mixer implementation only supports stereo output
2130 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002131 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 }
Glenn Kasten58912562012-04-03 10:45:00 -07002133
2134 // create an NBAIO sink for the HAL output stream, and negotiate
2135 mOutputSink = new AudioStreamOutSink(output->stream);
2136 size_t numCounterOffers = 0;
2137 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2138 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2139 ALOG_ASSERT(index == 0);
2140
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002141 // initialize fast mixer depending on configuration
2142 bool initFastMixer;
2143 switch (kUseFastMixer) {
2144 case FastMixer_Never:
2145 initFastMixer = false;
2146 break;
2147 case FastMixer_Always:
2148 initFastMixer = true;
2149 break;
2150 case FastMixer_Static:
2151 case FastMixer_Dynamic:
2152 initFastMixer = mFrameCount < mNormalFrameCount;
2153 break;
2154 }
2155 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002156
2157 // create a MonoPipe to connect our submix to FastMixer
2158 NBAIO_Format format = mOutputSink->format();
2159 // frame count will be rounded up to a power of 2, so this formula should work well
2160 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2161 true /*writeCanBlock*/);
2162 const NBAIO_Format offers[1] = {format};
2163 size_t numCounterOffers = 0;
2164 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2165 ALOG_ASSERT(index == 0);
2166 mPipeSink = monoPipe;
2167
2168#ifdef SOAKER
2169 // create a soaker as workaround for governor issues
2170 mSoaker = new Soaker();
2171 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2172 mSoaker->run("Soaker", PRIORITY_LOWEST);
2173#endif
2174
2175 // create fast mixer and configure it initially with just one fast track for our submix
2176 mFastMixer = new FastMixer();
2177 FastMixerStateQueue *sq = mFastMixer->sq();
2178 FastMixerState *state = sq->begin();
2179 FastTrack *fastTrack = &state->mFastTracks[0];
2180 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2181 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2182 fastTrack->mVolumeProvider = NULL;
2183 fastTrack->mGeneration++;
2184 state->mFastTracksGen++;
2185 state->mTrackMask = 1;
2186 // fast mixer will use the HAL output sink
2187 state->mOutputSink = mOutputSink.get();
2188 state->mOutputSinkGen++;
2189 state->mFrameCount = mFrameCount;
2190 state->mCommand = FastMixerState::COLD_IDLE;
2191 // already done in constructor initialization list
2192 //mFastMixerFutex = 0;
2193 state->mColdFutexAddr = &mFastMixerFutex;
2194 state->mColdGen++;
2195 state->mDumpState = &mFastMixerDumpState;
2196 sq->end();
2197 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2198
2199 // start the fast mixer
2200 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2201#ifdef HAVE_REQUEST_PRIORITY
2202 pid_t tid = mFastMixer->getTid();
2203 int err = requestPriority(getpid_cached, tid, 2);
2204 if (err != 0) {
2205 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2206 2, getpid_cached, tid, err);
2207 }
2208#endif
2209
2210 } else {
2211 mFastMixer = NULL;
2212 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002213
2214 switch (kUseFastMixer) {
2215 case FastMixer_Never:
2216 case FastMixer_Dynamic:
2217 mNormalSink = mOutputSink;
2218 break;
2219 case FastMixer_Always:
2220 mNormalSink = mPipeSink;
2221 break;
2222 case FastMixer_Static:
2223 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2224 break;
2225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226}
2227
2228AudioFlinger::MixerThread::~MixerThread()
2229{
Glenn Kasten58912562012-04-03 10:45:00 -07002230 if (mFastMixer != NULL) {
2231 FastMixerStateQueue *sq = mFastMixer->sq();
2232 FastMixerState *state = sq->begin();
2233 if (state->mCommand == FastMixerState::COLD_IDLE) {
2234 int32_t old = android_atomic_inc(&mFastMixerFutex);
2235 if (old == -1) {
2236 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2237 }
2238 }
2239 state->mCommand = FastMixerState::EXIT;
2240 sq->end();
2241 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2242 mFastMixer->join();
2243 // Though the fast mixer thread has exited, it's state queue is still valid.
2244 // We'll use that extract the final state which contains one remaining fast track
2245 // corresponding to our sub-mix.
2246 state = sq->begin();
2247 ALOG_ASSERT(state->mTrackMask == 1);
2248 FastTrack *fastTrack = &state->mFastTracks[0];
2249 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2250 delete fastTrack->mBufferProvider;
2251 sq->end(false /*didModify*/);
2252 delete mFastMixer;
2253#ifdef SOAKER
2254 if (mSoaker != NULL) {
2255 mSoaker->requestExitAndWait();
2256 }
2257 delete mSoaker;
2258#endif
2259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260 delete mAudioMixer;
2261}
2262
Glenn Kasten83efdd02012-02-24 07:21:32 -08002263class CpuStats {
2264public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002265 CpuStats();
2266 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002267#ifdef DEBUG_CPU_USAGE
2268private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002269 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2270 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2271
2272 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2273
2274 int mCpuNum; // thread's current CPU number
2275 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002276#endif
2277};
2278
Glenn Kasten190a46f2012-03-06 11:27:10 -08002279CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002280#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002281 : mCpuNum(-1), mCpukHz(-1)
2282#endif
2283{
2284}
2285
2286void CpuStats::sample(const String8 &title) {
2287#ifdef DEBUG_CPU_USAGE
2288 // get current thread's delta CPU time in wall clock ns
2289 double wcNs;
2290 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2291
2292 // record sample for wall clock statistics
2293 if (valid) {
2294 mWcStats.sample(wcNs);
2295 }
2296
2297 // get the current CPU number
2298 int cpuNum = sched_getcpu();
2299
2300 // get the current CPU frequency in kHz
2301 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2302
2303 // check if either CPU number or frequency changed
2304 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2305 mCpuNum = cpuNum;
2306 mCpukHz = cpukHz;
2307 // ignore sample for purposes of cycles
2308 valid = false;
2309 }
2310
2311 // if no change in CPU number or frequency, then record sample for cycle statistics
2312 if (valid && mCpukHz > 0) {
2313 double cycles = wcNs * cpukHz * 0.000001;
2314 mHzStats.sample(cycles);
2315 }
2316
2317 unsigned n = mWcStats.n();
2318 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002319 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002320 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002321 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2322 double perLoop = elapsed / (double) n;
2323 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002324 double perLoop1k = perLoop * 0.001;
2325 double mean = mWcStats.mean();
2326 double stddev = mWcStats.stddev();
2327 double minimum = mWcStats.minimum();
2328 double maximum = mWcStats.maximum();
2329 double meanCycles = mHzStats.mean();
2330 double stddevCycles = mHzStats.stddev();
2331 double minCycles = mHzStats.minimum();
2332 double maxCycles = mHzStats.maximum();
2333 mCpuUsage.resetElapsed();
2334 mWcStats.reset();
2335 mHzStats.reset();
2336 ALOGD("CPU usage for %s over past %.1f secs\n"
2337 " (%u mixer loops at %.1f mean ms per loop):\n"
2338 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2339 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2340 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2341 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002342 elapsed * .000000001, n, perLoop * .000001,
2343 mean * .001,
2344 stddev * .001,
2345 minimum * .001,
2346 maximum * .001,
2347 mean / perLoop100,
2348 stddev / perLoop100,
2349 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002350 maximum / perLoop100,
2351 meanCycles / perLoop1k,
2352 stddevCycles / perLoop1k,
2353 minCycles / perLoop1k,
2354 maxCycles / perLoop1k);
2355
Glenn Kasten83efdd02012-02-24 07:21:32 -08002356 }
2357 }
2358#endif
2359};
2360
Glenn Kasten37d825e2012-02-24 07:21:48 -08002361void AudioFlinger::PlaybackThread::checkSilentMode_l()
2362{
2363 if (!mMasterMute) {
2364 char value[PROPERTY_VALUE_MAX];
2365 if (property_get("ro.audio.silent", value, "0") > 0) {
2366 char *endptr;
2367 unsigned long ul = strtoul(value, &endptr, 0);
2368 if (*endptr == '\0' && ul != 0) {
2369 ALOGD("Silence is golden");
2370 // The setprop command will not allow a property to be changed after
2371 // the first time it is set, so we don't have to worry about un-muting.
2372 setMasterMute_l(true);
2373 }
2374 }
2375 }
2376}
2377
Glenn Kasten000f0e32012-03-01 17:10:56 -08002378bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379{
2380 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002381
Glenn Kasten000f0e32012-03-01 17:10:56 -08002382 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002383
2384 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002386if (mType == MIXER) {
2387 longStandbyExit = false;
2388}
Glenn Kasten688a6402012-02-29 07:57:06 -08002389
Glenn Kasten000f0e32012-03-01 17:10:56 -08002390 // DUPLICATING
2391 // FIXME could this be made local to while loop?
2392 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002393
Glenn Kasten66fcab92012-02-24 14:59:21 -08002394 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002395 sleepTime = idleSleepTime;
2396
2397if (mType == MIXER) {
2398 sleepTimeShift = 0;
2399}
2400
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002402 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403
Eric Laurentfeb0db62011-07-22 09:04:31 -07002404 acquireWakeLock();
2405
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 while (!exitPending())
2407 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002408 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002409
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002410 Vector< sp<EffectChain> > effectChains;
2411
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 processConfigEvents();
2413
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 { // scope for mLock
2415
2416 Mutex::Autolock _l(mLock);
2417
2418 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002419 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 }
2421
Glenn Kastenfa26a852012-03-06 11:28:04 -08002422 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002423
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002425 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002426 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002428
2429 threadLoop_standby();
2430
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 mStandby = true;
2432 mBytesWritten = 0;
2433 }
2434
Glenn Kasten3e074702012-02-28 18:40:35 -08002435 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 // we're about to wait, flush the binder command buffer
2437 IPCThreadState::self()->flushCommands();
2438
Glenn Kastenfa26a852012-03-06 11:28:04 -08002439 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002440
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 if (exitPending()) break;
2442
Eric Laurentfeb0db62011-07-22 09:04:31 -07002443 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002447 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002448 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449
Eric Laurentda747442012-04-25 18:53:13 -07002450 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002451 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002452
Glenn Kasten37d825e2012-02-24 07:21:48 -08002453 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454
Glenn Kasten000f0e32012-03-01 17:10:56 -08002455 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002457 if (mType == MIXER) {
2458 sleepTimeShift = 0;
2459 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002460
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 continue;
2462 }
2463 }
2464
Glenn Kasten81028042012-04-30 18:15:12 -07002465 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002466 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467
2468 // prevent any changes in effect chain list and in each effect chain
2469 // during mixing and effect process as the audio buffers could be deleted
2470 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002471 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002472 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473
Glenn Kastenfec279f2012-03-08 07:47:15 -08002474 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475 threadLoop_mix();
2476 } else {
2477 threadLoop_sleepTime();
2478 }
2479
2480 if (mSuspended > 0) {
2481 sleepTime = suspendSleepTimeUs();
2482 }
2483
2484 // only process effects if we're going to write
2485 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002486 for (size_t i = 0; i < effectChains.size(); i ++) {
2487 effectChains[i]->process_l();
2488 }
2489 }
2490
2491 // enable changes in effect chain
2492 unlockEffectChains(effectChains);
2493
2494 // sleepTime == 0 means we must write to audio hardware
2495 if (sleepTime == 0) {
2496
2497 threadLoop_write();
2498
2499if (mType == MIXER) {
2500 // write blocked detection
2501 nsecs_t now = systemTime();
2502 nsecs_t delta = now - mLastWriteTime;
2503 if (!mStandby && delta > maxPeriod) {
2504 mNumDelayedWrites++;
2505 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002506 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten000f0e32012-03-01 17:10:56 -08002507 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2508 ns2ms(delta), mNumDelayedWrites, this);
2509 lastWarning = now;
2510 }
2511 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2512 // a different threshold. Or completely removed for what it is worth anyway...
2513 if (mStandby) {
2514 longStandbyExit = true;
2515 }
2516 }
2517}
2518
2519 mStandby = false;
2520 } else {
2521 usleep(sleepTime);
2522 }
2523
Glenn Kasten58912562012-04-03 10:45:00 -07002524 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002526 // same lock. This will also mutate and push a new fast mixer state.
2527 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002528 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002529
Glenn Kastenfa26a852012-03-06 11:28:04 -08002530 // FIXME I don't understand the need for this here;
2531 // it was in the original code but maybe the
2532 // assignment in saveOutputTracks() makes this unnecessary?
2533 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534
2535 // Effect chains will be actually deleted here if they were removed from
2536 // mEffectChains list during mixing or effects processing
2537 effectChains.clear();
2538
2539 // FIXME Note that the above .clear() is no longer necessary since effectChains
2540 // is now local to this block, but will keep it for now (at least until merge done).
2541 }
2542
2543if (mType == MIXER || mType == DIRECT) {
2544 // put output stream into standby mode
2545 if (!mStandby) {
2546 mOutput->stream->common.standby(&mOutput->stream->common);
2547 }
2548}
2549if (mType == DUPLICATING) {
2550 // for DuplicatingThread, standby mode is handled by the outputTracks
2551}
2552
2553 releaseWakeLock();
2554
2555 ALOGV("Thread %p type %d exiting", this, mType);
2556 return false;
2557}
2558
Glenn Kasten288ed212012-04-25 17:52:27 -07002559// returns (via tracksToRemove) a set of tracks to remove.
Glenn Kasten58912562012-04-03 10:45:00 -07002560void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2561{
Glenn Kasten58912562012-04-03 10:45:00 -07002562 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2563}
2564
2565void AudioFlinger::MixerThread::threadLoop_write()
2566{
2567 // FIXME we should only do one push per cycle; confirm this is true
2568 // Start the fast mixer if it's not already running
2569 if (mFastMixer != NULL) {
2570 FastMixerStateQueue *sq = mFastMixer->sq();
2571 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002572 if (state->mCommand != FastMixerState::MIX_WRITE &&
2573 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002574 if (state->mCommand == FastMixerState::COLD_IDLE) {
2575 int32_t old = android_atomic_inc(&mFastMixerFutex);
2576 if (old == -1) {
2577 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2578 }
2579 }
2580 state->mCommand = FastMixerState::MIX_WRITE;
2581 sq->end();
2582 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002583 if (kUseFastMixer == FastMixer_Dynamic) {
2584 mNormalSink = mPipeSink;
2585 }
Glenn Kasten58912562012-04-03 10:45:00 -07002586 } else {
2587 sq->end(false /*didModify*/);
2588 }
2589 }
2590 PlaybackThread::threadLoop_write();
2591}
2592
Glenn Kasten000f0e32012-03-01 17:10:56 -08002593// shared by MIXER and DIRECT, overridden by DUPLICATING
2594void AudioFlinger::PlaybackThread::threadLoop_write()
2595{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002596 // FIXME rewrite to reduce number of system calls
2597 mLastWriteTime = systemTime();
2598 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002599
Glenn Kasten58912562012-04-03 10:45:00 -07002600#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002601 size_t count = mixBufferSize >> mBitShift;
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002602 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002603 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002604 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002605 if (framesWritten > 0) {
2606 size_t bytesWritten = framesWritten << mBitShift;
2607 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002608 }
2609
Glenn Kasten952eeb22012-03-06 11:30:57 -08002610 mNumWrites++;
2611 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002612}
2613
Glenn Kasten58912562012-04-03 10:45:00 -07002614void AudioFlinger::MixerThread::threadLoop_standby()
2615{
2616 // Idle the fast mixer if it's currently running
2617 if (mFastMixer != NULL) {
2618 FastMixerStateQueue *sq = mFastMixer->sq();
2619 FastMixerState *state = sq->begin();
2620 if (!(state->mCommand & FastMixerState::IDLE)) {
2621 state->mCommand = FastMixerState::COLD_IDLE;
2622 state->mColdFutexAddr = &mFastMixerFutex;
2623 state->mColdGen++;
2624 mFastMixerFutex = 0;
2625 sq->end();
2626 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2627 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002628 if (kUseFastMixer == FastMixer_Dynamic) {
2629 mNormalSink = mOutputSink;
2630 }
Glenn Kasten58912562012-04-03 10:45:00 -07002631 } else {
2632 sq->end(false /*didModify*/);
2633 }
2634 }
2635 PlaybackThread::threadLoop_standby();
2636}
2637
Glenn Kasten000f0e32012-03-01 17:10:56 -08002638// shared by MIXER and DIRECT, overridden by DUPLICATING
2639void AudioFlinger::PlaybackThread::threadLoop_standby()
2640{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002641 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2642 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002643}
2644
2645void AudioFlinger::MixerThread::threadLoop_mix()
2646{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002647 // obtain the presentation timestamp of the next output buffer
2648 int64_t pts;
2649 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002650
Glenn Kasten952eeb22012-03-06 11:30:57 -08002651 if (NULL != mOutput->stream->get_next_write_timestamp) {
2652 status = mOutput->stream->get_next_write_timestamp(
2653 mOutput->stream, &pts);
2654 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002655
Glenn Kasten952eeb22012-03-06 11:30:57 -08002656 if (status != NO_ERROR) {
2657 pts = AudioBufferProvider::kInvalidPTS;
2658 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002659
Glenn Kasten952eeb22012-03-06 11:30:57 -08002660 // mix buffers...
2661 mAudioMixer->process(pts);
2662 // increase sleep time progressively when application underrun condition clears.
2663 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2664 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2665 // such that we would underrun the audio HAL.
2666 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2667 sleepTimeShift--;
2668 }
2669 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002670 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002671 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002672}
2673
2674void AudioFlinger::MixerThread::threadLoop_sleepTime()
2675{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002676 // If no tracks are ready, sleep once for the duration of an output
2677 // buffer size, then write 0s to the output
2678 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002679 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002680 sleepTime = activeSleepTime >> sleepTimeShift;
2681 if (sleepTime < kMinThreadSleepTimeUs) {
2682 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002684 // reduce sleep time in case of consecutive application underruns to avoid
2685 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2686 // duration we would end up writing less data than needed by the audio HAL if
2687 // the condition persists.
2688 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2689 sleepTimeShift++;
2690 }
2691 } else {
2692 sleepTime = idleSleepTime;
2693 }
2694 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002695 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002696 memset (mMixBuffer, 0, mixBufferSize);
2697 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002698 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002699 }
2700 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701}
2702
2703// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002704AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002705 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706{
2707
Glenn Kasten29c23c32012-01-26 13:37:52 -08002708 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002710 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711 size_t mixedTracks = 0;
2712 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002713 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002714 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002715 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716
2717 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002718 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719
Eric Laurent571d49c2010-08-11 05:20:11 -07002720 if (masterMute) {
2721 masterVolume = 0;
2722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002724 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002726 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002727 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002728 masterVolume = (float)((v + (1 << 23)) >> 24);
2729 chain.clear();
2730 }
2731
Glenn Kasten288ed212012-04-25 17:52:27 -07002732 // prepare a new state to push
2733 FastMixerStateQueue *sq = NULL;
2734 FastMixerState *state = NULL;
2735 bool didModify = false;
2736 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2737 if (mFastMixer != NULL) {
2738 sq = mFastMixer->sq();
2739 state = sq->begin();
2740 }
2741
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002743 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 if (t == 0) continue;
2745
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002746 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002748
Glenn Kasten288ed212012-04-25 17:52:27 -07002749 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002750 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002751
2752 // It's theoretically possible (though unlikely) for a fast track to be created
2753 // and then removed within the same normal mix cycle. This is not a problem, as
2754 // the track never becomes active so it's fast mixer slot is never touched.
2755 // The converse, of removing an (active) track and then creating a new track
2756 // at the identical fast mixer slot within the same normal mix cycle,
2757 // is impossible because the slot isn't marked available until the end of each cycle.
2758 int j = track->mFastIndex;
2759 FastTrack *fastTrack = &state->mFastTracks[j];
2760
2761 // Determine whether the track is currently in underrun condition,
2762 // and whether it had a recent underrun.
2763 uint32_t underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2764 uint32_t recentUnderruns = (underruns - (track->mObservedUnderruns & ~1)) >> 1;
2765 // don't count underruns that occur while stopping or pausing
2766 if (!(track->isStopped() || track->isPausing())) {
2767 track->mUnderrunCount += recentUnderruns;
2768 }
2769 track->mObservedUnderruns = underruns;
2770
2771 // This is similar to the formula for normal tracks,
2772 // with a few modifications for fast tracks.
2773 bool isActive;
2774 if (track->isStopped()) {
2775 // track stays active after stop() until first underrun
2776 isActive = recentUnderruns == 0;
2777 } else if (track->isPaused() || track->isTerminated()) {
2778 isActive = false;
2779 } else if (track->isPausing()) {
2780 // ramp down is not yet implemented
2781 isActive = true;
2782 track->setPaused();
2783 } else if (track->isResuming()) {
2784 // ramp up is not yet implemented
2785 isActive = true;
2786 track->mState = TrackBase::ACTIVE;
2787 } else {
2788 // no minimum frame count for fast tracks; continual underrun is allowed,
2789 // but later could implement automatic pause after several consecutive underruns,
2790 // or auto-mute yet still consider the track active and continue to service it
2791 isActive = true;
2792 }
2793
2794 if (isActive) {
2795 // was it previously inactive?
2796 if (!(state->mTrackMask & (1 << j))) {
2797 ExtendedAudioBufferProvider *eabp = track;
2798 VolumeProvider *vp = track;
2799 fastTrack->mBufferProvider = eabp;
2800 fastTrack->mVolumeProvider = vp;
2801 fastTrack->mSampleRate = track->mSampleRate;
2802 fastTrack->mChannelMask = track->mChannelMask;
2803 fastTrack->mGeneration++;
2804 state->mTrackMask |= 1 << j;
2805 didModify = true;
2806 // no acknowledgement required for newly active tracks
2807 }
2808 // cache the combined master volume and stream type volume for fast mixer; this
2809 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2810 track->mCachedVolume = track->isMuted() ?
2811 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2812 ++fastTracks;
2813 } else {
2814 // was it previously active?
2815 if (state->mTrackMask & (1 << j)) {
2816 fastTrack->mBufferProvider = NULL;
2817 fastTrack->mGeneration++;
2818 state->mTrackMask &= ~(1 << j);
2819 didModify = true;
2820 // If any fast tracks were removed, we must wait for acknowledgement
2821 // because we're about to decrement the last sp<> on those tracks.
2822 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2823 }
2824 // Remainder of this block is copied from similar code for normal tracks
2825 if (track->isStopped()) {
2826 // Can't reset directly, as fast mixer is still polling this track
2827 // track->reset();
2828 // So instead mark this track as needing to be reset after push with ack
2829 resetMask |= 1 << i;
2830 }
2831 // This would be incomplete if we auto-paused on underrun
2832 size_t audioHALFrames =
2833 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2834 size_t framesWritten =
2835 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2836 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2837 tracksToRemove->add(track);
2838 }
2839 // Avoids a misleading display in dumpsys
2840 track->mObservedUnderruns &= ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07002841 }
2842 continue;
2843 }
2844
2845 { // local variable scope to avoid goto warning
2846
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 audio_track_cblk_t* cblk = track->cblk();
2848
2849 // The first time a track is added we wait
2850 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002851 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002852 // make sure that we have enough frames to mix one full buffer.
2853 // enforce this condition only once to enable draining the buffer in case the client
2854 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002855 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002856 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002857 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002858 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002859 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002860 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002861 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002862 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002863 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002864 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002865 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002866 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002867 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2868 // the minimum track buffer size is normally twice the number of frames necessary
2869 // to fill one buffer and the resampler should not leave more than one buffer worth
2870 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002871 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002872 }
2873 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002874 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 !track->isPaused() && !track->isTerminated())
2876 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002877 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878
2879 mixedTracks++;
2880
2881 // track->mainBuffer() != mMixBuffer means there is an effect chain
2882 // connected to the track
2883 chain.clear();
2884 if (track->mainBuffer() != mMixBuffer) {
2885 chain = getEffectChain_l(track->sessionId());
2886 // Delegate volume control to effect in track effect chain if needed
2887 if (chain != 0) {
2888 tracksWithEffect++;
2889 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002890 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002891 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 }
2893 }
2894
2895
2896 int param = AudioMixer::VOLUME;
2897 if (track->mFillingUpStatus == Track::FS_FILLED) {
2898 // no ramp for the first volume setting
2899 track->mFillingUpStatus = Track::FS_ACTIVE;
2900 if (track->mState == TrackBase::RESUMING) {
2901 track->mState = TrackBase::ACTIVE;
2902 param = AudioMixer::RAMP_VOLUME;
2903 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002904 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 } else if (cblk->server != 0) {
2906 // If the track is stopped before the first frame was mixed,
2907 // do not apply ramp
2908 param = AudioMixer::RAMP_VOLUME;
2909 }
2910
2911 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002912 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002913 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002914 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002915 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916 if (track->isPausing()) {
2917 track->setPaused();
2918 }
2919 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002920
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002922 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002924 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002925 vl = vlr & 0xFFFF;
2926 vr = vlr >> 16;
2927 // track volumes come from shared memory, so can't be trusted and must be clamped
2928 if (vl > MAX_GAIN_INT) {
2929 ALOGV("Track left volume out of range: %04X", vl);
2930 vl = MAX_GAIN_INT;
2931 }
2932 if (vr > MAX_GAIN_INT) {
2933 ALOGV("Track right volume out of range: %04X", vr);
2934 vr = MAX_GAIN_INT;
2935 }
2936 // now apply the master volume and stream type volume
2937 vl = (uint32_t)(v * vl) << 12;
2938 vr = (uint32_t)(v * vr) << 12;
2939 // assuming master volume and stream type volume each go up to 1.0,
2940 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941
Glenn Kasten05632a52012-01-03 14:22:33 -08002942 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2943 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002944 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002945 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002946 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002947 }
2948 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002950 // Delegate volume control to effect in track effect chain if needed
2951 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2952 // Do not ramp volume if volume is controlled by effect
2953 param = AudioMixer::VOLUME;
2954 track->mHasVolumeController = true;
2955 } else {
2956 // force no volume ramp when volume controller was just disabled or removed
2957 // from effect chain to avoid volume spike
2958 if (track->mHasVolumeController) {
2959 param = AudioMixer::VOLUME;
2960 }
2961 track->mHasVolumeController = false;
2962 }
2963
2964 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002965 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002966 vl = (vl + (1 << 11)) >> 12;
2967 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2968 vr = (vr + (1 << 11)) >> 12;
2969 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002970
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002971 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 -07002972
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002974 mAudioMixer->setBufferProvider(name, track);
2975 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002977 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2978 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2979 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002981 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 AudioMixer::TRACK,
2983 AudioMixer::FORMAT, (void *)track->format());
2984 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002985 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002987 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002989 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 AudioMixer::RESAMPLE,
2991 AudioMixer::SAMPLE_RATE,
2992 (void *)(cblk->sampleRate));
2993 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002994 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002995 AudioMixer::TRACK,
2996 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2997 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002998 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999 AudioMixer::TRACK,
3000 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3001
3002 // reset retry count
3003 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003004
Eric Laurent27741442012-01-17 19:20:12 -08003005 // If one track is ready, set the mixer ready if:
3006 // - the mixer was not ready during previous round OR
3007 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003008 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003009 mixerStatus != MIXER_TRACKS_ENABLED) {
3010 mixerStatus = MIXER_TRACKS_READY;
3011 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003013 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014 if (track->isStopped()) {
3015 track->reset();
3016 }
Eric Laurent83faee02012-04-27 18:24:29 -07003017 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3018 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 // We have consumed all the buffers of this track.
3020 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003021 // TODO: use actual buffer filling status instead of latency when available from
3022 // audio HAL
3023 size_t audioHALFrames =
3024 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3025 size_t framesWritten =
3026 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3027 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3028 tracksToRemove->add(track);
3029 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 } else {
3031 // No buffers for this track. Give it a few chances to
3032 // fill a buffer, then remove it from active list.
3033 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003034 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003036 // indicate to client process that the track was disabled because of underrun;
3037 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003038 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003039 // If one track is not ready, mark the mixer also not ready if:
3040 // - the mixer was ready during previous round OR
3041 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003042 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003043 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 mixerStatus = MIXER_TRACKS_ENABLED;
3045 }
3046 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003047 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 }
Glenn Kasten58912562012-04-03 10:45:00 -07003049
3050 } // local variable scope to avoid goto warning
3051track_is_ready: ;
3052
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 }
3054
Glenn Kasten288ed212012-04-25 17:52:27 -07003055 // Push the new FastMixer state if necessary
3056 if (didModify) {
3057 state->mFastTracksGen++;
3058 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3059 if (kUseFastMixer == FastMixer_Dynamic &&
3060 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3061 state->mCommand = FastMixerState::COLD_IDLE;
3062 state->mColdFutexAddr = &mFastMixerFutex;
3063 state->mColdGen++;
3064 mFastMixerFutex = 0;
3065 if (kUseFastMixer == FastMixer_Dynamic) {
3066 mNormalSink = mOutputSink;
3067 }
3068 // If we go into cold idle, need to wait for acknowledgement
3069 // so that fast mixer stops doing I/O.
3070 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3071 }
3072 sq->end();
3073 }
3074 if (sq != NULL) {
3075 sq->end(didModify);
3076 sq->push(block);
3077 }
3078
3079 // Now perform the deferred reset on fast tracks that have stopped
3080 while (resetMask != 0) {
3081 size_t i = __builtin_ctz(resetMask);
3082 ALOG_ASSERT(i < count);
3083 resetMask &= ~(1 << i);
3084 sp<Track> t = mActiveTracks[i].promote();
3085 if (t == 0) continue;
3086 Track* track = t.get();
3087 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3088 track->reset();
3089 }
Glenn Kasten58912562012-04-03 10:45:00 -07003090
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 // remove all the tracks that need to be...
3092 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003093 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 for (size_t i=0 ; i<count ; i++) {
3095 const sp<Track>& track = tracksToRemove->itemAt(i);
3096 mActiveTracks.remove(track);
3097 if (track->mainBuffer() != mMixBuffer) {
3098 chain = getEffectChain_l(track->sessionId());
3099 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003100 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003101 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 }
3103 }
3104 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003105 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003106 }
3107 }
3108 }
3109
3110 // mix buffer must be cleared if all tracks are connected to an
3111 // effect chain as in this case the mixer will not write to
3112 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003113 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3114 // FIXME as a performance optimization, should remember previous zero status
3115 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 }
3117
Glenn Kasten58912562012-04-03 10:45:00 -07003118 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003119 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003120 if (fastTracks > 0) {
3121 mixerStatus = MIXER_TRACKS_READY;
3122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 return mixerStatus;
3124}
3125
Glenn Kasten66fcab92012-02-24 14:59:21 -08003126/*
3127The derived values that are cached:
3128 - mixBufferSize from frame count * frame size
3129 - activeSleepTime from activeSleepTimeUs()
3130 - idleSleepTime from idleSleepTimeUs()
3131 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3132 - maxPeriod from frame count and sample rate (MIXER only)
3133
3134The parameters that affect these derived values are:
3135 - frame count
3136 - frame size
3137 - sample rate
3138 - device type: A2DP or not
3139 - device latency
3140 - format: PCM or not
3141 - active sleep time
3142 - idle sleep time
3143*/
3144
3145void AudioFlinger::PlaybackThread::cacheParameters_l()
3146{
Glenn Kasten58912562012-04-03 10:45:00 -07003147 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003148 activeSleepTime = activeSleepTimeUs();
3149 idleSleepTime = idleSleepTimeUs();
3150}
3151
Glenn Kastenfff6d712012-01-12 16:38:12 -08003152void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153{
Steve Block3856b092011-10-20 11:56:00 +01003154 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003155 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003157
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 size_t size = mTracks.size();
3159 for (size_t i = 0; i < size; i++) {
3160 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003161 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003162 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 }
3165 }
3166}
3167
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003169int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003171 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172}
3173
3174// deleteTrackName_l() must be called with ThreadBase::mLock held
3175void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3176{
Steve Block3856b092011-10-20 11:56:00 +01003177 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178 mAudioMixer->deleteTrackName(name);
3179}
3180
3181// checkForNewParameters_l() must be called with ThreadBase::mLock held
3182bool AudioFlinger::MixerThread::checkForNewParameters_l()
3183{
Glenn Kasten58912562012-04-03 10:45:00 -07003184 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3185 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 bool reconfig = false;
3187
3188 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003189
3190 if (mFastMixer != NULL) {
3191 FastMixerStateQueue *sq = mFastMixer->sq();
3192 FastMixerState *state = sq->begin();
3193 if (!(state->mCommand & FastMixerState::IDLE)) {
3194 previousCommand = state->mCommand;
3195 state->mCommand = FastMixerState::HOT_IDLE;
3196 sq->end();
3197 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3198 } else {
3199 sq->end(false /*didModify*/);
3200 }
3201 }
3202
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 status_t status = NO_ERROR;
3204 String8 keyValuePair = mNewParameters[0];
3205 AudioParameter param = AudioParameter(keyValuePair);
3206 int value;
3207
3208 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3209 reconfig = true;
3210 }
3211 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003212 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 status = BAD_VALUE;
3214 } else {
3215 reconfig = true;
3216 }
3217 }
3218 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003219 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 status = BAD_VALUE;
3221 } else {
3222 reconfig = true;
3223 }
3224 }
3225 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3226 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003227 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 // if frame count is changed after track creation
3229 if (!mTracks.isEmpty()) {
3230 status = INVALID_OPERATION;
3231 } else {
3232 reconfig = true;
3233 }
3234 }
3235 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003236#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003237 // when changing the audio output device, call addBatteryData to notify
3238 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003239 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003240 uint32_t params = 0;
3241 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003242 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003243 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3244 }
3245
3246 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003247 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003248 // check if any other device (except speaker) is on
3249 if (value & deviceWithoutSpeaker ) {
3250 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3251 }
3252
3253 if (params != 0) {
3254 addBatteryData(params);
3255 }
3256 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003257#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003258
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 // forward device change to effects that have requested to be
3260 // aware of attached audio device.
3261 mDevice = (uint32_t)value;
3262 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003263 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 }
3265 }
3266
3267 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003268 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003269 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003271 mOutput->stream->common.standby(&mOutput->stream->common);
3272 mStandby = true;
3273 mBytesWritten = 0;
3274 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003275 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 }
3277 if (status == NO_ERROR && reconfig) {
3278 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003279 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3280 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003282 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003284 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 if (name < 0) break;
3286 mTracks[i]->mName = name;
3287 // limit track sample rate to 2 x new output sample rate
3288 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3289 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3290 }
3291 }
3292 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3293 }
3294 }
3295
3296 mNewParameters.removeAt(0);
3297
3298 mParamStatus = status;
3299 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003300 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3301 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003302 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 }
Glenn Kasten58912562012-04-03 10:45:00 -07003304
3305 if (!(previousCommand & FastMixerState::IDLE)) {
3306 ALOG_ASSERT(mFastMixer != NULL);
3307 FastMixerStateQueue *sq = mFastMixer->sq();
3308 FastMixerState *state = sq->begin();
3309 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3310 state->mCommand = previousCommand;
3311 sq->end();
3312 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3313 }
3314
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 return reconfig;
3316}
3317
3318status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3319{
3320 const size_t SIZE = 256;
3321 char buffer[SIZE];
3322 String8 result;
3323
3324 PlaybackThread::dumpInternals(fd, args);
3325
3326 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3327 result.append(buffer);
3328 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003329
3330 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3331 FastMixerDumpState copy = mFastMixerDumpState;
3332 copy.dump(fd);
3333
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 return NO_ERROR;
3335}
3336
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003337uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338{
Glenn Kasten58912562012-04-03 10:45:00 -07003339 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340}
3341
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003342uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003343{
Glenn Kasten58912562012-04-03 10:45:00 -07003344 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003345}
3346
Glenn Kasten66fcab92012-02-24 14:59:21 -08003347void AudioFlinger::MixerThread::cacheParameters_l()
3348{
3349 PlaybackThread::cacheParameters_l();
3350
3351 // FIXME: Relaxed timing because of a certain device that can't meet latency
3352 // Should be reduced to 2x after the vendor fixes the driver issue
3353 // increase threshold again due to low power audio mode. The way this warning
3354 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003355 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003356}
3357
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003359AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3360 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003361 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003362 // mLeftVolFloat, mRightVolFloat
3363 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003364{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365}
3366
3367AudioFlinger::DirectOutputThread::~DirectOutputThread()
3368{
3369}
3370
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003371AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3372 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003373)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003375 sp<Track> trackToRemove;
3376
Glenn Kastenfec279f2012-03-08 07:47:15 -08003377 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378
Glenn Kasten952eeb22012-03-06 11:30:57 -08003379 // find out which tracks need to be processed
3380 if (mActiveTracks.size() != 0) {
3381 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003382 // The track died recently
3383 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384
Glenn Kasten952eeb22012-03-06 11:30:57 -08003385 Track* const track = t.get();
3386 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387
Glenn Kasten952eeb22012-03-06 11:30:57 -08003388 // The first time a track is added we wait
3389 // for all its buffers to be filled before processing it
3390 if (cblk->framesReady() && track->isReady() &&
3391 !track->isPaused() && !track->isTerminated())
3392 {
3393 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394
Glenn Kasten952eeb22012-03-06 11:30:57 -08003395 if (track->mFillingUpStatus == Track::FS_FILLED) {
3396 track->mFillingUpStatus = Track::FS_ACTIVE;
3397 mLeftVolFloat = mRightVolFloat = 0;
3398 mLeftVolShort = mRightVolShort = 0;
3399 if (track->mState == TrackBase::RESUMING) {
3400 track->mState = TrackBase::ACTIVE;
3401 rampVolume = true;
3402 }
3403 } else if (cblk->server != 0) {
3404 // If the track is stopped before the first frame was mixed,
3405 // do not apply ramp
3406 rampVolume = true;
3407 }
3408 // compute volume for this track
3409 float left, right;
3410 if (track->isMuted() || mMasterMute || track->isPausing() ||
3411 mStreamTypes[track->streamType()].mute) {
3412 left = right = 0;
3413 if (track->isPausing()) {
3414 track->setPaused();
3415 }
3416 } else {
3417 float typeVolume = mStreamTypes[track->streamType()].volume;
3418 float v = mMasterVolume * typeVolume;
3419 uint32_t vlr = cblk->getVolumeLR();
3420 float v_clamped = v * (vlr & 0xFFFF);
3421 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3422 left = v_clamped/MAX_GAIN;
3423 v_clamped = v * (vlr >> 16);
3424 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3425 right = v_clamped/MAX_GAIN;
3426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427
Glenn Kasten952eeb22012-03-06 11:30:57 -08003428 if (left != mLeftVolFloat || right != mRightVolFloat) {
3429 mLeftVolFloat = left;
3430 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431
Glenn Kasten952eeb22012-03-06 11:30:57 -08003432 // If audio HAL implements volume control,
3433 // force software volume to nominal value
3434 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3435 left = 1.0f;
3436 right = 1.0f;
3437 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438
Glenn Kasten952eeb22012-03-06 11:30:57 -08003439 // Convert volumes from float to 8.24
3440 uint32_t vl = (uint32_t)(left * (1 << 24));
3441 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442
Glenn Kasten952eeb22012-03-06 11:30:57 -08003443 // Delegate volume control to effect in track effect chain if needed
3444 // only one effect chain can be present on DirectOutputThread, so if
3445 // there is one, the track is connected to it
3446 if (!mEffectChains.isEmpty()) {
3447 // Do not ramp volume if volume is controlled by effect
3448 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 rampVolume = false;
3450 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452
Glenn Kasten952eeb22012-03-06 11:30:57 -08003453 // Convert volumes from 8.24 to 4.12 format
3454 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3455 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3456 leftVol = (uint16_t)v_clamped;
3457 v_clamped = (vr + (1 << 11)) >> 12;
3458 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3459 rightVol = (uint16_t)v_clamped;
3460 } else {
3461 leftVol = mLeftVolShort;
3462 rightVol = mRightVolShort;
3463 rampVolume = false;
3464 }
3465
3466 // reset retry count
3467 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003468 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003469 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003470 } else {
3471 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3472 if (track->isStopped()) {
3473 track->reset();
3474 }
3475 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3476 // We have consumed all the buffers of this track.
3477 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003478 // TODO: implement behavior for compressed audio
3479 size_t audioHALFrames =
3480 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3481 size_t framesWritten =
3482 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3483 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3484 trackToRemove = track;
3485 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003486 } else {
3487 // No buffers for this track. Give it a few chances to
3488 // fill a buffer, then remove it from active list.
3489 if (--(track->mRetryCount) <= 0) {
3490 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3491 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003493 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 }
3495 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003496 }
3497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003499 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003500 // remove all the tracks that need to be...
3501 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003502 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003503 mActiveTracks.remove(trackToRemove);
3504 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003505 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003506 trackToRemove->sessionId());
3507 mEffectChains[0]->decActiveTrackCnt();
3508 }
3509 if (trackToRemove->isTerminated()) {
3510 removeTrack_l(trackToRemove);
3511 }
3512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513
Glenn Kastenfec279f2012-03-08 07:47:15 -08003514 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003515}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516
Glenn Kasten000f0e32012-03-01 17:10:56 -08003517void AudioFlinger::DirectOutputThread::threadLoop_mix()
3518{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003519 AudioBufferProvider::Buffer buffer;
3520 size_t frameCount = mFrameCount;
3521 int8_t *curBuf = (int8_t *)mMixBuffer;
3522 // output audio to hardware
3523 while (frameCount) {
3524 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003525 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003526 if (CC_UNLIKELY(buffer.raw == NULL)) {
3527 memset(curBuf, 0, frameCount * mFrameSize);
3528 break;
3529 }
3530 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3531 frameCount -= buffer.frameCount;
3532 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003533 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003534 }
3535 sleepTime = 0;
3536 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003537 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003538
3539 // apply volume
3540
3541 // Do not apply volume on compressed audio
3542 if (!audio_is_linear_pcm(mFormat)) {
3543 return;
3544 }
3545
3546 // convert to signed 16 bit before volume calculation
3547 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3548 size_t count = mFrameCount * mChannelCount;
3549 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3550 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003551 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003552 *dst-- = (int16_t)(*src--^0x80) << 8;
3553 }
3554 }
3555
3556 frameCount = mFrameCount;
3557 int16_t *out = mMixBuffer;
3558 if (rampVolume) {
3559 if (mChannelCount == 1) {
3560 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3561 int32_t vlInc = d / (int32_t)frameCount;
3562 int32_t vl = ((int32_t)mLeftVolShort << 16);
3563 do {
3564 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3565 out++;
3566 vl += vlInc;
3567 } while (--frameCount);
3568
3569 } else {
3570 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3571 int32_t vlInc = d / (int32_t)frameCount;
3572 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3573 int32_t vrInc = d / (int32_t)frameCount;
3574 int32_t vl = ((int32_t)mLeftVolShort << 16);
3575 int32_t vr = ((int32_t)mRightVolShort << 16);
3576 do {
3577 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3578 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3579 out += 2;
3580 vl += vlInc;
3581 vr += vrInc;
3582 } while (--frameCount);
3583 }
3584 } else {
3585 if (mChannelCount == 1) {
3586 do {
3587 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3588 out++;
3589 } while (--frameCount);
3590 } else {
3591 do {
3592 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3593 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3594 out += 2;
3595 } while (--frameCount);
3596 }
3597 }
3598
3599 // convert back to unsigned 8 bit after volume calculation
3600 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3601 size_t count = mFrameCount * mChannelCount;
3602 int16_t *src = mMixBuffer;
3603 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003604 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003605 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3606 }
3607 }
3608
3609 mLeftVolShort = leftVol;
3610 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003611}
3612
3613void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3614{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003615 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003616 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003617 sleepTime = activeSleepTime;
3618 } else {
3619 sleepTime = idleSleepTime;
3620 }
3621 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003622 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003623 sleepTime = 0;
3624 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625}
3626
3627// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003628int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629{
3630 return 0;
3631}
3632
3633// deleteTrackName_l() must be called with ThreadBase::mLock held
3634void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3635{
3636}
3637
3638// checkForNewParameters_l() must be called with ThreadBase::mLock held
3639bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3640{
3641 bool reconfig = false;
3642
3643 while (!mNewParameters.isEmpty()) {
3644 status_t status = NO_ERROR;
3645 String8 keyValuePair = mNewParameters[0];
3646 AudioParameter param = AudioParameter(keyValuePair);
3647 int value;
3648
3649 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3650 // do not accept frame count changes if tracks are open as the track buffer
3651 // size depends on frame count and correct behavior would not be garantied
3652 // if frame count is changed after track creation
3653 if (!mTracks.isEmpty()) {
3654 status = INVALID_OPERATION;
3655 } else {
3656 reconfig = true;
3657 }
3658 }
3659 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003660 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003661 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003662 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003663 mOutput->stream->common.standby(&mOutput->stream->common);
3664 mStandby = true;
3665 mBytesWritten = 0;
3666 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003667 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003668 }
3669 if (status == NO_ERROR && reconfig) {
3670 readOutputParameters();
3671 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3672 }
3673 }
3674
3675 mNewParameters.removeAt(0);
3676
3677 mParamStatus = status;
3678 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003679 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3680 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003681 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 }
3683 return reconfig;
3684}
3685
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003686uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687{
3688 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003689 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003690 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 } else {
3692 time = 10000;
3693 }
3694 return time;
3695}
3696
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003697uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698{
3699 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003700 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003701 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702 } else {
3703 time = 10000;
3704 }
3705 return time;
3706}
3707
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003708uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003709{
3710 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003711 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003712 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3713 } else {
3714 time = 10000;
3715 }
3716 return time;
3717}
3718
Glenn Kasten66fcab92012-02-24 14:59:21 -08003719void AudioFlinger::DirectOutputThread::cacheParameters_l()
3720{
3721 PlaybackThread::cacheParameters_l();
3722
3723 // use shorter standby delay as on normal output to release
3724 // hardware resources as soon as possible
3725 standbyDelay = microseconds(activeSleepTime*2);
3726}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003727
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728// ----------------------------------------------------------------------------
3729
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003730AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003731 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003732 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3733 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735 addOutputTrack(mainThread);
3736}
3737
3738AudioFlinger::DuplicatingThread::~DuplicatingThread()
3739{
3740 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3741 mOutputTracks[i]->destroy();
3742 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743}
3744
Glenn Kasten000f0e32012-03-01 17:10:56 -08003745void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003747 // mix buffers...
3748 if (outputsReady(outputTracks)) {
3749 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3750 } else {
3751 memset(mMixBuffer, 0, mixBufferSize);
3752 }
3753 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003754 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003755}
3756
3757void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3758{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003759 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003760 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003761 sleepTime = activeSleepTime;
3762 } else {
3763 sleepTime = idleSleepTime;
3764 }
3765 } else if (mBytesWritten != 0) {
3766 // flush remaining overflow buffers in output tracks
3767 for (size_t i = 0; i < outputTracks.size(); i++) {
3768 if (outputTracks[i]->isActive()) {
3769 sleepTime = 0;
3770 writeFrames = 0;
3771 memset(mMixBuffer, 0, mixBufferSize);
3772 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 }
3775 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003776}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777
Glenn Kasten000f0e32012-03-01 17:10:56 -08003778void AudioFlinger::DuplicatingThread::threadLoop_write()
3779{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003780 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003781 for (size_t i = 0; i < outputTracks.size(); i++) {
3782 outputTracks[i]->write(mMixBuffer, writeFrames);
3783 }
3784 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003785}
Glenn Kasten688a6402012-02-29 07:57:06 -08003786
Glenn Kasten000f0e32012-03-01 17:10:56 -08003787void AudioFlinger::DuplicatingThread::threadLoop_standby()
3788{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003789 // DuplicatingThread implements standby by stopping all tracks
3790 for (size_t i = 0; i < outputTracks.size(); i++) {
3791 outputTracks[i]->stop();
3792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793}
3794
Glenn Kastenfa26a852012-03-06 11:28:04 -08003795void AudioFlinger::DuplicatingThread::saveOutputTracks()
3796{
3797 outputTracks = mOutputTracks;
3798}
3799
3800void AudioFlinger::DuplicatingThread::clearOutputTracks()
3801{
3802 outputTracks.clear();
3803}
3804
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3806{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003807 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003808 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003809 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003810 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003811 this,
3812 mSampleRate,
3813 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003814 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815 frameCount);
3816 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003817 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003819 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003820 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821 }
3822}
3823
3824void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3825{
3826 Mutex::Autolock _l(mLock);
3827 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003828 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829 mOutputTracks[i]->destroy();
3830 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003831 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003832 return;
3833 }
3834 }
Steve Block3856b092011-10-20 11:56:00 +01003835 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836}
3837
Glenn Kasten438b0362012-03-06 11:24:48 -08003838// caller must hold mLock
3839void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840{
3841 mWaitTimeMs = UINT_MAX;
3842 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3843 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003844 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003845 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3846 if (waitTimeMs < mWaitTimeMs) {
3847 mWaitTimeMs = waitTimeMs;
3848 }
3849 }
3850 }
3851}
3852
3853
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003854bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003855{
3856 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003857 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003859 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003860 return false;
3861 }
3862 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3863 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003864 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 return false;
3866 }
3867 }
3868 return true;
3869}
3870
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003871uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872{
3873 return (mWaitTimeMs * 1000) / 2;
3874}
3875
Glenn Kasten66fcab92012-02-24 14:59:21 -08003876void AudioFlinger::DuplicatingThread::cacheParameters_l()
3877{
3878 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3879 updateWaitTime_l();
3880
3881 MixerThread::cacheParameters_l();
3882}
3883
Mathias Agopian65ab4712010-07-14 17:59:35 -07003884// ----------------------------------------------------------------------------
3885
3886// TrackBase constructor must be called with AudioFlinger::mLock held
3887AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003888 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889 const sp<Client>& client,
3890 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003891 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003892 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 const sp<IMemory>& sharedBuffer,
3895 int sessionId)
3896 : RefBase(),
3897 mThread(thread),
3898 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003899 mCblk(NULL),
3900 // mBuffer
3901 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 mFrameCount(0),
3903 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003904 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003906 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003907 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003908 // mChannelCount
3909 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910{
Steve Block3856b092011-10-20 11:56:00 +01003911 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912
Steve Blockb8a80522011-12-20 16:23:08 +00003913 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003914 size_t size = sizeof(audio_track_cblk_t);
3915 uint8_t channelCount = popcount(channelMask);
3916 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3917 if (sharedBuffer == 0) {
3918 size += bufferSize;
3919 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003921 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003922 mCblkMemory = client->heap()->allocate(size);
3923 if (mCblkMemory != 0) {
3924 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003925 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926 new(mCblk) audio_track_cblk_t();
3927 // clear all buffers
3928 mCblk->frameCount = frameCount;
3929 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003930// uncomment the following lines to quickly test 32-bit wraparound
3931// mCblk->user = 0xffff0000;
3932// mCblk->server = 0xffff0000;
3933// mCblk->userBase = 0xffff0000;
3934// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003935 mChannelCount = channelCount;
3936 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937 if (sharedBuffer == 0) {
3938 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3939 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3940 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003941 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942 mCblk->flags = CBLK_UNDERRUN_ON;
3943 } else {
3944 mBuffer = sharedBuffer->pointer();
3945 }
3946 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3947 }
3948 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003949 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950 client->heap()->dump("AudioTrack");
3951 return;
3952 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003953 } else {
3954 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003955 // construct the shared structure in-place.
3956 new(mCblk) audio_track_cblk_t();
3957 // clear all buffers
3958 mCblk->frameCount = frameCount;
3959 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003960// uncomment the following lines to quickly test 32-bit wraparound
3961// mCblk->user = 0xffff0000;
3962// mCblk->server = 0xffff0000;
3963// mCblk->userBase = 0xffff0000;
3964// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003965 mChannelCount = channelCount;
3966 mChannelMask = channelMask;
3967 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3968 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3969 // Force underrun condition to avoid false underrun callback until first data is
3970 // written to buffer (other flags are cleared)
3971 mCblk->flags = CBLK_UNDERRUN_ON;
3972 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003973 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974}
3975
3976AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3977{
Glenn Kastena0d68332012-01-27 16:47:15 -08003978 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003979 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003981 } else {
3982 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983 }
3984 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003985 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003986 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003987 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003989 // If the client's reference count drops to zero, the associated destructor
3990 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3991 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 mClient.clear();
3993 }
3994}
3995
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003996// AudioBufferProvider interface
3997// getNextBuffer() = 0;
3998// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4000{
Glenn Kastene0feee32011-12-13 11:53:26 -08004001 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004003 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004004 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005 buffer->frameCount = 0;
4006}
4007
4008bool AudioFlinger::ThreadBase::TrackBase::step() {
4009 bool result;
4010 audio_track_cblk_t* cblk = this->cblk();
4011
4012 result = cblk->stepServer(mFrameCount);
4013 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004014 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004015 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004016 }
4017 return result;
4018}
4019
4020void AudioFlinger::ThreadBase::TrackBase::reset() {
4021 audio_track_cblk_t* cblk = this->cblk();
4022
4023 cblk->user = 0;
4024 cblk->server = 0;
4025 cblk->userBase = 0;
4026 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004027 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004028 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029}
4030
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4032 return (int)mCblk->sampleRate;
4033}
4034
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4036 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004037 size_t frameSize = cblk->frameSize;
4038 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4039 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040
4041 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004042 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4043 "TrackBase::getBuffer buffer out of range:\n"
4044 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4045 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004047 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048
4049 return bufferStart;
4050}
4051
Eric Laurenta011e352012-03-29 15:51:43 -07004052status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4053{
4054 mSyncEvents.add(event);
4055 return NO_ERROR;
4056}
4057
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058// ----------------------------------------------------------------------------
4059
4060// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4061AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004062 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004064 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004066 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004067 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068 int frameCount,
4069 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004070 int sessionId,
4071 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004072 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004073 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004074 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004075 // mRetryCount initialized later when needed
4076 mSharedBuffer(sharedBuffer),
4077 mStreamType(streamType),
4078 mName(-1), // see note below
4079 mMainBuffer(thread->mixBuffer()),
4080 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004081 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004082 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004083 mFlags(flags),
4084 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004085 mObservedUnderruns(0),
4086 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004087 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088{
4089 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4091 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004092 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004093 if (flags & IAudioFlinger::TRACK_FAST) {
4094 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4095 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4096 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4097 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004098 // FIXME This is too eager. We allocate a fast track index before the
4099 // fast track becomes active. Since fast tracks are a scarce resource,
4100 // this means we are potentially denying other more important fast tracks from
4101 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004102 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004103 // Read the initial underruns because this field is never cleared by the fast mixer
4104 mObservedUnderruns = thread->getFastTrackUnderruns(i) & ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07004105 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004106 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004107 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004108 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004109 if (mName < 0) {
4110 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004111 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4112 // then we leak a fast track index. Should swap these two sections, or better yet
4113 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004116 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117}
4118
4119AudioFlinger::PlaybackThread::Track::~Track()
4120{
Steve Block3856b092011-10-20 11:56:00 +01004121 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 sp<ThreadBase> thread = mThread.promote();
4123 if (thread != 0) {
4124 Mutex::Autolock _l(thread->mLock);
4125 mState = TERMINATED;
4126 }
4127}
4128
4129void AudioFlinger::PlaybackThread::Track::destroy()
4130{
4131 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4132 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004133 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134 // we must acquire a strong reference on this Track before locking mLock
4135 // here so that the destructor is called only when exiting this function.
4136 // On the other hand, as long as Track::destroy() is only called by
4137 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4138 // this Track with its member mTrack.
4139 sp<Track> keep(this);
4140 { // scope for mLock
4141 sp<ThreadBase> thread = mThread.promote();
4142 if (thread != 0) {
4143 if (!isOutputTrack()) {
4144 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004145 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004146
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004147#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004148 // to track the speaker usage
4149 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004150#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 }
4152 AudioSystem::releaseOutput(thread->id());
4153 }
4154 Mutex::Autolock _l(thread->mLock);
4155 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4156 playbackThread->destroyTrack_l(this);
4157 }
4158 }
4159}
4160
Glenn Kasten288ed212012-04-25 17:52:27 -07004161/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4162{
Glenn Kastene213c862012-04-25 13:46:15 -07004163 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4164 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004165}
4166
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4168{
Glenn Kasten83d86532012-01-17 14:39:34 -08004169 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004170 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004171 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004172 } else {
4173 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4174 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004175 track_state state = mState;
4176 char stateChar;
4177 switch (state) {
4178 case IDLE:
4179 stateChar = 'I';
4180 break;
4181 case TERMINATED:
4182 stateChar = 'T';
4183 break;
4184 case STOPPED:
4185 stateChar = 'S';
4186 break;
4187 case RESUMING:
4188 stateChar = 'R';
4189 break;
4190 case ACTIVE:
4191 stateChar = 'A';
4192 break;
4193 case PAUSING:
4194 stateChar = 'p';
4195 break;
4196 case PAUSED:
4197 stateChar = 'P';
4198 break;
4199 default:
4200 stateChar = '?';
4201 break;
4202 }
4203 bool nowInUnderrun = mObservedUnderruns & 1;
Glenn Kastene213c862012-04-25 13:46:15 -07004204 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4205 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004206 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207 mStreamType,
4208 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004209 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 mSessionId,
4211 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004212 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004213 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 mMute,
4215 mFillingUpStatus,
4216 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004217 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4218 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 mCblk->server,
4220 mCblk->user,
4221 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004222 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004223 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004224 mUnderrunCount,
4225 nowInUnderrun ? '*' : ' ');
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226}
4227
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004228// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004229status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004230 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004232 audio_track_cblk_t* cblk = this->cblk();
4233 uint32_t framesReady;
4234 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004236 // Check if last stepServer failed, try to step now
4237 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004238 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4239 // Since the fast mixer is higher priority than client callback thread,
4240 // it does not result in priority inversion for client.
4241 // But a non-blocking solution would be preferable to avoid
4242 // fast mixer being unable to tryLock(), and
4243 // to avoid the extra context switches if the client wakes up,
4244 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004245 if (!step()) goto getNextBuffer_exit;
4246 ALOGV("stepServer recovered");
4247 mStepServerFailed = false;
4248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249
Glenn Kasten288ed212012-04-25 17:52:27 -07004250 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004251 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004253 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 uint32_t s = cblk->server;
4255 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4256
4257 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4258 if (framesReq > framesReady) {
4259 framesReq = framesReady;
4260 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004261 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 framesReq = bufferEnd - s;
4263 }
4264
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004265 buffer->raw = getBuffer(s, framesReq);
4266 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004268 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271
4272getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004273 buffer->raw = NULL;
4274 buffer->frameCount = 0;
4275 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4276 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277}
4278
Glenn Kasten288ed212012-04-25 17:52:27 -07004279// Note that framesReady() takes a mutex on the control block using tryLock().
4280// This could result in priority inversion if framesReady() is called by the normal mixer,
4281// as the normal mixer thread runs at lower
4282// priority than the client's callback thread: there is a short window within framesReady()
4283// during which the normal mixer could be preempted, and the client callback would block.
4284// Another problem can occur if framesReady() is called by the fast mixer:
4285// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4286// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4287size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004288 return mCblk->framesReady();
4289}
4290
Glenn Kasten288ed212012-04-25 17:52:27 -07004291// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004293 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294
John Grossman4ff14ba2012-02-08 16:37:41 -08004295 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4297 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004298 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 return true;
4300 }
4301 return false;
4302}
4303
Glenn Kasten3acbd052012-02-28 10:39:56 -08004304status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004305 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306{
4307 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004308 ALOGV("start(%d), calling pid %d session %d",
4309 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004310
Mathias Agopian65ab4712010-07-14 17:59:35 -07004311 sp<ThreadBase> thread = mThread.promote();
4312 if (thread != 0) {
4313 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004314 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 // here the track could be either new, or restarted
4316 // in both cases "unstop" the track
4317 if (mState == PAUSED) {
4318 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004319 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 } else {
4321 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004322 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 }
4324
4325 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4326 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004327 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004329
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004330#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004331 // to track the speaker usage
4332 if (status == NO_ERROR) {
4333 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4334 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004335#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336 }
4337 if (status == NO_ERROR) {
4338 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4339 playbackThread->addTrack_l(this);
4340 } else {
4341 mState = state;
4342 }
4343 } else {
4344 status = BAD_VALUE;
4345 }
4346 return status;
4347}
4348
4349void AudioFlinger::PlaybackThread::Track::stop()
4350{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004351 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 sp<ThreadBase> thread = mThread.promote();
4353 if (thread != 0) {
4354 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004355 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356 if (mState > STOPPED) {
4357 mState = STOPPED;
4358 // If the track is not active (PAUSED and buffers full), flush buffers
4359 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4360 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4361 reset();
4362 }
Steve Block3856b092011-10-20 11:56:00 +01004363 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004364 }
4365 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4366 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004367 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004369
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004370#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004371 // to track the speaker usage
4372 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004373#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374 }
4375 }
4376}
4377
4378void AudioFlinger::PlaybackThread::Track::pause()
4379{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004380 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 sp<ThreadBase> thread = mThread.promote();
4382 if (thread != 0) {
4383 Mutex::Autolock _l(thread->mLock);
4384 if (mState == ACTIVE || mState == RESUMING) {
4385 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004386 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004387 if (!isOutputTrack()) {
4388 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004389 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004391
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004392#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004393 // to track the speaker usage
4394 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004395#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 }
4397 }
4398 }
4399}
4400
4401void AudioFlinger::PlaybackThread::Track::flush()
4402{
Steve Block3856b092011-10-20 11:56:00 +01004403 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 sp<ThreadBase> thread = mThread.promote();
4405 if (thread != 0) {
4406 Mutex::Autolock _l(thread->mLock);
4407 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4408 return;
4409 }
4410 // No point remaining in PAUSED state after a flush => go to
4411 // STOPPED state
4412 mState = STOPPED;
4413
Eric Laurent38ccae22011-03-28 18:37:07 -07004414 // do not reset the track if it is still in the process of being stopped or paused.
4415 // this will be done by prepareTracks_l() when the track is stopped.
4416 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4417 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4418 reset();
4419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 }
4421}
4422
4423void AudioFlinger::PlaybackThread::Track::reset()
4424{
4425 // Do not reset twice to avoid discarding data written just after a flush and before
4426 // the audioflinger thread detects the track is stopped.
4427 if (!mResetDone) {
4428 TrackBase::reset();
4429 // Force underrun condition to avoid false underrun callback until first data is
4430 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004431 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4432 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 mFillingUpStatus = FS_FILLING;
4434 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004435 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 }
4437}
4438
4439void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4440{
4441 mMute = muted;
4442}
4443
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4445{
4446 status_t status = DEAD_OBJECT;
4447 sp<ThreadBase> thread = mThread.promote();
4448 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004449 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4450 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451 }
4452 return status;
4453}
4454
4455void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4456{
4457 mAuxEffectId = EffectId;
4458 mAuxBuffer = buffer;
4459}
4460
Eric Laurenta011e352012-03-29 15:51:43 -07004461bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4462 size_t audioHalFrames)
4463{
4464 // a track is considered presented when the total number of frames written to audio HAL
4465 // corresponds to the number of frames written when presentationComplete() is called for the
4466 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4467 if (mPresentationCompleteFrames == 0) {
4468 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4469 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4470 mPresentationCompleteFrames, audioHalFrames);
4471 }
4472 if (framesWritten >= mPresentationCompleteFrames) {
4473 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4474 mSessionId, framesWritten);
4475 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4476 mPresentationCompleteFrames = 0;
4477 return true;
4478 }
4479 return false;
4480}
4481
4482void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4483{
4484 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4485 if (mSyncEvents[i]->type() == type) {
4486 mSyncEvents[i]->trigger();
4487 mSyncEvents.removeAt(i);
4488 i--;
4489 }
4490 }
4491}
4492
Glenn Kasten58912562012-04-03 10:45:00 -07004493// implement VolumeBufferProvider interface
4494
4495uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4496{
4497 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4498 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4499 uint32_t vlr = mCblk->getVolumeLR();
4500 uint32_t vl = vlr & 0xFFFF;
4501 uint32_t vr = vlr >> 16;
4502 // track volumes come from shared memory, so can't be trusted and must be clamped
4503 if (vl > MAX_GAIN_INT) {
4504 vl = MAX_GAIN_INT;
4505 }
4506 if (vr > MAX_GAIN_INT) {
4507 vr = MAX_GAIN_INT;
4508 }
4509 // now apply the cached master volume and stream type volume;
4510 // this is trusted but lacks any synchronization or barrier so may be stale
4511 float v = mCachedVolume;
4512 vl *= v;
4513 vr *= v;
4514 // re-combine into U4.16
4515 vlr = (vr << 16) | (vl & 0xFFFF);
4516 // FIXME look at mute, pause, and stop flags
4517 return vlr;
4518}
Eric Laurenta011e352012-03-29 15:51:43 -07004519
John Grossman4ff14ba2012-02-08 16:37:41 -08004520// timed audio tracks
4521
4522sp<AudioFlinger::PlaybackThread::TimedTrack>
4523AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004524 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004525 const sp<Client>& client,
4526 audio_stream_type_t streamType,
4527 uint32_t sampleRate,
4528 audio_format_t format,
4529 uint32_t channelMask,
4530 int frameCount,
4531 const sp<IMemory>& sharedBuffer,
4532 int sessionId) {
4533 if (!client->reserveTimedTrack())
4534 return NULL;
4535
Glenn Kastena0356762012-03-19 10:38:51 -07004536 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004537 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4538 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004539}
4540
4541AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004542 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004543 const sp<Client>& client,
4544 audio_stream_type_t streamType,
4545 uint32_t sampleRate,
4546 audio_format_t format,
4547 uint32_t channelMask,
4548 int frameCount,
4549 const sp<IMemory>& sharedBuffer,
4550 int sessionId)
4551 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004552 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004553 mQueueHeadInFlight(false),
4554 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004555 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004556 mTimedSilenceBuffer(NULL),
4557 mTimedSilenceBufferSize(0),
4558 mTimedAudioOutputOnTime(false),
4559 mMediaTimeTransformValid(false)
4560{
4561 LocalClock lc;
4562 mLocalTimeFreq = lc.getLocalFreq();
4563
4564 mLocalTimeToSampleTransform.a_zero = 0;
4565 mLocalTimeToSampleTransform.b_zero = 0;
4566 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4567 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4568 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4569 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004570
4571 mMediaTimeToSampleTransform.a_zero = 0;
4572 mMediaTimeToSampleTransform.b_zero = 0;
4573 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4574 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4575 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4576 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004577}
4578
4579AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4580 mClient->releaseTimedTrack();
4581 delete [] mTimedSilenceBuffer;
4582}
4583
4584status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4585 size_t size, sp<IMemory>* buffer) {
4586
4587 Mutex::Autolock _l(mTimedBufferQueueLock);
4588
4589 trimTimedBufferQueue_l();
4590
4591 // lazily initialize the shared memory heap for timed buffers
4592 if (mTimedMemoryDealer == NULL) {
4593 const int kTimedBufferHeapSize = 512 << 10;
4594
4595 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4596 "AudioFlingerTimed");
4597 if (mTimedMemoryDealer == NULL)
4598 return NO_MEMORY;
4599 }
4600
4601 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4602 if (newBuffer == NULL) {
4603 newBuffer = mTimedMemoryDealer->allocate(size);
4604 if (newBuffer == NULL)
4605 return NO_MEMORY;
4606 }
4607
4608 *buffer = newBuffer;
4609 return NO_ERROR;
4610}
4611
4612// caller must hold mTimedBufferQueueLock
4613void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4614 int64_t mediaTimeNow;
4615 {
4616 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4617 if (!mMediaTimeTransformValid)
4618 return;
4619
4620 int64_t targetTimeNow;
4621 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4622 ? mCCHelper.getCommonTime(&targetTimeNow)
4623 : mCCHelper.getLocalTime(&targetTimeNow);
4624
4625 if (OK != res)
4626 return;
4627
4628 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4629 &mediaTimeNow)) {
4630 return;
4631 }
4632 }
4633
John Grossman1c345192012-03-27 14:00:17 -07004634 size_t trimEnd;
4635 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004636 int64_t bufEnd;
4637
John Grossmanc95cfbb2012-04-12 11:53:11 -07004638 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4639 // We have a next buffer. Just use its PTS as the PTS of the frame
4640 // following the last frame in this buffer. If the stream is sparse
4641 // (ie, there are deliberate gaps left in the stream which should be
4642 // filled with silence by the TimedAudioTrack), then this can result
4643 // in one extra buffer being left un-trimmed when it could have
4644 // been. In general, this is not typical, and we would rather
4645 // optimized away the TS calculation below for the more common case
4646 // where PTSes are contiguous.
4647 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4648 } else {
4649 // We have no next buffer. Compute the PTS of the frame following
4650 // the last frame in this buffer by computing the duration of of
4651 // this frame in media time units and adding it to the PTS of the
4652 // buffer.
4653 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4654 / mCblk->frameSize;
4655
4656 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4657 &bufEnd)) {
4658 ALOGE("Failed to convert frame count of %lld to media time"
4659 " duration" " (scale factor %d/%u) in %s",
4660 frameCount,
4661 mMediaTimeToSampleTransform.a_to_b_numer,
4662 mMediaTimeToSampleTransform.a_to_b_denom,
4663 __PRETTY_FUNCTION__);
4664 break;
4665 }
4666 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004667 }
John Grossman9fbdee12012-03-26 17:51:46 -07004668
4669 if (bufEnd > mediaTimeNow)
4670 break;
4671
4672 // Is the buffer we want to use in the middle of a mix operation right
4673 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4674 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004675 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004676 mTrimQueueHeadOnRelease = true;
4677 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004678 }
4679
John Grossman9fbdee12012-03-26 17:51:46 -07004680 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004681 if (trimStart < trimEnd) {
4682 // Update the bookkeeping for framesReady()
4683 for (size_t i = trimStart; i < trimEnd; ++i) {
4684 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4685 }
4686
4687 // Now actually remove the buffers from the queue.
4688 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004689 }
4690}
4691
John Grossman1c345192012-03-27 14:00:17 -07004692void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4693 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004694 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4695 "%s called (reason \"%s\"), but timed buffer queue has no"
4696 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004697
4698 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4699 mTimedBufferQueue.removeAt(0);
4700}
4701
4702void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4703 const TimedBuffer& buf,
4704 const char* logTag) {
4705 uint32_t bufBytes = buf.buffer()->size();
4706 uint32_t consumedAlready = buf.position();
4707
Eric Laurentb388e532012-04-14 13:32:48 -07004708 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004709 "Bad bookkeeping while updating frames pending. Timed buffer is"
4710 " only %u bytes long, but claims to have consumed %u"
4711 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004712 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004713
4714 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004715 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4716 "Bad bookkeeping while updating frames pending. Should have at"
4717 " least %u queued frames, but we think we have only %u. (update"
4718 " reason: \"%s\")",
4719 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004720
4721 mFramesPendingInQueue -= bufFrames;
4722}
4723
John Grossman4ff14ba2012-02-08 16:37:41 -08004724status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4725 const sp<IMemory>& buffer, int64_t pts) {
4726
4727 {
4728 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4729 if (!mMediaTimeTransformValid)
4730 return INVALID_OPERATION;
4731 }
4732
4733 Mutex::Autolock _l(mTimedBufferQueueLock);
4734
John Grossman1c345192012-03-27 14:00:17 -07004735 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4736 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004737 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4738
4739 return NO_ERROR;
4740}
4741
4742status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4743 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4744
John Grossman1c345192012-03-27 14:00:17 -07004745 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4746 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4747 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004748
4749 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4750 target == TimedAudioTrack::COMMON_TIME)) {
4751 return BAD_VALUE;
4752 }
4753
4754 Mutex::Autolock lock(mMediaTimeTransformLock);
4755 mMediaTimeTransform = xform;
4756 mMediaTimeTransformTarget = target;
4757 mMediaTimeTransformValid = true;
4758
4759 return NO_ERROR;
4760}
4761
4762#define min(a, b) ((a) < (b) ? (a) : (b))
4763
4764// implementation of getNextBuffer for tracks whose buffers have timestamps
4765status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4766 AudioBufferProvider::Buffer* buffer, int64_t pts)
4767{
4768 if (pts == AudioBufferProvider::kInvalidPTS) {
4769 buffer->raw = 0;
4770 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004771 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004772 return INVALID_OPERATION;
4773 }
4774
John Grossman4ff14ba2012-02-08 16:37:41 -08004775 Mutex::Autolock _l(mTimedBufferQueueLock);
4776
John Grossman9fbdee12012-03-26 17:51:46 -07004777 ALOG_ASSERT(!mQueueHeadInFlight,
4778 "getNextBuffer called without releaseBuffer!");
4779
John Grossman4ff14ba2012-02-08 16:37:41 -08004780 while (true) {
4781
4782 // if we have no timed buffers, then fail
4783 if (mTimedBufferQueue.isEmpty()) {
4784 buffer->raw = 0;
4785 buffer->frameCount = 0;
4786 return NOT_ENOUGH_DATA;
4787 }
4788
4789 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4790
4791 // calculate the PTS of the head of the timed buffer queue expressed in
4792 // local time
4793 int64_t headLocalPTS;
4794 {
4795 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4796
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004797 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004798
4799 if (mMediaTimeTransform.a_to_b_denom == 0) {
4800 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004801 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004802 return NO_ERROR;
4803 }
4804
4805 int64_t transformedPTS;
4806 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4807 &transformedPTS)) {
4808 // the transform failed. this shouldn't happen, but if it does
4809 // then just drop this buffer
4810 ALOGW("timedGetNextBuffer transform failed");
4811 buffer->raw = 0;
4812 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004813 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004814 return NO_ERROR;
4815 }
4816
4817 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4818 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4819 &headLocalPTS)) {
4820 buffer->raw = 0;
4821 buffer->frameCount = 0;
4822 return INVALID_OPERATION;
4823 }
4824 } else {
4825 headLocalPTS = transformedPTS;
4826 }
4827 }
4828
4829 // adjust the head buffer's PTS to reflect the portion of the head buffer
4830 // that has already been consumed
4831 int64_t effectivePTS = headLocalPTS +
4832 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4833
4834 // Calculate the delta in samples between the head of the input buffer
4835 // queue and the start of the next output buffer that will be written.
4836 // If the transformation fails because of over or underflow, it means
4837 // that the sample's position in the output stream is so far out of
4838 // whack that it should just be dropped.
4839 int64_t sampleDelta;
4840 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4841 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004842 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4843 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004844 continue;
4845 }
4846 if (!mLocalTimeToSampleTransform.doForwardTransform(
4847 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004848 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004849 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004850 continue;
4851 }
4852
John Grossman1c345192012-03-27 14:00:17 -07004853 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4854 " sampleDelta=[%d.%08x]",
4855 head.pts(), head.position(), pts,
4856 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4857 + (sampleDelta >> 32)),
4858 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004859
4860 // if the delta between the ideal placement for the next input sample and
4861 // the current output position is within this threshold, then we will
4862 // concatenate the next input samples to the previous output
4863 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004864 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004865
4866 // if this is the first buffer of audio that we're emitting from this track
4867 // then it should be almost exactly on time.
4868 const int64_t kSampleStartupThreshold = 1LL << 32;
4869
4870 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004871 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004872 // the next input is close enough to being on time, so concatenate it
4873 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004874 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004875
John Grossman1c345192012-03-27 14:00:17 -07004876 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4877 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004878 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004879 }
4880
4881 // Looks like our output is not on time. Reset our on timed status.
4882 // Next time we mix samples from our input queue, then should be within
4883 // the StartupThreshold.
4884 mTimedAudioOutputOnTime = false;
4885 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004886 // the gap between the current output position and the proper start of
4887 // the next input sample is too big, so fill it with silence
4888 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4889
John Grossman9fbdee12012-03-26 17:51:46 -07004890 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004891 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4892 return NO_ERROR;
4893 } else {
4894 // the next input sample is late
4895 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4896 size_t onTimeSamplePosition =
4897 head.position() + lateFrames * mCblk->frameSize;
4898
4899 if (onTimeSamplePosition > head.buffer()->size()) {
4900 // all the remaining samples in the head are too late, so
4901 // drop it and move on
4902 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004903 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004904 continue;
4905 } else {
4906 // skip over the late samples
4907 head.setPosition(onTimeSamplePosition);
4908
4909 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004910 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004911
4912 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4913 return NO_ERROR;
4914 }
4915 }
4916 }
4917}
4918
4919// Yield samples from the timed buffer queue head up to the given output
4920// buffer's capacity.
4921//
4922// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004923void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004924 AudioBufferProvider::Buffer* buffer) {
4925
4926 const TimedBuffer& head = mTimedBufferQueue[0];
4927
4928 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4929 head.position());
4930
4931 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4932 mCblk->frameSize);
4933 size_t framesRequested = buffer->frameCount;
4934 buffer->frameCount = min(framesLeftInHead, framesRequested);
4935
John Grossman9fbdee12012-03-26 17:51:46 -07004936 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004937 mTimedAudioOutputOnTime = true;
4938}
4939
4940// Yield samples of silence up to the given output buffer's capacity
4941//
4942// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004943void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004944 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4945
4946 // lazily allocate a buffer filled with silence
4947 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4948 delete [] mTimedSilenceBuffer;
4949 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4950 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4951 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4952 }
4953
4954 buffer->raw = mTimedSilenceBuffer;
4955 size_t framesRequested = buffer->frameCount;
4956 buffer->frameCount = min(numFrames, framesRequested);
4957
4958 mTimedAudioOutputOnTime = false;
4959}
4960
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004961// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004962void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4963 AudioBufferProvider::Buffer* buffer) {
4964
4965 Mutex::Autolock _l(mTimedBufferQueueLock);
4966
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004967 // If the buffer which was just released is part of the buffer at the head
4968 // of the queue, be sure to update the amt of the buffer which has been
4969 // consumed. If the buffer being returned is not part of the head of the
4970 // queue, its either because the buffer is part of the silence buffer, or
4971 // because the head of the timed queue was trimmed after the mixer called
4972 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004973 if (buffer->raw == mTimedSilenceBuffer) {
4974 ALOG_ASSERT(!mQueueHeadInFlight,
4975 "Queue head in flight during release of silence buffer!");
4976 goto done;
4977 }
4978
4979 ALOG_ASSERT(mQueueHeadInFlight,
4980 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4981 " head in flight.");
4982
4983 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004984 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004985
4986 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004987 void* end = reinterpret_cast<void*>(
4988 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4989 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004990
John Grossman9fbdee12012-03-26 17:51:46 -07004991 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4992 "released buffer not within the head of the timed buffer"
4993 " queue; qHead = [%p, %p], released buffer = %p",
4994 start, end, buffer->raw);
4995
4996 head.setPosition(head.position() +
4997 (buffer->frameCount * mCblk->frameSize));
4998 mQueueHeadInFlight = false;
4999
John Grossman1c345192012-03-27 14:00:17 -07005000 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5001 "Bad bookkeeping during releaseBuffer! Should have at"
5002 " least %u queued frames, but we think we have only %u",
5003 buffer->frameCount, mFramesPendingInQueue);
5004
5005 mFramesPendingInQueue -= buffer->frameCount;
5006
John Grossman9fbdee12012-03-26 17:51:46 -07005007 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5008 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005009 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005010 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005011 }
John Grossman9fbdee12012-03-26 17:51:46 -07005012 } else {
5013 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5014 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005015 }
5016
John Grossman9fbdee12012-03-26 17:51:46 -07005017done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005018 buffer->raw = 0;
5019 buffer->frameCount = 0;
5020}
5021
Glenn Kasten288ed212012-04-25 17:52:27 -07005022size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005023 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005024 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005025}
5026
5027AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5028 : mPTS(0), mPosition(0) {}
5029
5030AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5031 const sp<IMemory>& buffer, int64_t pts)
5032 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5033
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034// ----------------------------------------------------------------------------
5035
5036// RecordTrack constructor must be called with AudioFlinger::mLock held
5037AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005038 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 const sp<Client>& client,
5040 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005041 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005042 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044 int sessionId)
5045 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005046 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005047 mOverflow(false)
5048{
5049 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005050 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5051 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5052 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5053 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5054 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5055 } else {
5056 mCblk->frameSize = sizeof(int8_t);
5057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058 }
5059}
5060
5061AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5062{
5063 sp<ThreadBase> thread = mThread.promote();
5064 if (thread != 0) {
5065 AudioSystem::releaseInput(thread->id());
5066 }
5067}
5068
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005069// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005070status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005071{
5072 audio_track_cblk_t* cblk = this->cblk();
5073 uint32_t framesAvail;
5074 uint32_t framesReq = buffer->frameCount;
5075
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005076 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005077 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005079 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005080 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005081 }
5082
5083 framesAvail = cblk->framesAvailable_l();
5084
Glenn Kastenf6b16782011-12-15 09:51:17 -08005085 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 uint32_t s = cblk->server;
5087 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5088
5089 if (framesReq > framesAvail) {
5090 framesReq = framesAvail;
5091 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005092 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 framesReq = bufferEnd - s;
5094 }
5095
5096 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005097 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098
5099 buffer->frameCount = framesReq;
5100 return NO_ERROR;
5101 }
5102
5103getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005104 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105 buffer->frameCount = 0;
5106 return NOT_ENOUGH_DATA;
5107}
5108
Glenn Kasten3acbd052012-02-28 10:39:56 -08005109status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005110 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111{
5112 sp<ThreadBase> thread = mThread.promote();
5113 if (thread != 0) {
5114 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005115 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 } else {
5117 return BAD_VALUE;
5118 }
5119}
5120
5121void AudioFlinger::RecordThread::RecordTrack::stop()
5122{
5123 sp<ThreadBase> thread = mThread.promote();
5124 if (thread != 0) {
5125 RecordThread *recordThread = (RecordThread *)thread.get();
5126 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005127 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005128 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005129 // read from buffer
5130 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131 }
5132}
5133
5134void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5135{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005136 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005137 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005139 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005140 mSessionId,
5141 mFrameCount,
5142 mState,
5143 mCblk->sampleRate,
5144 mCblk->server,
5145 mCblk->user);
5146}
5147
5148
5149// ----------------------------------------------------------------------------
5150
5151AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005152 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005153 DuplicatingThread *sourceThread,
5154 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005155 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005156 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005157 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005158 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5159 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005160 mActive(false), mSourceThread(sourceThread)
5161{
5162
Mathias Agopian65ab4712010-07-14 17:59:35 -07005163 if (mCblk != NULL) {
5164 mCblk->flags |= CBLK_DIRECTION_OUT;
5165 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 mOutBuffer.frameCount = 0;
5167 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005168 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005169 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5170 mCblk, mBuffer, mCblk->buffers,
5171 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005173 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 }
5175}
5176
5177AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5178{
5179 clearBufferQueue();
5180}
5181
Glenn Kasten3acbd052012-02-28 10:39:56 -08005182status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005183 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005184{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005185 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 if (status != NO_ERROR) {
5187 return status;
5188 }
5189
5190 mActive = true;
5191 mRetryCount = 127;
5192 return status;
5193}
5194
5195void AudioFlinger::PlaybackThread::OutputTrack::stop()
5196{
5197 Track::stop();
5198 clearBufferQueue();
5199 mOutBuffer.frameCount = 0;
5200 mActive = false;
5201}
5202
5203bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5204{
5205 Buffer *pInBuffer;
5206 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005207 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005208 bool outputBufferFull = false;
5209 inBuffer.frameCount = frames;
5210 inBuffer.i16 = data;
5211
5212 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5213
5214 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005215 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 sp<ThreadBase> thread = mThread.promote();
5217 if (thread != 0) {
5218 MixerThread *mixerThread = (MixerThread *)thread.get();
5219 if (mCblk->frameCount > frames){
5220 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5221 uint32_t startFrames = (mCblk->frameCount - frames);
5222 pInBuffer = new Buffer;
5223 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5224 pInBuffer->frameCount = startFrames;
5225 pInBuffer->i16 = pInBuffer->mBuffer;
5226 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5227 mBufferQueue.add(pInBuffer);
5228 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005229 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005230 }
5231 }
5232 }
5233 }
5234
5235 while (waitTimeLeftMs) {
5236 // First write pending buffers, then new data
5237 if (mBufferQueue.size()) {
5238 pInBuffer = mBufferQueue.itemAt(0);
5239 } else {
5240 pInBuffer = &inBuffer;
5241 }
5242
5243 if (pInBuffer->frameCount == 0) {
5244 break;
5245 }
5246
5247 if (mOutBuffer.frameCount == 0) {
5248 mOutBuffer.frameCount = pInBuffer->frameCount;
5249 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005250 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005251 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005252 outputBufferFull = true;
5253 break;
5254 }
5255 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5256 if (waitTimeLeftMs >= waitTimeMs) {
5257 waitTimeLeftMs -= waitTimeMs;
5258 } else {
5259 waitTimeLeftMs = 0;
5260 }
5261 }
5262
5263 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5264 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5265 mCblk->stepUser(outFrames);
5266 pInBuffer->frameCount -= outFrames;
5267 pInBuffer->i16 += outFrames * channelCount;
5268 mOutBuffer.frameCount -= outFrames;
5269 mOutBuffer.i16 += outFrames * channelCount;
5270
5271 if (pInBuffer->frameCount == 0) {
5272 if (mBufferQueue.size()) {
5273 mBufferQueue.removeAt(0);
5274 delete [] pInBuffer->mBuffer;
5275 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005276 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005277 } else {
5278 break;
5279 }
5280 }
5281 }
5282
5283 // If we could not write all frames, allocate a buffer and queue it for next time.
5284 if (inBuffer.frameCount) {
5285 sp<ThreadBase> thread = mThread.promote();
5286 if (thread != 0 && !thread->standby()) {
5287 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5288 pInBuffer = new Buffer;
5289 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5290 pInBuffer->frameCount = inBuffer.frameCount;
5291 pInBuffer->i16 = pInBuffer->mBuffer;
5292 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5293 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005294 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005295 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005296 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297 }
5298 }
5299 }
5300
5301 // Calling write() with a 0 length buffer, means that no more data will be written:
5302 // If no more buffers are pending, fill output track buffer to make sure it is started
5303 // by output mixer.
5304 if (frames == 0 && mBufferQueue.size() == 0) {
5305 if (mCblk->user < mCblk->frameCount) {
5306 frames = mCblk->frameCount - mCblk->user;
5307 pInBuffer = new Buffer;
5308 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5309 pInBuffer->frameCount = frames;
5310 pInBuffer->i16 = pInBuffer->mBuffer;
5311 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5312 mBufferQueue.add(pInBuffer);
5313 } else if (mActive) {
5314 stop();
5315 }
5316 }
5317
5318 return outputBufferFull;
5319}
5320
5321status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5322{
5323 int active;
5324 status_t result;
5325 audio_track_cblk_t* cblk = mCblk;
5326 uint32_t framesReq = buffer->frameCount;
5327
Steve Block3856b092011-10-20 11:56:00 +01005328// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329 buffer->frameCount = 0;
5330
5331 uint32_t framesAvail = cblk->framesAvailable();
5332
5333
5334 if (framesAvail == 0) {
5335 Mutex::Autolock _l(cblk->lock);
5336 goto start_loop_here;
5337 while (framesAvail == 0) {
5338 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005339 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005340 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005341 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342 }
5343 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5344 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005345 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 }
5347 // read the server count again
5348 start_loop_here:
5349 framesAvail = cblk->framesAvailable_l();
5350 }
5351 }
5352
5353// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005354// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355// }
5356
5357 if (framesReq > framesAvail) {
5358 framesReq = framesAvail;
5359 }
5360
5361 uint32_t u = cblk->user;
5362 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5363
Marco Nelissena1472d92012-03-30 14:36:54 -07005364 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365 framesReq = bufferEnd - u;
5366 }
5367
5368 buffer->frameCount = framesReq;
5369 buffer->raw = (void *)cblk->buffer(u);
5370 return NO_ERROR;
5371}
5372
5373
5374void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5375{
5376 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377
5378 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005379 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380 delete [] pBuffer->mBuffer;
5381 delete pBuffer;
5382 }
5383 mBufferQueue.clear();
5384}
5385
5386// ----------------------------------------------------------------------------
5387
5388AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5389 : RefBase(),
5390 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005391 // 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 -07005392 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005393 mPid(pid),
5394 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395{
5396 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5397}
5398
5399// Client destructor must be called with AudioFlinger::mLock held
5400AudioFlinger::Client::~Client()
5401{
5402 mAudioFlinger->removeClient_l(mPid);
5403}
5404
Glenn Kasten435dbe62012-01-30 10:15:48 -08005405sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406{
5407 return mMemoryDealer;
5408}
5409
John Grossman4ff14ba2012-02-08 16:37:41 -08005410// Reserve one of the limited slots for a timed audio track associated
5411// with this client
5412bool AudioFlinger::Client::reserveTimedTrack()
5413{
5414 const int kMaxTimedTracksPerClient = 4;
5415
5416 Mutex::Autolock _l(mTimedTrackLock);
5417
5418 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5419 ALOGW("can not create timed track - pid %d has exceeded the limit",
5420 mPid);
5421 return false;
5422 }
5423
5424 mTimedTrackCount++;
5425 return true;
5426}
5427
5428// Release a slot for a timed audio track
5429void AudioFlinger::Client::releaseTimedTrack()
5430{
5431 Mutex::Autolock _l(mTimedTrackLock);
5432 mTimedTrackCount--;
5433}
5434
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435// ----------------------------------------------------------------------------
5436
5437AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5438 const sp<IAudioFlingerClient>& client,
5439 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005440 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441{
5442}
5443
5444AudioFlinger::NotificationClient::~NotificationClient()
5445{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446}
5447
5448void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5449{
5450 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005451 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452}
5453
5454// ----------------------------------------------------------------------------
5455
5456AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5457 : BnAudioTrack(),
5458 mTrack(track)
5459{
5460}
5461
5462AudioFlinger::TrackHandle::~TrackHandle() {
5463 // just stop the track on deletion, associated resources
5464 // will be freed from the main thread once all pending buffers have
5465 // been played. Unless it's not in the active track list, in which
5466 // case we free everything now...
5467 mTrack->destroy();
5468}
5469
Glenn Kasten90716c52012-01-26 13:40:12 -08005470sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5471 return mTrack->getCblk();
5472}
5473
Glenn Kasten3acbd052012-02-28 10:39:56 -08005474status_t AudioFlinger::TrackHandle::start() {
5475 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476}
5477
5478void AudioFlinger::TrackHandle::stop() {
5479 mTrack->stop();
5480}
5481
5482void AudioFlinger::TrackHandle::flush() {
5483 mTrack->flush();
5484}
5485
5486void AudioFlinger::TrackHandle::mute(bool e) {
5487 mTrack->mute(e);
5488}
5489
5490void AudioFlinger::TrackHandle::pause() {
5491 mTrack->pause();
5492}
5493
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5495{
5496 return mTrack->attachAuxEffect(EffectId);
5497}
5498
John Grossman4ff14ba2012-02-08 16:37:41 -08005499status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5500 sp<IMemory>* buffer) {
5501 if (!mTrack->isTimedTrack())
5502 return INVALID_OPERATION;
5503
5504 PlaybackThread::TimedTrack* tt =
5505 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5506 return tt->allocateTimedBuffer(size, buffer);
5507}
5508
5509status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5510 int64_t pts) {
5511 if (!mTrack->isTimedTrack())
5512 return INVALID_OPERATION;
5513
5514 PlaybackThread::TimedTrack* tt =
5515 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5516 return tt->queueTimedBuffer(buffer, pts);
5517}
5518
5519status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5520 const LinearTransform& xform, int target) {
5521
5522 if (!mTrack->isTimedTrack())
5523 return INVALID_OPERATION;
5524
5525 PlaybackThread::TimedTrack* tt =
5526 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5527 return tt->setMediaTimeTransform(
5528 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5529}
5530
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531status_t AudioFlinger::TrackHandle::onTransact(
5532 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5533{
5534 return BnAudioTrack::onTransact(code, data, reply, flags);
5535}
5536
5537// ----------------------------------------------------------------------------
5538
5539sp<IAudioRecord> AudioFlinger::openRecord(
5540 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005541 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005543 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005544 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005546 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 int *sessionId,
5548 status_t *status)
5549{
5550 sp<RecordThread::RecordTrack> recordTrack;
5551 sp<RecordHandle> recordHandle;
5552 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 status_t lStatus;
5554 RecordThread *thread;
5555 size_t inFrameCount;
5556 int lSessionId;
5557
5558 // check calling permissions
5559 if (!recordingAllowed()) {
5560 lStatus = PERMISSION_DENIED;
5561 goto Exit;
5562 }
5563
5564 // add client to list
5565 { // scope for mLock
5566 Mutex::Autolock _l(mLock);
5567 thread = checkRecordThread_l(input);
5568 if (thread == NULL) {
5569 lStatus = BAD_VALUE;
5570 goto Exit;
5571 }
5572
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005573 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005574
5575 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005576 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 lSessionId = *sessionId;
5578 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005579 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005580 if (sessionId != NULL) {
5581 *sessionId = lSessionId;
5582 }
5583 }
5584 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005585 recordTrack = thread->createRecordTrack_l(client,
5586 sampleRate,
5587 format,
5588 channelMask,
5589 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005590 lSessionId,
5591 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005593 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5595 // destructor is called by the TrackBase destructor with mLock held
5596 client.clear();
5597 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 goto Exit;
5599 }
5600
5601 // return to handle to client
5602 recordHandle = new RecordHandle(recordTrack);
5603 lStatus = NO_ERROR;
5604
5605Exit:
5606 if (status) {
5607 *status = lStatus;
5608 }
5609 return recordHandle;
5610}
5611
5612// ----------------------------------------------------------------------------
5613
5614AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5615 : BnAudioRecord(),
5616 mRecordTrack(recordTrack)
5617{
5618}
5619
5620AudioFlinger::RecordHandle::~RecordHandle() {
5621 stop();
5622}
5623
Glenn Kasten90716c52012-01-26 13:40:12 -08005624sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5625 return mRecordTrack->getCblk();
5626}
5627
Glenn Kasten3acbd052012-02-28 10:39:56 -08005628status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005629 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005630 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631}
5632
5633void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005634 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635 mRecordTrack->stop();
5636}
5637
Mathias Agopian65ab4712010-07-14 17:59:35 -07005638status_t AudioFlinger::RecordHandle::onTransact(
5639 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5640{
5641 return BnAudioRecord::onTransact(code, data, reply, flags);
5642}
5643
5644// ----------------------------------------------------------------------------
5645
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005646AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5647 AudioStreamIn *input,
5648 uint32_t sampleRate,
5649 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005650 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005651 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005652 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005653 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5654 // mRsmpInIndex and mInputBytes set by readInputParameters()
5655 mReqChannelCount(popcount(channels)),
5656 mReqSampleRate(sampleRate)
5657 // mBytesRead is only meaningful while active, and so is cleared in start()
5658 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659{
Glenn Kasten480b4682012-02-28 12:30:08 -08005660 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005661
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 readInputParameters();
5663}
5664
5665
5666AudioFlinger::RecordThread::~RecordThread()
5667{
5668 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005669 delete mResampler;
5670 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671}
5672
5673void AudioFlinger::RecordThread::onFirstRef()
5674{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005675 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676}
5677
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005678status_t AudioFlinger::RecordThread::readyToRun()
5679{
5680 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005681 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005682 return status;
5683}
5684
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685bool AudioFlinger::RecordThread::threadLoop()
5686{
5687 AudioBufferProvider::Buffer buffer;
5688 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005689 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690
Eric Laurent44d98482010-09-30 16:12:31 -07005691 nsecs_t lastWarning = 0;
5692
Eric Laurentfeb0db62011-07-22 09:04:31 -07005693 acquireWakeLock();
5694
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695 // start recording
5696 while (!exitPending()) {
5697
5698 processConfigEvents();
5699
5700 { // scope for mLock
5701 Mutex::Autolock _l(mLock);
5702 checkForNewParameters_l();
5703 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5704 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005705 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005706 mStandby = true;
5707 }
5708
5709 if (exitPending()) break;
5710
Eric Laurentfeb0db62011-07-22 09:04:31 -07005711 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005712 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 // go to sleep
5714 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005715 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005716 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 continue;
5718 }
5719 if (mActiveTrack != 0) {
5720 if (mActiveTrack->mState == TrackBase::PAUSING) {
5721 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005722 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 mStandby = true;
5724 }
5725 mActiveTrack.clear();
5726 mStartStopCond.broadcast();
5727 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5728 if (mReqChannelCount != mActiveTrack->channelCount()) {
5729 mActiveTrack.clear();
5730 mStartStopCond.broadcast();
5731 } else if (mBytesRead != 0) {
5732 // record start succeeds only if first read from audio input
5733 // succeeds
5734 if (mBytesRead > 0) {
5735 mActiveTrack->mState = TrackBase::ACTIVE;
5736 } else {
5737 mActiveTrack.clear();
5738 }
5739 mStartStopCond.broadcast();
5740 }
5741 mStandby = false;
5742 }
5743 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005744 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745 }
5746
5747 if (mActiveTrack != 0) {
5748 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5749 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005750 unlockEffectChains(effectChains);
5751 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005752 continue;
5753 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005754 for (size_t i = 0; i < effectChains.size(); i ++) {
5755 effectChains[i]->process_l();
5756 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005757
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005759 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005761 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 // no resampling
5763 while (framesOut) {
5764 size_t framesIn = mFrameCount - mRsmpInIndex;
5765 if (framesIn) {
5766 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5767 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5768 if (framesIn > framesOut)
5769 framesIn = framesOut;
5770 mRsmpInIndex += framesIn;
5771 framesOut -= framesIn;
5772 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005773 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774 memcpy(dst, src, framesIn * mFrameSize);
5775 } else {
5776 int16_t *src16 = (int16_t *)src;
5777 int16_t *dst16 = (int16_t *)dst;
5778 if (mChannelCount == 1) {
5779 while (framesIn--) {
5780 *dst16++ = *src16;
5781 *dst16++ = *src16++;
5782 }
5783 } else {
5784 while (framesIn--) {
5785 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5786 src16 += 2;
5787 }
5788 }
5789 }
5790 }
5791 if (framesOut && mFrameCount == mRsmpInIndex) {
5792 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005793 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005794 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795 framesOut = 0;
5796 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005797 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005798 mRsmpInIndex = 0;
5799 }
5800 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005801 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5803 // Force input into standby so that it tries to
5804 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005805 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005806 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 }
5808 mRsmpInIndex = mFrameCount;
5809 framesOut = 0;
5810 buffer.frameCount = 0;
5811 }
5812 }
5813 }
5814 } else {
5815 // resampling
5816
5817 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5818 // alter output frame count as if we were expecting stereo samples
5819 if (mChannelCount == 1 && mReqChannelCount == 1) {
5820 framesOut >>= 1;
5821 }
5822 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5823 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5824 // are 32 bit aligned which should be always true.
5825 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005826 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 // the resampler always outputs stereo samples: do post stereo to mono conversion
5828 int16_t *src = (int16_t *)mRsmpOutBuffer;
5829 int16_t *dst = buffer.i16;
5830 while (framesOut--) {
5831 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5832 src += 2;
5833 }
5834 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005835 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 }
5837
5838 }
Eric Laurenta011e352012-03-29 15:51:43 -07005839 if (mFramestoDrop == 0) {
5840 mActiveTrack->releaseBuffer(&buffer);
5841 } else {
5842 if (mFramestoDrop > 0) {
5843 mFramestoDrop -= buffer.frameCount;
5844 if (mFramestoDrop < 0) {
5845 mFramestoDrop = 0;
5846 }
5847 }
5848 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849 mActiveTrack->overflow();
5850 }
5851 // client isn't retrieving buffers fast enough
5852 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005853 if (!mActiveTrack->setOverflow()) {
5854 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005855 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005856 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005857 lastWarning = now;
5858 }
5859 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860 // Release the processor for a while before asking for a new buffer.
5861 // This will give the application more chance to read from the buffer and
5862 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005863 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 }
5865 }
Eric Laurentec437d82011-07-26 20:54:46 -07005866 // enable changes in effect chain
5867 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005868 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005869 }
5870
5871 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005872 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 }
5874 mActiveTrack.clear();
5875
5876 mStartStopCond.broadcast();
5877
Eric Laurentfeb0db62011-07-22 09:04:31 -07005878 releaseWakeLock();
5879
Steve Block3856b092011-10-20 11:56:00 +01005880 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 return false;
5882}
5883
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005884
5885sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5886 const sp<AudioFlinger::Client>& client,
5887 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005888 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005889 int channelMask,
5890 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005891 int sessionId,
5892 status_t *status)
5893{
5894 sp<RecordTrack> track;
5895 status_t lStatus;
5896
5897 lStatus = initCheck();
5898 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005899 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005900 goto Exit;
5901 }
5902
5903 { // scope for mLock
5904 Mutex::Autolock _l(mLock);
5905
5906 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005907 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005908
Glenn Kasten7378ca52012-01-20 13:44:40 -08005909 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005910 lStatus = NO_MEMORY;
5911 goto Exit;
5912 }
5913
5914 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005915 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5916 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005917 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005918 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5919 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005920 }
5921 lStatus = NO_ERROR;
5922
5923Exit:
5924 if (status) {
5925 *status = lStatus;
5926 }
5927 return track;
5928}
5929
Eric Laurenta011e352012-03-29 15:51:43 -07005930status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005931 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005932 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933{
Glenn Kasten58912562012-04-03 10:45:00 -07005934 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005935 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005937
5938 if (event == AudioSystem::SYNC_EVENT_NONE) {
5939 mSyncStartEvent.clear();
5940 mFramestoDrop = 0;
5941 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5942 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5943 triggerSession,
5944 recordTrack->sessionId(),
5945 syncStartEventCallback,
5946 this);
5947 mFramestoDrop = -1;
5948 }
5949
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005951 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 if (mActiveTrack != 0) {
5953 if (recordTrack != mActiveTrack.get()) {
5954 status = -EBUSY;
5955 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5956 mActiveTrack->mState = TrackBase::ACTIVE;
5957 }
5958 return status;
5959 }
5960
5961 recordTrack->mState = TrackBase::IDLE;
5962 mActiveTrack = recordTrack;
5963 mLock.unlock();
5964 status_t status = AudioSystem::startInput(mId);
5965 mLock.lock();
5966 if (status != NO_ERROR) {
5967 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005968 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 return status;
5970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 mRsmpInIndex = mFrameCount;
5972 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005973 if (mResampler != NULL) {
5974 mResampler->reset();
5975 }
5976 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005978 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005979 mWaitWorkCV.signal();
5980 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005981 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 mActiveTrack.clear();
5983 status = INVALID_OPERATION;
5984 goto startError;
5985 }
5986 mStartStopCond.wait(mLock);
5987 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005988 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 status = BAD_VALUE;
5990 goto startError;
5991 }
Steve Block3856b092011-10-20 11:56:00 +01005992 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 return status;
5994 }
5995startError:
5996 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005997 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998 return status;
5999}
6000
Eric Laurenta011e352012-03-29 15:51:43 -07006001void AudioFlinger::RecordThread::clearSyncStartEvent()
6002{
6003 if (mSyncStartEvent != 0) {
6004 mSyncStartEvent->cancel();
6005 }
6006 mSyncStartEvent.clear();
6007}
6008
6009void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6010{
6011 sp<SyncEvent> strongEvent = event.promote();
6012
6013 if (strongEvent != 0) {
6014 RecordThread *me = (RecordThread *)strongEvent->cookie();
6015 me->handleSyncStartEvent(strongEvent);
6016 }
6017}
6018
6019void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6020{
6021 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
6022 mActiveTrack.get(),
6023 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
6024 event->listenerSession());
6025
6026 if (mActiveTrack != 0 &&
6027 event == mSyncStartEvent) {
6028 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6029 // from audio HAL
6030 mFramestoDrop = mFrameCount * 2;
6031 mSyncStartEvent.clear();
6032 }
6033}
6034
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006036 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006037 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006039 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6041 mActiveTrack->mState = TrackBase::PAUSING;
6042 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006043 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 return;
6045 }
6046 mStartStopCond.wait(mLock);
6047 // if we have been restarted, recordTrack == mActiveTrack.get() here
6048 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6049 mLock.unlock();
6050 AudioSystem::stopInput(mId);
6051 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006052 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 }
6054 }
6055 }
6056}
6057
Eric Laurenta011e352012-03-29 15:51:43 -07006058bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6059{
6060 return false;
6061}
6062
6063status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6064{
6065 if (!isValidSyncEvent(event)) {
6066 return BAD_VALUE;
6067 }
6068
6069 Mutex::Autolock _l(mLock);
6070
6071 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6072 mTrack->setSyncEvent(event);
6073 return NO_ERROR;
6074 }
6075 return NAME_NOT_FOUND;
6076}
6077
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6079{
6080 const size_t SIZE = 256;
6081 char buffer[SIZE];
6082 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083
6084 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6085 result.append(buffer);
6086
6087 if (mActiveTrack != 0) {
6088 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006089 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006090 mActiveTrack->dump(buffer, SIZE);
6091 result.append(buffer);
6092
6093 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6094 result.append(buffer);
6095 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6096 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006097 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 result.append(buffer);
6099 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6100 result.append(buffer);
6101 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6102 result.append(buffer);
6103
6104
6105 } else {
6106 result.append("No record client\n");
6107 }
6108 write(fd, result.string(), result.size());
6109
6110 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006111 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112
6113 return NO_ERROR;
6114}
6115
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006116// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006117status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118{
6119 size_t framesReq = buffer->frameCount;
6120 size_t framesReady = mFrameCount - mRsmpInIndex;
6121 int channelCount;
6122
6123 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006124 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006126 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6128 // Force input into standby so that it tries to
6129 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006130 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006131 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006133 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 buffer->frameCount = 0;
6135 return NOT_ENOUGH_DATA;
6136 }
6137 mRsmpInIndex = 0;
6138 framesReady = mFrameCount;
6139 }
6140
6141 if (framesReq > framesReady) {
6142 framesReq = framesReady;
6143 }
6144
6145 if (mChannelCount == 1 && mReqChannelCount == 2) {
6146 channelCount = 1;
6147 } else {
6148 channelCount = 2;
6149 }
6150 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6151 buffer->frameCount = framesReq;
6152 return NO_ERROR;
6153}
6154
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006155// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6157{
6158 mRsmpInIndex += buffer->frameCount;
6159 buffer->frameCount = 0;
6160}
6161
6162bool AudioFlinger::RecordThread::checkForNewParameters_l()
6163{
6164 bool reconfig = false;
6165
6166 while (!mNewParameters.isEmpty()) {
6167 status_t status = NO_ERROR;
6168 String8 keyValuePair = mNewParameters[0];
6169 AudioParameter param = AudioParameter(keyValuePair);
6170 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006171 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 int reqSamplingRate = mReqSampleRate;
6173 int reqChannelCount = mReqChannelCount;
6174
6175 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6176 reqSamplingRate = value;
6177 reconfig = true;
6178 }
6179 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006180 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181 reconfig = true;
6182 }
6183 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006184 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185 reconfig = true;
6186 }
6187 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6188 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006189 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 // if frame count is changed after track creation
6191 if (mActiveTrack != 0) {
6192 status = INVALID_OPERATION;
6193 } else {
6194 reconfig = true;
6195 }
6196 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006197 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6198 // forward device change to effects that have requested to be
6199 // aware of attached audio device.
6200 for (size_t i = 0; i < mEffectChains.size(); i++) {
6201 mEffectChains[i]->setDevice_l(value);
6202 }
6203 // store input device and output device but do not forward output device to audio HAL.
6204 // Note that status is ignored by the caller for output device
6205 // (see AudioFlinger::setParameters()
6206 if (value & AUDIO_DEVICE_OUT_ALL) {
6207 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6208 status = BAD_VALUE;
6209 } else {
6210 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006211 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6212 if (mTrack != NULL) {
6213 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006214 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006215 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6216 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6217 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006218 }
6219 mDevice |= (uint32_t)value;
6220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006222 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006224 mInput->stream->common.standby(&mInput->stream->common);
6225 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6226 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 }
6228 if (reconfig) {
6229 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006230 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006231 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006232 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006233 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6234 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235 status = NO_ERROR;
6236 }
6237 if (status == NO_ERROR) {
6238 readInputParameters();
6239 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6240 }
6241 }
6242 }
6243
6244 mNewParameters.removeAt(0);
6245
6246 mParamStatus = status;
6247 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006248 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6249 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006250 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 }
6252 return reconfig;
6253}
6254
6255String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6256{
Dima Zavinfce7a472011-04-19 22:30:36 -07006257 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006258 String8 out_s8 = String8();
6259
6260 Mutex::Autolock _l(mLock);
6261 if (initCheck() != NO_ERROR) {
6262 return out_s8;
6263 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006264
Dima Zavin799a70e2011-04-18 16:57:27 -07006265 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006266 out_s8 = String8(s);
6267 free(s);
6268 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269}
6270
6271void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6272 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006273 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274
6275 switch (event) {
6276 case AudioSystem::INPUT_OPENED:
6277 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006278 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279 desc.samplingRate = mSampleRate;
6280 desc.format = mFormat;
6281 desc.frameCount = mFrameCount;
6282 desc.latency = 0;
6283 param2 = &desc;
6284 break;
6285
6286 case AudioSystem::INPUT_CLOSED:
6287 default:
6288 break;
6289 }
6290 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6291}
6292
6293void AudioFlinger::RecordThread::readInputParameters()
6294{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006295 delete mRsmpInBuffer;
6296 // mRsmpInBuffer is always assigned a new[] below
6297 delete mRsmpOutBuffer;
6298 mRsmpOutBuffer = NULL;
6299 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006300 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301
Dima Zavin799a70e2011-04-18 16:57:27 -07006302 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006303 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6304 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006305 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006306 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006307 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006308 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006309 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006310 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6311
Glenn Kasten53d76db2012-03-08 12:32:47 -08006312 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313 {
6314 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006315 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6316 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 if (mChannelCount == 1 && mReqChannelCount == 2) {
6318 channelCount = 1;
6319 } else {
6320 channelCount = 2;
6321 }
6322 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6323 mResampler->setSampleRate(mSampleRate);
6324 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6325 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6326
6327 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6328 if (mChannelCount == 1 && mReqChannelCount == 1) {
6329 mFrameCount >>= 1;
6330 }
6331
6332 }
6333 mRsmpInIndex = mFrameCount;
6334}
6335
6336unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6337{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006338 Mutex::Autolock _l(mLock);
6339 if (initCheck() != NO_ERROR) {
6340 return 0;
6341 }
6342
Dima Zavin799a70e2011-04-18 16:57:27 -07006343 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344}
6345
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006346uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6347{
6348 Mutex::Autolock _l(mLock);
6349 uint32_t result = 0;
6350 if (getEffectChain_l(sessionId) != 0) {
6351 result = EFFECT_SESSION;
6352 }
6353
6354 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6355 result |= TRACK_SESSION;
6356 }
6357
6358 return result;
6359}
6360
Eric Laurent59bd0da2011-08-01 09:52:20 -07006361AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6362{
6363 Mutex::Autolock _l(mLock);
6364 return mTrack;
6365}
6366
Glenn Kastenaed850d2012-01-26 09:46:34 -08006367AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006368{
6369 Mutex::Autolock _l(mLock);
6370 return mInput;
6371}
6372
6373AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6374{
6375 Mutex::Autolock _l(mLock);
6376 AudioStreamIn *input = mInput;
6377 mInput = NULL;
6378 return input;
6379}
6380
6381// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006382audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006383{
6384 if (mInput == NULL) {
6385 return NULL;
6386 }
6387 return &mInput->stream->common;
6388}
6389
6390
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391// ----------------------------------------------------------------------------
6392
Eric Laurenta4c5a552012-03-29 10:12:40 -07006393audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6394{
6395 if (!settingsAllowed()) {
6396 return 0;
6397 }
6398 Mutex::Autolock _l(mLock);
6399 return loadHwModule_l(name);
6400}
6401
6402// loadHwModule_l() must be called with AudioFlinger::mLock held
6403audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6404{
6405 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6406 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6407 ALOGW("loadHwModule() module %s already loaded", name);
6408 return mAudioHwDevs.keyAt(i);
6409 }
6410 }
6411
Eric Laurenta4c5a552012-03-29 10:12:40 -07006412 audio_hw_device_t *dev;
6413
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006414 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006415 if (rc) {
6416 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6417 return 0;
6418 }
6419
6420 mHardwareStatus = AUDIO_HW_INIT;
6421 rc = dev->init_check(dev);
6422 mHardwareStatus = AUDIO_HW_IDLE;
6423 if (rc) {
6424 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6425 return 0;
6426 }
6427
6428 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6429 (NULL != dev->set_master_volume)) {
6430 AutoMutex lock(mHardwareLock);
6431 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6432 dev->set_master_volume(dev, mMasterVolume);
6433 mHardwareStatus = AUDIO_HW_IDLE;
6434 }
6435
6436 audio_module_handle_t handle = nextUniqueId();
6437 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6438
6439 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006440 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006441
6442 return handle;
6443
6444}
6445
6446audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6447 audio_devices_t *pDevices,
6448 uint32_t *pSamplingRate,
6449 audio_format_t *pFormat,
6450 audio_channel_mask_t *pChannelMask,
6451 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006452 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453{
6454 status_t status;
6455 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006456 struct audio_config config = {
6457 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6458 channel_mask: pChannelMask ? *pChannelMask : 0,
6459 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6460 };
6461 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006462 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463
Eric Laurenta4c5a552012-03-29 10:12:40 -07006464 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6465 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006466 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006467 config.sample_rate,
6468 config.format,
6469 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006470 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471
6472 if (pDevices == NULL || *pDevices == 0) {
6473 return 0;
6474 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006475
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 Mutex::Autolock _l(mLock);
6477
Eric Laurenta4c5a552012-03-29 10:12:40 -07006478 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006479 if (outHwDev == NULL)
6480 return 0;
6481
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006482 audio_io_handle_t id = nextUniqueId();
6483
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006484 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006485
6486 status = outHwDev->open_output_stream(outHwDev,
6487 id,
6488 *pDevices,
6489 (audio_output_flags_t)flags,
6490 &config,
6491 &outStream);
6492
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006493 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006494 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006495 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006496 config.sample_rate,
6497 config.format,
6498 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 status);
6500
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006501 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006502 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006503
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006504 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006505 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6506 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006508 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 } else {
6510 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006511 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512 }
6513 mPlaybackThreads.add(id, thread);
6514
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006515 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6516 if (pFormat != NULL) *pFormat = config.format;
6517 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006518 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519
6520 // notify client processes of the new output creation
6521 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006522
6523 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006524 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006525 ALOGI("Using module %d has the primary audio interface", module);
6526 mPrimaryHardwareDev = outHwDev;
6527
6528 AutoMutex lock(mHardwareLock);
6529 mHardwareStatus = AUDIO_HW_SET_MODE;
6530 outHwDev->set_mode(outHwDev, mMode);
6531
6532 // Determine the level of master volume support the primary audio HAL has,
6533 // and set the initial master volume at the same time.
6534 float initialVolume = 1.0;
6535 mMasterVolumeSupportLvl = MVS_NONE;
6536
6537 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6538 if ((NULL != outHwDev->get_master_volume) &&
6539 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6540 mMasterVolumeSupportLvl = MVS_FULL;
6541 } else {
6542 mMasterVolumeSupportLvl = MVS_SETONLY;
6543 initialVolume = 1.0;
6544 }
6545
6546 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6547 if ((NULL == outHwDev->set_master_volume) ||
6548 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6549 mMasterVolumeSupportLvl = MVS_NONE;
6550 }
6551 // now that we have a primary device, initialize master volume on other devices
6552 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6553 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6554
6555 if ((dev != mPrimaryHardwareDev) &&
6556 (NULL != dev->set_master_volume)) {
6557 dev->set_master_volume(dev, initialVolume);
6558 }
6559 }
6560 mHardwareStatus = AUDIO_HW_IDLE;
6561 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6562 ? initialVolume
6563 : 1.0;
6564 mMasterVolume = initialVolume;
6565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566 return id;
6567 }
6568
6569 return 0;
6570}
6571
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006572audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6573 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006574{
6575 Mutex::Autolock _l(mLock);
6576 MixerThread *thread1 = checkMixerThread_l(output1);
6577 MixerThread *thread2 = checkMixerThread_l(output2);
6578
6579 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006580 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 return 0;
6582 }
6583
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006584 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6586 thread->addOutputTrack(thread2);
6587 mPlaybackThreads.add(id, thread);
6588 // notify client processes of the new output creation
6589 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6590 return id;
6591}
6592
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006593status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594{
6595 // keep strong reference on the playback thread so that
6596 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006597 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598 {
6599 Mutex::Autolock _l(mLock);
6600 thread = checkPlaybackThread_l(output);
6601 if (thread == NULL) {
6602 return BAD_VALUE;
6603 }
6604
Steve Block3856b092011-10-20 11:56:00 +01006605 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006607 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006609 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6611 dupThread->removeOutputTrack((MixerThread *)thread.get());
6612 }
6613 }
6614 }
Glenn Kastena1117922012-01-26 10:53:32 -08006615 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 mPlaybackThreads.removeItem(output);
6617 }
6618 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006619 // The thread entity (active unit of execution) is no longer running here,
6620 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006621
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006622 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006623 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006624 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006625 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006626 out->hwDev->close_output_stream(out->hwDev, out->stream);
6627 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628 }
6629 return NO_ERROR;
6630}
6631
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006632status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633{
6634 Mutex::Autolock _l(mLock);
6635 PlaybackThread *thread = checkPlaybackThread_l(output);
6636
6637 if (thread == NULL) {
6638 return BAD_VALUE;
6639 }
6640
Steve Block3856b092011-10-20 11:56:00 +01006641 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642 thread->suspend();
6643
6644 return NO_ERROR;
6645}
6646
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006647status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648{
6649 Mutex::Autolock _l(mLock);
6650 PlaybackThread *thread = checkPlaybackThread_l(output);
6651
6652 if (thread == NULL) {
6653 return BAD_VALUE;
6654 }
6655
Steve Block3856b092011-10-20 11:56:00 +01006656 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006657
6658 thread->restore();
6659
6660 return NO_ERROR;
6661}
6662
Eric Laurenta4c5a552012-03-29 10:12:40 -07006663audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6664 audio_devices_t *pDevices,
6665 uint32_t *pSamplingRate,
6666 audio_format_t *pFormat,
6667 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668{
6669 status_t status;
6670 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006671 struct audio_config config = {
6672 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6673 channel_mask: pChannelMask ? *pChannelMask : 0,
6674 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6675 };
6676 uint32_t reqSamplingRate = config.sample_rate;
6677 audio_format_t reqFormat = config.format;
6678 audio_channel_mask_t reqChannels = config.channel_mask;
6679 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006680 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681
6682 if (pDevices == NULL || *pDevices == 0) {
6683 return 0;
6684 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006685
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 Mutex::Autolock _l(mLock);
6687
Eric Laurenta4c5a552012-03-29 10:12:40 -07006688 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006689 if (inHwDev == NULL)
6690 return 0;
6691
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006692 audio_io_handle_t id = nextUniqueId();
6693
6694 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006695 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006696 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006697 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006698 config.sample_rate,
6699 config.format,
6700 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006701 status);
6702
6703 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6704 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6705 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006706 if (status == BAD_VALUE &&
6707 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6708 (config.sample_rate <= 2 * reqSamplingRate) &&
6709 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006710 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006711 inStream = NULL;
6712 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713 }
6714
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006715 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006716 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6717
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006718 // Start record thread
6719 // RecorThread require both input and output device indication to forward to audio
6720 // pre processing modules
6721 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6722 thread = new RecordThread(this,
6723 input,
6724 reqSamplingRate,
6725 reqChannels,
6726 id,
6727 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006729 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006730 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006731 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006732 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733
Dima Zavin799a70e2011-04-18 16:57:27 -07006734 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735
6736 // notify client processes of the new input creation
6737 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6738 return id;
6739 }
6740
6741 return 0;
6742}
6743
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006744status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745{
6746 // keep strong reference on the record thread so that
6747 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006748 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749 {
6750 Mutex::Autolock _l(mLock);
6751 thread = checkRecordThread_l(input);
6752 if (thread == NULL) {
6753 return BAD_VALUE;
6754 }
6755
Steve Block3856b092011-10-20 11:56:00 +01006756 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006757 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 mRecordThreads.removeItem(input);
6759 }
6760 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006761 // The thread entity (active unit of execution) is no longer running here,
6762 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006764 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006765 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006766 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006767 in->hwDev->close_input_stream(in->hwDev, in->stream);
6768 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769
6770 return NO_ERROR;
6771}
6772
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006773status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774{
6775 Mutex::Autolock _l(mLock);
6776 MixerThread *dstThread = checkMixerThread_l(output);
6777 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006778 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779 return BAD_VALUE;
6780 }
6781
Steve Block3856b092011-10-20 11:56:00 +01006782 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006783 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6784
6785 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6786 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006787 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 MixerThread *srcThread = (MixerThread *)thread;
6789 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 }
Eric Laurentde070132010-07-13 04:45:46 -07006791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792
6793 return NO_ERROR;
6794}
6795
6796
6797int AudioFlinger::newAudioSessionId()
6798{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006799 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006800}
6801
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006802void AudioFlinger::acquireAudioSessionId(int audioSession)
6803{
6804 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006805 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006806 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006807 size_t num = mAudioSessionRefs.size();
6808 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006809 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006810 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6811 ref->mCnt++;
6812 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006813 return;
6814 }
6815 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006816 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6817 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006818}
6819
6820void AudioFlinger::releaseAudioSessionId(int audioSession)
6821{
6822 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006823 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006824 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006825 size_t num = mAudioSessionRefs.size();
6826 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006827 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006828 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6829 ref->mCnt--;
6830 ALOGV(" decremented refcount to %d", ref->mCnt);
6831 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006832 mAudioSessionRefs.removeAt(i);
6833 delete ref;
6834 purgeStaleEffects_l();
6835 }
6836 return;
6837 }
6838 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006839 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006840}
6841
6842void AudioFlinger::purgeStaleEffects_l() {
6843
Steve Block3856b092011-10-20 11:56:00 +01006844 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006845
6846 Vector< sp<EffectChain> > chains;
6847
6848 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6849 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6850 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6851 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006852 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6853 chains.push(ec);
6854 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006855 }
6856 }
6857 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6858 sp<RecordThread> t = mRecordThreads.valueAt(i);
6859 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6860 sp<EffectChain> ec = t->mEffectChains[j];
6861 chains.push(ec);
6862 }
6863 }
6864
6865 for (size_t i = 0; i < chains.size(); i++) {
6866 sp<EffectChain> ec = chains[i];
6867 int sessionid = ec->sessionId();
6868 sp<ThreadBase> t = ec->mThread.promote();
6869 if (t == 0) {
6870 continue;
6871 }
6872 size_t numsessionrefs = mAudioSessionRefs.size();
6873 bool found = false;
6874 for (size_t k = 0; k < numsessionrefs; k++) {
6875 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006876 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006877 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006878 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006879 found = true;
6880 break;
6881 }
6882 }
6883 if (!found) {
6884 // remove all effects from the chain
6885 while (ec->mEffects.size()) {
6886 sp<EffectModule> effect = ec->mEffects[0];
6887 effect->unPin();
6888 Mutex::Autolock _l (t->mLock);
6889 t->removeEffect_l(effect);
6890 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6891 sp<EffectHandle> handle = effect->mHandles[j].promote();
6892 if (handle != 0) {
6893 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006894 if (handle->mHasControl && handle->mEnabled) {
6895 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6896 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006897 }
6898 }
6899 AudioSystem::unregisterEffect(effect->id());
6900 }
6901 }
6902 }
6903 return;
6904}
6905
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006907AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908{
Glenn Kastena1117922012-01-26 10:53:32 -08006909 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910}
6911
6912// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006913AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914{
6915 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006916 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917}
6918
6919// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006920AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921{
Glenn Kastena1117922012-01-26 10:53:32 -08006922 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923}
6924
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006925uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006927 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928}
6929
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006930AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006931{
6932 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6933 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006934 AudioStreamOut *output = thread->getOutput();
6935 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006936 return thread;
6937 }
6938 }
6939 return NULL;
6940}
6941
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006942uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006943{
6944 PlaybackThread *thread = primaryPlaybackThread_l();
6945
6946 if (thread == NULL) {
6947 return 0;
6948 }
6949
6950 return thread->device();
6951}
6952
Eric Laurenta011e352012-03-29 15:51:43 -07006953sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6954 int triggerSession,
6955 int listenerSession,
6956 sync_event_callback_t callBack,
6957 void *cookie)
6958{
6959 Mutex::Autolock _l(mLock);
6960
6961 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6962 status_t playStatus = NAME_NOT_FOUND;
6963 status_t recStatus = NAME_NOT_FOUND;
6964 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6965 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6966 if (playStatus == NO_ERROR) {
6967 return event;
6968 }
6969 }
6970 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6971 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6972 if (recStatus == NO_ERROR) {
6973 return event;
6974 }
6975 }
6976 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6977 mPendingSyncEvents.add(event);
6978 } else {
6979 ALOGV("createSyncEvent() invalid event %d", event->type());
6980 event.clear();
6981 }
6982 return event;
6983}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006984
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985// ----------------------------------------------------------------------------
6986// Effect management
6987// ----------------------------------------------------------------------------
6988
6989
Glenn Kastenf587ba52012-01-26 16:25:10 -08006990status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991{
6992 Mutex::Autolock _l(mLock);
6993 return EffectQueryNumberEffects(numEffects);
6994}
6995
Glenn Kastenf587ba52012-01-26 16:25:10 -08006996status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997{
6998 Mutex::Autolock _l(mLock);
6999 return EffectQueryEffect(index, descriptor);
7000}
7001
Glenn Kasten5e92a782012-01-30 07:40:52 -08007002status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007003 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004{
7005 Mutex::Autolock _l(mLock);
7006 return EffectGetDescriptor(pUuid, descriptor);
7007}
7008
7009
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7011 effect_descriptor_t *pDesc,
7012 const sp<IEffectClient>& effectClient,
7013 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007014 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015 int sessionId,
7016 status_t *status,
7017 int *id,
7018 int *enabled)
7019{
7020 status_t lStatus = NO_ERROR;
7021 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007024 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007025 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026
7027 if (pDesc == NULL) {
7028 lStatus = BAD_VALUE;
7029 goto Exit;
7030 }
7031
Eric Laurent84e9a102010-09-23 16:10:16 -07007032 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007033 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007034 lStatus = PERMISSION_DENIED;
7035 goto Exit;
7036 }
7037
Dima Zavinfce7a472011-04-19 22:30:36 -07007038 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007039 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007040 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007041 lStatus = PERMISSION_DENIED;
7042 goto Exit;
7043 }
7044
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007045 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007046 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007047 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007048 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007049 lStatus = BAD_VALUE;
7050 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007051 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007052 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007053 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007054 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007055 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007056 }
7057 }
7058
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 {
7060 Mutex::Autolock _l(mLock);
7061
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062
7063 if (!EffectIsNullUuid(&pDesc->uuid)) {
7064 // if uuid is specified, request effect descriptor
7065 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7066 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007067 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 goto Exit;
7069 }
7070 } else {
7071 // if uuid is not specified, look for an available implementation
7072 // of the required type in effect factory
7073 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007074 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075 lStatus = BAD_VALUE;
7076 goto Exit;
7077 }
7078 uint32_t numEffects = 0;
7079 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007080 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081 bool found = false;
7082
7083 lStatus = EffectQueryNumberEffects(&numEffects);
7084 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007085 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 goto Exit;
7087 }
7088 for (uint32_t i = 0; i < numEffects; i++) {
7089 lStatus = EffectQueryEffect(i, &desc);
7090 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007091 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092 continue;
7093 }
7094 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7095 // If matching type found save effect descriptor. If the session is
7096 // 0 and the effect is not auxiliary, continue enumeration in case
7097 // an auxiliary version of this effect type is available
7098 found = true;
7099 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007100 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7102 break;
7103 }
7104 }
7105 }
7106 if (!found) {
7107 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007108 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007109 goto Exit;
7110 }
7111 // For same effect type, chose auxiliary version over insert version if
7112 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007113 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7115 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7116 }
7117 }
7118
7119 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007120 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7122 lStatus = INVALID_OPERATION;
7123 goto Exit;
7124 }
7125
Eric Laurent59255e42011-07-27 19:49:51 -07007126 // check recording permission for visualizer
7127 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7128 !recordingAllowed()) {
7129 lStatus = PERMISSION_DENIED;
7130 goto Exit;
7131 }
7132
Mathias Agopian65ab4712010-07-14 17:59:35 -07007133 // return effect descriptor
7134 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7135
7136 // If output is not specified try to find a matching audio session ID in one of the
7137 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007138 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7139 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007140 // Note: io is never 0 when creating an effect on an input
7141 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007142 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007143 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7144 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007145 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007146 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007149 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007150 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7151 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7152 io = mRecordThreads.keyAt(i);
7153 break;
7154 }
7155 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007156 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007157 // If no output thread contains the requested session ID, default to
7158 // first output. The effect chain will be moved to the correct output
7159 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007160 if (io == 0 && mPlaybackThreads.size()) {
7161 io = mPlaybackThreads.keyAt(0);
7162 }
Steve Block3856b092011-10-20 11:56:00 +01007163 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007164 }
7165 ThreadBase *thread = checkRecordThread_l(io);
7166 if (thread == NULL) {
7167 thread = checkPlaybackThread_l(io);
7168 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007169 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007170 lStatus = BAD_VALUE;
7171 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007174
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007175 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007177 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007178 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7179 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180 if (handle != 0 && id != NULL) {
7181 *id = handle->id();
7182 }
7183 }
7184
7185Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007186 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187 *status = lStatus;
7188 }
7189 return handle;
7190}
7191
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007192status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7193 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007194{
Steve Block3856b092011-10-20 11:56:00 +01007195 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007196 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007197 Mutex::Autolock _l(mLock);
7198 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007199 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007200 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201 }
Eric Laurentde070132010-07-13 04:45:46 -07007202 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7203 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007204 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007205 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206 }
Eric Laurentde070132010-07-13 04:45:46 -07007207 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7208 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007209 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007210 return BAD_VALUE;
7211 }
7212
7213 Mutex::Autolock _dl(dstThread->mLock);
7214 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007215 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007216
Mathias Agopian65ab4712010-07-14 17:59:35 -07007217 return NO_ERROR;
7218}
7219
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007220// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007221status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007222 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007223 AudioFlinger::PlaybackThread *dstThread,
7224 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007225{
Steve Block3856b092011-10-20 11:56:00 +01007226 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007227 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007228
Eric Laurent59255e42011-07-27 19:49:51 -07007229 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007230 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007231 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007232 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007233 return INVALID_OPERATION;
7234 }
7235
Eric Laurent39e94f82010-07-28 01:32:47 -07007236 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007237 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007238 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007239 // removed.
7240 srcThread->removeEffectChain_l(chain);
7241
7242 // transfer all effects one by one so that new effect chain is created on new thread with
7243 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007244 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007245 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007246 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007247 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7248 while (effect != 0) {
7249 srcThread->removeEffect_l(effect);
7250 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007251 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7252 if (effect->state() == EffectModule::ACTIVE ||
7253 effect->state() == EffectModule::STOPPING) {
7254 effect->start();
7255 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007256 // if the move request is not received from audio policy manager, the effect must be
7257 // re-registered with the new strategy and output
7258 if (dstChain == 0) {
7259 dstChain = effect->chain().promote();
7260 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007261 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007262 srcThread->addEffect_l(effect);
7263 return NO_INIT;
7264 }
7265 strategy = dstChain->strategy();
7266 }
7267 if (reRegister) {
7268 AudioSystem::unregisterEffect(effect->id());
7269 AudioSystem::registerEffect(&effect->desc(),
7270 dstOutput,
7271 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007272 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007273 effect->id());
7274 }
Eric Laurentde070132010-07-13 04:45:46 -07007275 effect = chain->getEffectFromId_l(0);
7276 }
7277
7278 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279}
7280
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007281
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007283sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 const sp<AudioFlinger::Client>& client,
7285 const sp<IEffectClient>& effectClient,
7286 int32_t priority,
7287 int sessionId,
7288 effect_descriptor_t *desc,
7289 int *enabled,
7290 status_t *status
7291 )
7292{
7293 sp<EffectModule> effect;
7294 sp<EffectHandle> handle;
7295 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007297 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007298 bool effectCreated = false;
7299 bool effectRegistered = false;
7300
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007301 lStatus = initCheck();
7302 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007303 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304 goto Exit;
7305 }
7306
7307 // Do not allow effects with session ID 0 on direct output or duplicating threads
7308 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007309 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007310 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007311 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312 lStatus = BAD_VALUE;
7313 goto Exit;
7314 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007315 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007316 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007317 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007318 desc->name, desc->flags, mType);
7319 lStatus = BAD_VALUE;
7320 goto Exit;
7321 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322
Steve Block3856b092011-10-20 11:56:00 +01007323 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324
7325 { // scope for mLock
7326 Mutex::Autolock _l(mLock);
7327
7328 // check for existing effect chain with the requested audio session
7329 chain = getEffectChain_l(sessionId);
7330 if (chain == 0) {
7331 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007332 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333 chain = new EffectChain(this, sessionId);
7334 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007335 chain->setStrategy(getStrategyForSession_l(sessionId));
7336 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007338 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 }
7340
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007341 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342
7343 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007344 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007346 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 if (lStatus != NO_ERROR) {
7348 goto Exit;
7349 }
7350 effectRegistered = true;
7351 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007352 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353 lStatus = effect->status();
7354 if (lStatus != NO_ERROR) {
7355 goto Exit;
7356 }
Eric Laurentcab11242010-07-15 12:50:15 -07007357 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 if (lStatus != NO_ERROR) {
7359 goto Exit;
7360 }
7361 effectCreated = true;
7362
7363 effect->setDevice(mDevice);
7364 effect->setMode(mAudioFlinger->getMode());
7365 }
7366 // create effect handle and connect it to effect module
7367 handle = new EffectHandle(effect, client, effectClient, priority);
7368 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007369 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 *enabled = (int)effect->isEnabled();
7371 }
7372 }
7373
7374Exit:
7375 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007376 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007378 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379 }
7380 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007381 AudioSystem::unregisterEffect(effect->id());
7382 }
7383 if (chainCreated) {
7384 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385 }
7386 handle.clear();
7387 }
7388
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007389 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 *status = lStatus;
7391 }
7392 return handle;
7393}
7394
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007395sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7396{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007397 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007398 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007399}
7400
Eric Laurentde070132010-07-13 04:45:46 -07007401// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7402// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007403status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007404{
7405 // check for existing effect chain with the requested audio session
7406 int sessionId = effect->sessionId();
7407 sp<EffectChain> chain = getEffectChain_l(sessionId);
7408 bool chainCreated = false;
7409
7410 if (chain == 0) {
7411 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007412 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007413 chain = new EffectChain(this, sessionId);
7414 addEffectChain_l(chain);
7415 chain->setStrategy(getStrategyForSession_l(sessionId));
7416 chainCreated = true;
7417 }
Steve Block3856b092011-10-20 11:56:00 +01007418 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007419
7420 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007421 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007422 this, effect->desc().name, chain.get());
7423 return BAD_VALUE;
7424 }
7425
7426 status_t status = chain->addEffect_l(effect);
7427 if (status != NO_ERROR) {
7428 if (chainCreated) {
7429 removeEffectChain_l(chain);
7430 }
7431 return status;
7432 }
7433
7434 effect->setDevice(mDevice);
7435 effect->setMode(mAudioFlinger->getMode());
7436 return NO_ERROR;
7437}
7438
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007439void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007440
Steve Block3856b092011-10-20 11:56:00 +01007441 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007443 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7444 detachAuxEffect_l(effect->id());
7445 }
7446
7447 sp<EffectChain> chain = effect->chain().promote();
7448 if (chain != 0) {
7449 // remove effect chain if removing last effect
7450 if (chain->removeEffect_l(effect) == 0) {
7451 removeEffectChain_l(chain);
7452 }
7453 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007454 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007455 }
7456}
7457
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007458void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007459 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007460{
7461 effectChains = mEffectChains;
7462 for (size_t i = 0; i < mEffectChains.size(); i++) {
7463 mEffectChains[i]->lock();
7464 }
7465}
7466
7467void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007468 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007469{
7470 for (size_t i = 0; i < effectChains.size(); i++) {
7471 effectChains[i]->unlock();
7472 }
7473}
7474
7475sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7476{
7477 Mutex::Autolock _l(mLock);
7478 return getEffectChain_l(sessionId);
7479}
7480
7481sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7482{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007483 size_t size = mEffectChains.size();
7484 for (size_t i = 0; i < size; i++) {
7485 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007486 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007487 }
7488 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007489 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007490}
7491
Glenn Kastenf78aee72012-01-04 11:00:47 -08007492void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007493{
7494 Mutex::Autolock _l(mLock);
7495 size_t size = mEffectChains.size();
7496 for (size_t i = 0; i < size; i++) {
7497 mEffectChains[i]->setMode_l(mode);
7498 }
7499}
7500
7501void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007502 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007503 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007504
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007506 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507 // delete the effect module if removing last handle on it
7508 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007509 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007510 removeEffect_l(effect);
7511 AudioSystem::unregisterEffect(effect->id());
7512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007513 }
7514}
7515
7516status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7517{
7518 int session = chain->sessionId();
7519 int16_t *buffer = mMixBuffer;
7520 bool ownsBuffer = false;
7521
Steve Block3856b092011-10-20 11:56:00 +01007522 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 if (session > 0) {
7524 // Only one effect chain can be present in direct output thread and it uses
7525 // the mix buffer as input
7526 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007527 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007528 buffer = new int16_t[numSamples];
7529 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007530 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531 ownsBuffer = true;
7532 }
7533
7534 // Attach all tracks with same session ID to this chain.
7535 for (size_t i = 0; i < mTracks.size(); ++i) {
7536 sp<Track> track = mTracks[i];
7537 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007538 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007540 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007541 }
7542 }
7543
7544 // indicate all active tracks in the chain
7545 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7546 sp<Track> track = mActiveTracks[i].promote();
7547 if (track == 0) continue;
7548 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007549 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007550 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 }
7552 }
7553 }
7554
7555 chain->setInBuffer(buffer, ownsBuffer);
7556 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007557 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007558 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007559 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7560 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007562 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7563 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007564 // Effect chain for other sessions are inserted at beginning of effect
7565 // chains list to be processed before output mix effects. Relative order between other
7566 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 size_t size = mEffectChains.size();
7568 size_t i = 0;
7569 for (i = 0; i < size; i++) {
7570 if (mEffectChains[i]->sessionId() < session) break;
7571 }
7572 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007573 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574
7575 return NO_ERROR;
7576}
7577
7578size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7579{
7580 int session = chain->sessionId();
7581
Steve Block3856b092011-10-20 11:56:00 +01007582 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583
7584 for (size_t i = 0; i < mEffectChains.size(); i++) {
7585 if (chain == mEffectChains[i]) {
7586 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007587 // detach all active tracks from the chain
7588 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7589 sp<Track> track = mActiveTracks[i].promote();
7590 if (track == 0) continue;
7591 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007592 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007593 chain.get(), session);
7594 chain->decActiveTrackCnt();
7595 }
7596 }
7597
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598 // detach all tracks with same session ID from this chain
7599 for (size_t i = 0; i < mTracks.size(); ++i) {
7600 sp<Track> track = mTracks[i];
7601 if (session == track->sessionId()) {
7602 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007603 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007604 }
7605 }
Eric Laurentde070132010-07-13 04:45:46 -07007606 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007607 }
7608 }
7609 return mEffectChains.size();
7610}
7611
Eric Laurentde070132010-07-13 04:45:46 -07007612status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7613 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007614{
7615 Mutex::Autolock _l(mLock);
7616 return attachAuxEffect_l(track, EffectId);
7617}
7618
Eric Laurentde070132010-07-13 04:45:46 -07007619status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7620 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621{
7622 status_t status = NO_ERROR;
7623
7624 if (EffectId == 0) {
7625 track->setAuxBuffer(0, NULL);
7626 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007627 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7628 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007629 if (effect != 0) {
7630 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7631 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7632 } else {
7633 status = INVALID_OPERATION;
7634 }
7635 } else {
7636 status = BAD_VALUE;
7637 }
7638 }
7639 return status;
7640}
7641
7642void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7643{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007644 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 sp<Track> track = mTracks[i];
7646 if (track->auxEffectId() == effectId) {
7647 attachAuxEffect_l(track, 0);
7648 }
7649 }
7650}
7651
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007652status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7653{
7654 // only one chain per input thread
7655 if (mEffectChains.size() != 0) {
7656 return INVALID_OPERATION;
7657 }
Steve Block3856b092011-10-20 11:56:00 +01007658 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007659
7660 chain->setInBuffer(NULL);
7661 chain->setOutBuffer(NULL);
7662
Eric Laurent59255e42011-07-27 19:49:51 -07007663 checkSuspendOnAddEffectChain_l(chain);
7664
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007665 mEffectChains.add(chain);
7666
7667 return NO_ERROR;
7668}
7669
7670size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7671{
Steve Block3856b092011-10-20 11:56:00 +01007672 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007673 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007674 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7675 chain.get(), mEffectChains.size(), this);
7676 if (mEffectChains.size() == 1) {
7677 mEffectChains.removeAt(0);
7678 }
7679 return 0;
7680}
7681
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682// ----------------------------------------------------------------------------
7683// EffectModule implementation
7684// ----------------------------------------------------------------------------
7685
7686#undef LOG_TAG
7687#define LOG_TAG "AudioFlinger::EffectModule"
7688
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007689AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007690 const wp<AudioFlinger::EffectChain>& chain,
7691 effect_descriptor_t *desc,
7692 int id,
7693 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007694 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007695 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696{
Steve Block3856b092011-10-20 11:56:00 +01007697 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007699 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700 return;
7701 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007702
7703 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7704
7705 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007706 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707
7708 if (mStatus != NO_ERROR) {
7709 return;
7710 }
7711 lStatus = init();
7712 if (lStatus < 0) {
7713 mStatus = lStatus;
7714 goto Error;
7715 }
7716
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007717 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7718 mPinned = true;
7719 }
Steve Block3856b092011-10-20 11:56:00 +01007720 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007721 return;
7722Error:
7723 EffectRelease(mEffectInterface);
7724 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007725 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007726}
7727
7728AudioFlinger::EffectModule::~EffectModule()
7729{
Steve Block3856b092011-10-20 11:56:00 +01007730 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007731 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007732 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7733 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7734 sp<ThreadBase> thread = mThread.promote();
7735 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007736 audio_stream_t *stream = thread->stream();
7737 if (stream != NULL) {
7738 stream->remove_audio_effect(stream, mEffectInterface);
7739 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007740 }
7741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007742 // release effect engine
7743 EffectRelease(mEffectInterface);
7744 }
7745}
7746
Glenn Kasten435dbe62012-01-30 10:15:48 -08007747status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007748{
7749 status_t status;
7750
7751 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007752 int priority = handle->priority();
7753 size_t size = mHandles.size();
7754 sp<EffectHandle> h;
7755 size_t i;
7756 for (i = 0; i < size; i++) {
7757 h = mHandles[i].promote();
7758 if (h == 0) continue;
7759 if (h->priority() <= priority) break;
7760 }
7761 // if inserted in first place, move effect control from previous owner to this handle
7762 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007763 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007765 enabled = h->enabled();
7766 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007767 }
Eric Laurent59255e42011-07-27 19:49:51 -07007768 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769 status = NO_ERROR;
7770 } else {
7771 status = ALREADY_EXISTS;
7772 }
Steve Block3856b092011-10-20 11:56:00 +01007773 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 mHandles.insertAt(handle, i);
7775 return status;
7776}
7777
7778size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7779{
7780 Mutex::Autolock _l(mLock);
7781 size_t size = mHandles.size();
7782 size_t i;
7783 for (i = 0; i < size; i++) {
7784 if (mHandles[i] == handle) break;
7785 }
7786 if (i == size) {
7787 return size;
7788 }
Steve Block3856b092011-10-20 11:56:00 +01007789 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007790
7791 bool enabled = false;
7792 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007793 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007794 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007795 enabled = hdl->enabled();
7796 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 mHandles.removeAt(i);
7798 size = mHandles.size();
7799 // if removed from first place, move effect control from this handle to next in line
7800 if (i == 0 && size != 0) {
7801 sp<EffectHandle> h = mHandles[0].promote();
7802 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007803 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804 }
7805 }
7806
Eric Laurentec437d82011-07-26 20:54:46 -07007807 // Prevent calls to process() and other functions on effect interface from now on.
7808 // The effect engine will be released by the destructor when the last strong reference on
7809 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007810 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007811 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007812 }
7813
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814 return size;
7815}
7816
Eric Laurent59255e42011-07-27 19:49:51 -07007817sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7818{
7819 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007820 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007821}
7822
Glenn Kasten58123c32012-02-03 10:32:24 -08007823void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007825 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826 // keep a strong reference on this EffectModule to avoid calling the
7827 // destructor before we exit
7828 sp<EffectModule> keep(this);
7829 {
7830 sp<ThreadBase> thread = mThread.promote();
7831 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007832 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833 }
7834 }
7835}
7836
7837void AudioFlinger::EffectModule::updateState() {
7838 Mutex::Autolock _l(mLock);
7839
7840 switch (mState) {
7841 case RESTART:
7842 reset_l();
7843 // FALL THROUGH
7844
7845 case STARTING:
7846 // clear auxiliary effect input buffer for next accumulation
7847 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7848 memset(mConfig.inputCfg.buffer.raw,
7849 0,
7850 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7851 }
7852 start_l();
7853 mState = ACTIVE;
7854 break;
7855 case STOPPING:
7856 stop_l();
7857 mDisableWaitCnt = mMaxDisableWaitCnt;
7858 mState = STOPPED;
7859 break;
7860 case STOPPED:
7861 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7862 // turn off sequence.
7863 if (--mDisableWaitCnt == 0) {
7864 reset_l();
7865 mState = IDLE;
7866 }
7867 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007868 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007869 break;
7870 }
7871}
7872
7873void AudioFlinger::EffectModule::process()
7874{
7875 Mutex::Autolock _l(mLock);
7876
Eric Laurentec437d82011-07-26 20:54:46 -07007877 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 mConfig.inputCfg.buffer.raw == NULL ||
7879 mConfig.outputCfg.buffer.raw == NULL) {
7880 return;
7881 }
7882
Eric Laurent8f45bd72010-08-31 13:50:07 -07007883 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7885 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007886 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007888 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 }
7890
7891 // do the actual processing in the effect engine
7892 int ret = (*mEffectInterface)->process(mEffectInterface,
7893 &mConfig.inputCfg.buffer,
7894 &mConfig.outputCfg.buffer);
7895
7896 // force transition to IDLE state when engine is ready
7897 if (mState == STOPPED && ret == -ENODATA) {
7898 mDisableWaitCnt = 1;
7899 }
7900
7901 // clear auxiliary effect input buffer for next accumulation
7902 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007903 memset(mConfig.inputCfg.buffer.raw, 0,
7904 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905 }
7906 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007907 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7908 // If an insert effect is idle and input buffer is different from output buffer,
7909 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007911 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007912 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7913 int16_t *in = mConfig.inputCfg.buffer.s16;
7914 int16_t *out = mConfig.outputCfg.buffer.s16;
7915 for (size_t i = 0; i < frameCnt; i++) {
7916 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007917 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918 }
7919 }
7920}
7921
7922void AudioFlinger::EffectModule::reset_l()
7923{
7924 if (mEffectInterface == NULL) {
7925 return;
7926 }
7927 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7928}
7929
7930status_t AudioFlinger::EffectModule::configure()
7931{
7932 uint32_t channels;
7933 if (mEffectInterface == NULL) {
7934 return NO_INIT;
7935 }
7936
7937 sp<ThreadBase> thread = mThread.promote();
7938 if (thread == 0) {
7939 return DEAD_OBJECT;
7940 }
7941
7942 // TODO: handle configuration of effects replacing track process
7943 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007944 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007945 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007946 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947 }
7948
7949 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007950 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951 } else {
7952 mConfig.inputCfg.channels = channels;
7953 }
7954 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007955 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7956 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007957 mConfig.inputCfg.samplingRate = thread->sampleRate();
7958 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7959 mConfig.inputCfg.bufferProvider.cookie = NULL;
7960 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7961 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7962 mConfig.outputCfg.bufferProvider.cookie = NULL;
7963 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7964 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7965 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7966 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007967 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007968 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969 // - in other sessions:
7970 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7971 // other effect: overwrites output buffer: input buffer == output buffer
7972 // Auxiliary effect:
7973 // accumulates in output buffer: input buffer != output buffer
7974 // Therefore: accumulate <=> input buffer != output buffer
7975 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7976 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7977 } else {
7978 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7979 }
7980 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7981 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7982 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7983 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7984
Steve Block3856b092011-10-20 11:56:00 +01007985 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007986 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7987
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007989 uint32_t size = sizeof(int);
7990 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007991 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007992 sizeof(effect_config_t),
7993 &mConfig,
7994 &size,
7995 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996 if (status == 0) {
7997 status = cmdStatus;
7998 }
7999
8000 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8001 (1000 * mConfig.outputCfg.buffer.frameCount);
8002
8003 return status;
8004}
8005
8006status_t AudioFlinger::EffectModule::init()
8007{
8008 Mutex::Autolock _l(mLock);
8009 if (mEffectInterface == NULL) {
8010 return NO_INIT;
8011 }
8012 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008013 uint32_t size = sizeof(status_t);
8014 status_t status = (*mEffectInterface)->command(mEffectInterface,
8015 EFFECT_CMD_INIT,
8016 0,
8017 NULL,
8018 &size,
8019 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008020 if (status == 0) {
8021 status = cmdStatus;
8022 }
8023 return status;
8024}
8025
Eric Laurentec35a142011-10-05 17:42:25 -07008026status_t AudioFlinger::EffectModule::start()
8027{
8028 Mutex::Autolock _l(mLock);
8029 return start_l();
8030}
8031
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032status_t AudioFlinger::EffectModule::start_l()
8033{
8034 if (mEffectInterface == NULL) {
8035 return NO_INIT;
8036 }
8037 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008038 uint32_t size = sizeof(status_t);
8039 status_t status = (*mEffectInterface)->command(mEffectInterface,
8040 EFFECT_CMD_ENABLE,
8041 0,
8042 NULL,
8043 &size,
8044 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045 if (status == 0) {
8046 status = cmdStatus;
8047 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008048 if (status == 0 &&
8049 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8050 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8051 sp<ThreadBase> thread = mThread.promote();
8052 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008053 audio_stream_t *stream = thread->stream();
8054 if (stream != NULL) {
8055 stream->add_audio_effect(stream, mEffectInterface);
8056 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008057 }
8058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059 return status;
8060}
8061
Eric Laurentec437d82011-07-26 20:54:46 -07008062status_t AudioFlinger::EffectModule::stop()
8063{
8064 Mutex::Autolock _l(mLock);
8065 return stop_l();
8066}
8067
Mathias Agopian65ab4712010-07-14 17:59:35 -07008068status_t AudioFlinger::EffectModule::stop_l()
8069{
8070 if (mEffectInterface == NULL) {
8071 return NO_INIT;
8072 }
8073 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008074 uint32_t size = sizeof(status_t);
8075 status_t status = (*mEffectInterface)->command(mEffectInterface,
8076 EFFECT_CMD_DISABLE,
8077 0,
8078 NULL,
8079 &size,
8080 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008081 if (status == 0) {
8082 status = cmdStatus;
8083 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008084 if (status == 0 &&
8085 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8086 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8087 sp<ThreadBase> thread = mThread.promote();
8088 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008089 audio_stream_t *stream = thread->stream();
8090 if (stream != NULL) {
8091 stream->remove_audio_effect(stream, mEffectInterface);
8092 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008093 }
8094 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095 return status;
8096}
8097
Eric Laurent25f43952010-07-28 05:40:18 -07008098status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8099 uint32_t cmdSize,
8100 void *pCmdData,
8101 uint32_t *replySize,
8102 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008103{
8104 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008105// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008106
Eric Laurentec437d82011-07-26 20:54:46 -07008107 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108 return NO_INIT;
8109 }
Eric Laurent25f43952010-07-28 05:40:18 -07008110 status_t status = (*mEffectInterface)->command(mEffectInterface,
8111 cmdCode,
8112 cmdSize,
8113 pCmdData,
8114 replySize,
8115 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008116 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008117 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118 for (size_t i = 1; i < mHandles.size(); i++) {
8119 sp<EffectHandle> h = mHandles[i].promote();
8120 if (h != 0) {
8121 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8122 }
8123 }
8124 }
8125 return status;
8126}
8127
8128status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8129{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008130
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008132 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008133
8134 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008135 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8136 if (enabled && status != NO_ERROR) {
8137 return status;
8138 }
8139
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140 switch (mState) {
8141 // going from disabled to enabled
8142 case IDLE:
8143 mState = STARTING;
8144 break;
8145 case STOPPED:
8146 mState = RESTART;
8147 break;
8148 case STOPPING:
8149 mState = ACTIVE;
8150 break;
8151
8152 // going from enabled to disabled
8153 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008154 mState = STOPPED;
8155 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 case STARTING:
8157 mState = IDLE;
8158 break;
8159 case ACTIVE:
8160 mState = STOPPING;
8161 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008162 case DESTROYED:
8163 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008164 }
8165 for (size_t i = 1; i < mHandles.size(); i++) {
8166 sp<EffectHandle> h = mHandles[i].promote();
8167 if (h != 0) {
8168 h->setEnabled(enabled);
8169 }
8170 }
8171 }
8172 return NO_ERROR;
8173}
8174
Glenn Kastenc59c0042012-02-02 14:06:11 -08008175bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008176{
8177 switch (mState) {
8178 case RESTART:
8179 case STARTING:
8180 case ACTIVE:
8181 return true;
8182 case IDLE:
8183 case STOPPING:
8184 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008185 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186 default:
8187 return false;
8188 }
8189}
8190
Glenn Kastenc59c0042012-02-02 14:06:11 -08008191bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008192{
8193 switch (mState) {
8194 case RESTART:
8195 case ACTIVE:
8196 case STOPPING:
8197 case STOPPED:
8198 return true;
8199 case IDLE:
8200 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008201 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008202 default:
8203 return false;
8204 }
8205}
8206
Mathias Agopian65ab4712010-07-14 17:59:35 -07008207status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8208{
8209 Mutex::Autolock _l(mLock);
8210 status_t status = NO_ERROR;
8211
8212 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8213 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008214 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008215 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8216 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 status_t cmdStatus;
8218 uint32_t volume[2];
8219 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008220 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008221 volume[0] = *left;
8222 volume[1] = *right;
8223 if (controller) {
8224 pVolume = volume;
8225 }
Eric Laurent25f43952010-07-28 05:40:18 -07008226 status = (*mEffectInterface)->command(mEffectInterface,
8227 EFFECT_CMD_SET_VOLUME,
8228 size,
8229 volume,
8230 &size,
8231 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008232 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8233 *left = volume[0];
8234 *right = volume[1];
8235 }
8236 }
8237 return status;
8238}
8239
8240status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8241{
8242 Mutex::Autolock _l(mLock);
8243 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008244 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8245 // audio pre processing modules on RecordThread can receive both output and
8246 // input device indication in the same call
8247 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8248 if (dev) {
8249 status_t cmdStatus;
8250 uint32_t size = sizeof(status_t);
8251
8252 status = (*mEffectInterface)->command(mEffectInterface,
8253 EFFECT_CMD_SET_DEVICE,
8254 sizeof(uint32_t),
8255 &dev,
8256 &size,
8257 &cmdStatus);
8258 if (status == NO_ERROR) {
8259 status = cmdStatus;
8260 }
8261 }
8262 dev = device & AUDIO_DEVICE_IN_ALL;
8263 if (dev) {
8264 status_t cmdStatus;
8265 uint32_t size = sizeof(status_t);
8266
8267 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8268 EFFECT_CMD_SET_INPUT_DEVICE,
8269 sizeof(uint32_t),
8270 &dev,
8271 &size,
8272 &cmdStatus);
8273 if (status2 == NO_ERROR) {
8274 status2 = cmdStatus;
8275 }
8276 if (status == NO_ERROR) {
8277 status = status2;
8278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008279 }
8280 }
8281 return status;
8282}
8283
Glenn Kastenf78aee72012-01-04 11:00:47 -08008284status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008285{
8286 Mutex::Autolock _l(mLock);
8287 status_t status = NO_ERROR;
8288 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008289 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008290 uint32_t size = sizeof(status_t);
8291 status = (*mEffectInterface)->command(mEffectInterface,
8292 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008293 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008294 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008295 &size,
8296 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008297 if (status == NO_ERROR) {
8298 status = cmdStatus;
8299 }
8300 }
8301 return status;
8302}
8303
Eric Laurent59255e42011-07-27 19:49:51 -07008304void AudioFlinger::EffectModule::setSuspended(bool suspended)
8305{
8306 Mutex::Autolock _l(mLock);
8307 mSuspended = suspended;
8308}
Glenn Kastena3a85482012-01-04 11:01:11 -08008309
8310bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008311{
8312 Mutex::Autolock _l(mLock);
8313 return mSuspended;
8314}
8315
Mathias Agopian65ab4712010-07-14 17:59:35 -07008316status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8317{
8318 const size_t SIZE = 256;
8319 char buffer[SIZE];
8320 String8 result;
8321
8322 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8323 result.append(buffer);
8324
8325 bool locked = tryLock(mLock);
8326 // failed to lock - AudioFlinger is probably deadlocked
8327 if (!locked) {
8328 result.append("\t\tCould not lock Fx mutex:\n");
8329 }
8330
8331 result.append("\t\tSession Status State Engine:\n");
8332 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8333 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8334 result.append(buffer);
8335
8336 result.append("\t\tDescriptor:\n");
8337 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8338 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8339 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8340 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8341 result.append(buffer);
8342 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8343 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8344 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8345 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8346 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008347 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008348 mDescriptor.apiVersion,
8349 mDescriptor.flags);
8350 result.append(buffer);
8351 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8352 mDescriptor.name);
8353 result.append(buffer);
8354 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8355 mDescriptor.implementor);
8356 result.append(buffer);
8357
8358 result.append("\t\t- Input configuration:\n");
8359 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8360 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8361 (uint32_t)mConfig.inputCfg.buffer.raw,
8362 mConfig.inputCfg.buffer.frameCount,
8363 mConfig.inputCfg.samplingRate,
8364 mConfig.inputCfg.channels,
8365 mConfig.inputCfg.format);
8366 result.append(buffer);
8367
8368 result.append("\t\t- Output configuration:\n");
8369 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8370 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8371 (uint32_t)mConfig.outputCfg.buffer.raw,
8372 mConfig.outputCfg.buffer.frameCount,
8373 mConfig.outputCfg.samplingRate,
8374 mConfig.outputCfg.channels,
8375 mConfig.outputCfg.format);
8376 result.append(buffer);
8377
8378 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8379 result.append(buffer);
8380 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8381 for (size_t i = 0; i < mHandles.size(); ++i) {
8382 sp<EffectHandle> handle = mHandles[i].promote();
8383 if (handle != 0) {
8384 handle->dump(buffer, SIZE);
8385 result.append(buffer);
8386 }
8387 }
8388
8389 result.append("\n");
8390
8391 write(fd, result.string(), result.length());
8392
8393 if (locked) {
8394 mLock.unlock();
8395 }
8396
8397 return NO_ERROR;
8398}
8399
8400// ----------------------------------------------------------------------------
8401// EffectHandle implementation
8402// ----------------------------------------------------------------------------
8403
8404#undef LOG_TAG
8405#define LOG_TAG "AudioFlinger::EffectHandle"
8406
8407AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8408 const sp<AudioFlinger::Client>& client,
8409 const sp<IEffectClient>& effectClient,
8410 int32_t priority)
8411 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008412 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008413 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008414{
Steve Block3856b092011-10-20 11:56:00 +01008415 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008416
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008417 if (client == 0) {
8418 return;
8419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008420 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8421 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8422 if (mCblkMemory != 0) {
8423 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8424
Glenn Kastena0d68332012-01-27 16:47:15 -08008425 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008426 new(mCblk) effect_param_cblk_t();
8427 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008429 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008430 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008431 return;
8432 }
8433}
8434
8435AudioFlinger::EffectHandle::~EffectHandle()
8436{
Steve Block3856b092011-10-20 11:56:00 +01008437 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008438 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008439 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008440}
8441
8442status_t AudioFlinger::EffectHandle::enable()
8443{
Steve Block3856b092011-10-20 11:56:00 +01008444 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008445 if (!mHasControl) return INVALID_OPERATION;
8446 if (mEffect == 0) return DEAD_OBJECT;
8447
Eric Laurentdb7c0792011-08-10 10:37:50 -07008448 if (mEnabled) {
8449 return NO_ERROR;
8450 }
8451
Eric Laurent59255e42011-07-27 19:49:51 -07008452 mEnabled = true;
8453
8454 sp<ThreadBase> thread = mEffect->thread().promote();
8455 if (thread != 0) {
8456 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8457 }
8458
8459 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8460 if (mEffect->suspended()) {
8461 return NO_ERROR;
8462 }
8463
Eric Laurentdb7c0792011-08-10 10:37:50 -07008464 status_t status = mEffect->setEnabled(true);
8465 if (status != NO_ERROR) {
8466 if (thread != 0) {
8467 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8468 }
8469 mEnabled = false;
8470 }
8471 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008472}
8473
8474status_t AudioFlinger::EffectHandle::disable()
8475{
Steve Block3856b092011-10-20 11:56:00 +01008476 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008477 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008478 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008479
Eric Laurentdb7c0792011-08-10 10:37:50 -07008480 if (!mEnabled) {
8481 return NO_ERROR;
8482 }
Eric Laurent59255e42011-07-27 19:49:51 -07008483 mEnabled = false;
8484
8485 if (mEffect->suspended()) {
8486 return NO_ERROR;
8487 }
8488
8489 status_t status = mEffect->setEnabled(false);
8490
8491 sp<ThreadBase> thread = mEffect->thread().promote();
8492 if (thread != 0) {
8493 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8494 }
8495
8496 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497}
8498
8499void AudioFlinger::EffectHandle::disconnect()
8500{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008501 disconnect(true);
8502}
8503
Glenn Kasten58123c32012-02-03 10:32:24 -08008504void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008505{
Glenn Kasten58123c32012-02-03 10:32:24 -08008506 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008507 if (mEffect == 0) {
8508 return;
8509 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008510 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008511
Eric Laurenta85a74a2011-10-19 11:44:54 -07008512 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008513 sp<ThreadBase> thread = mEffect->thread().promote();
8514 if (thread != 0) {
8515 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8516 }
Eric Laurent59255e42011-07-27 19:49:51 -07008517 }
8518
Mathias Agopian65ab4712010-07-14 17:59:35 -07008519 // release sp on module => module destructor can be called now
8520 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008521 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008522 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008523 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008524 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8525 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008526 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008527 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8529 mClient.clear();
8530 }
8531}
8532
Eric Laurent25f43952010-07-28 05:40:18 -07008533status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8534 uint32_t cmdSize,
8535 void *pCmdData,
8536 uint32_t *replySize,
8537 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538{
Steve Block3856b092011-10-20 11:56:00 +01008539// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008540// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008541
8542 // only get parameter command is permitted for applications not controlling the effect
8543 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8544 return INVALID_OPERATION;
8545 }
8546 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008547 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008548
8549 // handle commands that are not forwarded transparently to effect engine
8550 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8551 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8552 // no risk to block the whole media server process or mixer threads is we are stuck here
8553 Mutex::Autolock _l(mCblk->lock);
8554 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8555 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8556 mCblk->serverIndex = 0;
8557 mCblk->clientIndex = 0;
8558 return BAD_VALUE;
8559 }
8560 status_t status = NO_ERROR;
8561 while (mCblk->serverIndex < mCblk->clientIndex) {
8562 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008563 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008564 int *p = (int *)(mBuffer + mCblk->serverIndex);
8565 int size = *p++;
8566 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008567 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008568 break;
8569 }
8570 effect_param_t *param = (effect_param_t *)p;
8571 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008572 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008573 mCblk->serverIndex += size;
8574 continue;
8575 }
Eric Laurent25f43952010-07-28 05:40:18 -07008576 uint32_t psize = sizeof(effect_param_t) +
8577 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8578 param->vsize;
8579 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8580 psize,
8581 p,
8582 &rsize,
8583 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008584 // stop at first error encountered
8585 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008586 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008587 *(int *)pReplyData = reply;
8588 break;
8589 } else if (reply != NO_ERROR) {
8590 *(int *)pReplyData = reply;
8591 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008592 }
8593 mCblk->serverIndex += size;
8594 }
8595 mCblk->serverIndex = 0;
8596 mCblk->clientIndex = 0;
8597 return status;
8598 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008599 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008600 return enable();
8601 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008602 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008603 return disable();
8604 }
8605
8606 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8607}
8608
Eric Laurent59255e42011-07-27 19:49:51 -07008609void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008610{
Steve Block3856b092011-10-20 11:56:00 +01008611 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612
8613 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008614 mEnabled = enabled;
8615
Mathias Agopian65ab4712010-07-14 17:59:35 -07008616 if (signal && mEffectClient != 0) {
8617 mEffectClient->controlStatusChanged(hasControl);
8618 }
8619}
8620
Eric Laurent25f43952010-07-28 05:40:18 -07008621void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8622 uint32_t cmdSize,
8623 void *pCmdData,
8624 uint32_t replySize,
8625 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008626{
8627 if (mEffectClient != 0) {
8628 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8629 }
8630}
8631
8632
8633
8634void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8635{
8636 if (mEffectClient != 0) {
8637 mEffectClient->enableStatusChanged(enabled);
8638 }
8639}
8640
8641status_t AudioFlinger::EffectHandle::onTransact(
8642 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8643{
8644 return BnEffect::onTransact(code, data, reply, flags);
8645}
8646
8647
8648void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8649{
Glenn Kastena0d68332012-01-27 16:47:15 -08008650 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651
8652 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008653 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008654 mPriority,
8655 mHasControl,
8656 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008657 mCblk ? mCblk->clientIndex : 0,
8658 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008659 );
8660
8661 if (locked) {
8662 mCblk->lock.unlock();
8663 }
8664}
8665
8666#undef LOG_TAG
8667#define LOG_TAG "AudioFlinger::EffectChain"
8668
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008669AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008670 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008671 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008672 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8673 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008674{
Dima Zavinfce7a472011-04-19 22:30:36 -07008675 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008676 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008677 return;
8678 }
8679 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8680 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008681}
8682
8683AudioFlinger::EffectChain::~EffectChain()
8684{
8685 if (mOwnInBuffer) {
8686 delete mInBuffer;
8687 }
8688
8689}
8690
Eric Laurent59255e42011-07-27 19:49:51 -07008691// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008692sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008693{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008694 size_t size = mEffects.size();
8695
8696 for (size_t i = 0; i < size; i++) {
8697 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008698 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699 }
8700 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008701 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008702}
8703
Eric Laurent59255e42011-07-27 19:49:51 -07008704// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008705sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008706{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 size_t size = mEffects.size();
8708
8709 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008710 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8711 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008712 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008713 }
8714 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008715 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008716}
8717
Eric Laurent59255e42011-07-27 19:49:51 -07008718// getEffectFromType_l() must be called with ThreadBase::mLock held
8719sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8720 const effect_uuid_t *type)
8721{
Eric Laurent59255e42011-07-27 19:49:51 -07008722 size_t size = mEffects.size();
8723
8724 for (size_t i = 0; i < size; i++) {
8725 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008726 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008727 }
8728 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008729 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008730}
8731
Mathias Agopian65ab4712010-07-14 17:59:35 -07008732// Must be called with EffectChain::mLock locked
8733void AudioFlinger::EffectChain::process_l()
8734{
Eric Laurentdac69112010-09-28 14:09:57 -07008735 sp<ThreadBase> thread = mThread.promote();
8736 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008737 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008738 return;
8739 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008740 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8741 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008742 // always process effects unless no more tracks are on the session and the effect tail
8743 // has been rendered
8744 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008745 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008746 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008747
Eric Laurent544fe9b2011-11-11 15:42:52 -08008748 if (!tracksOnSession && mTailBufferCount == 0) {
8749 doProcess = false;
8750 }
8751
8752 if (activeTrackCnt() == 0) {
8753 // if no track is active and the effect tail has not been rendered,
8754 // the input buffer must be cleared here as the mixer process will not do it
8755 if (tracksOnSession || mTailBufferCount > 0) {
8756 size_t numSamples = thread->frameCount() * thread->channelCount();
8757 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8758 if (mTailBufferCount > 0) {
8759 mTailBufferCount--;
8760 }
8761 }
8762 }
Eric Laurentdac69112010-09-28 14:09:57 -07008763 }
8764
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008766 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008767 for (size_t i = 0; i < size; i++) {
8768 mEffects[i]->process();
8769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008770 }
8771 for (size_t i = 0; i < size; i++) {
8772 mEffects[i]->updateState();
8773 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008774}
8775
Eric Laurentcab11242010-07-15 12:50:15 -07008776// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008777status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008778{
8779 effect_descriptor_t desc = effect->desc();
8780 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8781
8782 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008783 effect->setChain(this);
8784 sp<ThreadBase> thread = mThread.promote();
8785 if (thread == 0) {
8786 return NO_INIT;
8787 }
8788 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008789
8790 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8791 // Auxiliary effects are inserted at the beginning of mEffects vector as
8792 // they are processed first and accumulated in chain input buffer
8793 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008794
Mathias Agopian65ab4712010-07-14 17:59:35 -07008795 // the input buffer for auxiliary effect contains mono samples in
8796 // 32 bit format. This is to avoid saturation in AudoMixer
8797 // accumulation stage. Saturation is done in EffectModule::process() before
8798 // calling the process in effect engine
8799 size_t numSamples = thread->frameCount();
8800 int32_t *buffer = new int32_t[numSamples];
8801 memset(buffer, 0, numSamples * sizeof(int32_t));
8802 effect->setInBuffer((int16_t *)buffer);
8803 // auxiliary effects output samples to chain input buffer for further processing
8804 // by insert effects
8805 effect->setOutBuffer(mInBuffer);
8806 } else {
8807 // Insert effects are inserted at the end of mEffects vector as they are processed
8808 // after track and auxiliary effects.
8809 // Insert effect order as a function of indicated preference:
8810 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8811 // another effect is present
8812 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8813 // last effect claiming first position
8814 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8815 // first effect claiming last position
8816 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8817 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8818 // already present
8819
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008820 size_t size = mEffects.size();
8821 size_t idx_insert = size;
8822 ssize_t idx_insert_first = -1;
8823 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008824
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008825 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826 effect_descriptor_t d = mEffects[i]->desc();
8827 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8828 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8829 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8830 // check invalid effect chaining combinations
8831 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8832 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008833 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008834 return INVALID_OPERATION;
8835 }
8836 // remember position of first insert effect and by default
8837 // select this as insert position for new effect
8838 if (idx_insert == size) {
8839 idx_insert = i;
8840 }
8841 // remember position of last insert effect claiming
8842 // first position
8843 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8844 idx_insert_first = i;
8845 }
8846 // remember position of first insert effect claiming
8847 // last position
8848 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8849 idx_insert_last == -1) {
8850 idx_insert_last = i;
8851 }
8852 }
8853 }
8854
8855 // modify idx_insert from first position if needed
8856 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8857 if (idx_insert_last != -1) {
8858 idx_insert = idx_insert_last;
8859 } else {
8860 idx_insert = size;
8861 }
8862 } else {
8863 if (idx_insert_first != -1) {
8864 idx_insert = idx_insert_first + 1;
8865 }
8866 }
8867
8868 // always read samples from chain input buffer
8869 effect->setInBuffer(mInBuffer);
8870
8871 // if last effect in the chain, output samples to chain
8872 // output buffer, otherwise to chain input buffer
8873 if (idx_insert == size) {
8874 if (idx_insert != 0) {
8875 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8876 mEffects[idx_insert-1]->configure();
8877 }
8878 effect->setOutBuffer(mOutBuffer);
8879 } else {
8880 effect->setOutBuffer(mInBuffer);
8881 }
8882 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883
Steve Block3856b092011-10-20 11:56:00 +01008884 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008885 }
8886 effect->configure();
8887 return NO_ERROR;
8888}
8889
Eric Laurentcab11242010-07-15 12:50:15 -07008890// removeEffect_l() must be called with PlaybackThread::mLock held
8891size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892{
8893 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008894 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008895 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8896
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008897 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008898 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008899 // calling stop here will remove pre-processing effect from the audio HAL.
8900 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8901 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008902 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8903 mEffects[i]->state() == EffectModule::STOPPING) {
8904 mEffects[i]->stop();
8905 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008906 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8907 delete[] effect->inBuffer();
8908 } else {
8909 if (i == size - 1 && i != 0) {
8910 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8911 mEffects[i - 1]->configure();
8912 }
8913 }
8914 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008915 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008916 break;
8917 }
8918 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008919
8920 return mEffects.size();
8921}
8922
Eric Laurentcab11242010-07-15 12:50:15 -07008923// setDevice_l() must be called with PlaybackThread::mLock held
8924void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008925{
8926 size_t size = mEffects.size();
8927 for (size_t i = 0; i < size; i++) {
8928 mEffects[i]->setDevice(device);
8929 }
8930}
8931
Eric Laurentcab11242010-07-15 12:50:15 -07008932// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008933void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008934{
8935 size_t size = mEffects.size();
8936 for (size_t i = 0; i < size; i++) {
8937 mEffects[i]->setMode(mode);
8938 }
8939}
8940
Eric Laurentcab11242010-07-15 12:50:15 -07008941// setVolume_l() must be called with PlaybackThread::mLock held
8942bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008943{
8944 uint32_t newLeft = *left;
8945 uint32_t newRight = *right;
8946 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008947 int ctrlIdx = -1;
8948 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008949
Eric Laurentcab11242010-07-15 12:50:15 -07008950 // first update volume controller
8951 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008952 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008953 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8954 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008955 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008956 break;
8957 }
8958 }
8959
8960 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008961 if (hasControl) {
8962 *left = mNewLeftVolume;
8963 *right = mNewRightVolume;
8964 }
8965 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008966 }
8967
8968 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008969 mLeftVolume = newLeft;
8970 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008971
8972 // second get volume update from volume controller
8973 if (ctrlIdx >= 0) {
8974 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008975 mNewLeftVolume = newLeft;
8976 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008977 }
8978 // then indicate volume to all other effects in chain.
8979 // Pass altered volume to effects before volume controller
8980 // and requested volume to effects after controller
8981 uint32_t lVol = newLeft;
8982 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008983
Mathias Agopian65ab4712010-07-14 17:59:35 -07008984 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008985 if ((int)i == ctrlIdx) continue;
8986 // this also works for ctrlIdx == -1 when there is no volume controller
8987 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008988 lVol = *left;
8989 rVol = *right;
8990 }
8991 mEffects[i]->setVolume(&lVol, &rVol, false);
8992 }
8993 *left = newLeft;
8994 *right = newRight;
8995
8996 return hasControl;
8997}
8998
Mathias Agopian65ab4712010-07-14 17:59:35 -07008999status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9000{
9001 const size_t SIZE = 256;
9002 char buffer[SIZE];
9003 String8 result;
9004
9005 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9006 result.append(buffer);
9007
9008 bool locked = tryLock(mLock);
9009 // failed to lock - AudioFlinger is probably deadlocked
9010 if (!locked) {
9011 result.append("\tCould not lock mutex:\n");
9012 }
9013
Eric Laurentcab11242010-07-15 12:50:15 -07009014 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9015 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016 mEffects.size(),
9017 (uint32_t)mInBuffer,
9018 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009019 mActiveTrackCnt);
9020 result.append(buffer);
9021 write(fd, result.string(), result.size());
9022
9023 for (size_t i = 0; i < mEffects.size(); ++i) {
9024 sp<EffectModule> effect = mEffects[i];
9025 if (effect != 0) {
9026 effect->dump(fd, args);
9027 }
9028 }
9029
9030 if (locked) {
9031 mLock.unlock();
9032 }
9033
9034 return NO_ERROR;
9035}
9036
Eric Laurent59255e42011-07-27 19:49:51 -07009037// must be called with ThreadBase::mLock held
9038void AudioFlinger::EffectChain::setEffectSuspended_l(
9039 const effect_uuid_t *type, bool suspend)
9040{
9041 sp<SuspendedEffectDesc> desc;
9042 // use effect type UUID timelow as key as there is no real risk of identical
9043 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009044 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009045 if (suspend) {
9046 if (index >= 0) {
9047 desc = mSuspendedEffects.valueAt(index);
9048 } else {
9049 desc = new SuspendedEffectDesc();
9050 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9051 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009052 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009053 }
9054 if (desc->mRefCount++ == 0) {
9055 sp<EffectModule> effect = getEffectIfEnabled(type);
9056 if (effect != 0) {
9057 desc->mEffect = effect;
9058 effect->setSuspended(true);
9059 effect->setEnabled(false);
9060 }
9061 }
9062 } else {
9063 if (index < 0) {
9064 return;
9065 }
9066 desc = mSuspendedEffects.valueAt(index);
9067 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009068 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009069 desc->mRefCount = 1;
9070 }
9071 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009072 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009073 if (desc->mEffect != 0) {
9074 sp<EffectModule> effect = desc->mEffect.promote();
9075 if (effect != 0) {
9076 effect->setSuspended(false);
9077 sp<EffectHandle> handle = effect->controlHandle();
9078 if (handle != 0) {
9079 effect->setEnabled(handle->enabled());
9080 }
9081 }
9082 desc->mEffect.clear();
9083 }
9084 mSuspendedEffects.removeItemsAt(index);
9085 }
9086 }
9087}
9088
9089// must be called with ThreadBase::mLock held
9090void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9091{
9092 sp<SuspendedEffectDesc> desc;
9093
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009094 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009095 if (suspend) {
9096 if (index >= 0) {
9097 desc = mSuspendedEffects.valueAt(index);
9098 } else {
9099 desc = new SuspendedEffectDesc();
9100 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009101 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009102 }
9103 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009104 Vector< sp<EffectModule> > effects;
9105 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009106 for (size_t i = 0; i < effects.size(); i++) {
9107 setEffectSuspended_l(&effects[i]->desc().type, true);
9108 }
9109 }
9110 } else {
9111 if (index < 0) {
9112 return;
9113 }
9114 desc = mSuspendedEffects.valueAt(index);
9115 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009116 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009117 desc->mRefCount = 1;
9118 }
9119 if (--desc->mRefCount == 0) {
9120 Vector<const effect_uuid_t *> types;
9121 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9122 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9123 continue;
9124 }
9125 types.add(&mSuspendedEffects.valueAt(i)->mType);
9126 }
9127 for (size_t i = 0; i < types.size(); i++) {
9128 setEffectSuspended_l(types[i], false);
9129 }
Steve Block3856b092011-10-20 11:56:00 +01009130 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009131 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9132 }
9133 }
9134}
9135
Eric Laurent6bffdb82011-09-23 08:40:41 -07009136
9137// The volume effect is used for automated tests only
9138#ifndef OPENSL_ES_H_
9139static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9140 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9141const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9142#endif //OPENSL_ES_H_
9143
Eric Laurentdb7c0792011-08-10 10:37:50 -07009144bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9145{
9146 // auxiliary effects and visualizer are never suspended on output mix
9147 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9148 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009149 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9150 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009151 return false;
9152 }
9153 return true;
9154}
9155
Glenn Kastend0539712012-01-30 12:56:03 -08009156void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009157{
Glenn Kastend0539712012-01-30 12:56:03 -08009158 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009159 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009160 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9161 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009162 }
Eric Laurent59255e42011-07-27 19:49:51 -07009163 }
Eric Laurent59255e42011-07-27 19:49:51 -07009164}
9165
9166sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9167 const effect_uuid_t *type)
9168{
Glenn Kasten090f0192012-01-30 13:00:02 -08009169 sp<EffectModule> effect = getEffectFromType_l(type);
9170 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009171}
9172
9173void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9174 bool enabled)
9175{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009176 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009177 if (enabled) {
9178 if (index < 0) {
9179 // if the effect is not suspend check if all effects are suspended
9180 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9181 if (index < 0) {
9182 return;
9183 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009184 if (!isEffectEligibleForSuspend(effect->desc())) {
9185 return;
9186 }
Eric Laurent59255e42011-07-27 19:49:51 -07009187 setEffectSuspended_l(&effect->desc().type, enabled);
9188 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009189 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009190 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009191 return;
9192 }
Eric Laurent59255e42011-07-27 19:49:51 -07009193 }
Steve Block3856b092011-10-20 11:56:00 +01009194 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009195 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009196 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9197 // if effect is requested to suspended but was not yet enabled, supend it now.
9198 if (desc->mEffect == 0) {
9199 desc->mEffect = effect;
9200 effect->setEnabled(false);
9201 effect->setSuspended(true);
9202 }
9203 } else {
9204 if (index < 0) {
9205 return;
9206 }
Steve Block3856b092011-10-20 11:56:00 +01009207 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009208 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009209 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9210 desc->mEffect.clear();
9211 effect->setSuspended(false);
9212 }
9213}
9214
Mathias Agopian65ab4712010-07-14 17:59:35 -07009215#undef LOG_TAG
9216#define LOG_TAG "AudioFlinger"
9217
9218// ----------------------------------------------------------------------------
9219
9220status_t AudioFlinger::onTransact(
9221 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9222{
9223 return BnAudioFlinger::onTransact(code, data, reply, flags);
9224}
9225
Mathias Agopian65ab4712010-07-14 17:59:35 -07009226}; // namespace android