blob: 4e770af6f62346ee8275b0babd5b3fa44821af89 [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
Glenn Kastend08f48c2012-05-01 18:14:02 -07002766 // or stopped which can occur when flush() is called while active
2767 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002768 track->mUnderrunCount += recentUnderruns;
2769 }
2770 track->mObservedUnderruns = underruns;
2771
Glenn Kastend08f48c2012-05-01 18:14:02 -07002772 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002773 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002774 bool isActive = true;
2775 switch (track->mState) {
2776 case TrackBase::STOPPING_1:
2777 // track stays active in STOPPING_1 state until first underrun
2778 if (recentUnderruns > 0) {
2779 track->mState = TrackBase::STOPPING_2;
2780 }
2781 break;
2782 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002783 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002784 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002785 break;
2786 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002787 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002788 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002789 break;
2790 case TrackBase::ACTIVE:
Glenn Kasten288ed212012-04-25 17:52:27 -07002791 // no minimum frame count for fast tracks; continual underrun is allowed,
2792 // but later could implement automatic pause after several consecutive underruns,
2793 // or auto-mute yet still consider the track active and continue to service it
Glenn Kastend08f48c2012-05-01 18:14:02 -07002794 if (track->sharedBuffer() == 0 || recentUnderruns == 0) {
2795 break;
2796 }
2797 // fall through
2798 case TrackBase::STOPPING_2:
2799 case TrackBase::PAUSED:
2800 case TrackBase::TERMINATED:
2801 case TrackBase::STOPPED: // flush() while active
2802 // Check for presentation complete if track is inactive
2803 // We have consumed all the buffers of this track.
2804 // This would be incomplete if we auto-paused on underrun
2805 {
2806 size_t audioHALFrames =
2807 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2808 size_t framesWritten =
2809 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2810 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2811 // track stays in active list until presentation is complete
2812 break;
2813 }
2814 }
2815 if (track->isStopping_2()) {
2816 track->mState = TrackBase::STOPPED;
2817 }
2818 if (track->isStopped()) {
2819 // Can't reset directly, as fast mixer is still polling this track
2820 // track->reset();
2821 // So instead mark this track as needing to be reset after push with ack
2822 resetMask |= 1 << i;
2823 }
2824 isActive = false;
2825 break;
2826 case TrackBase::IDLE:
2827 default:
2828 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002829 }
2830
2831 if (isActive) {
2832 // was it previously inactive?
2833 if (!(state->mTrackMask & (1 << j))) {
2834 ExtendedAudioBufferProvider *eabp = track;
2835 VolumeProvider *vp = track;
2836 fastTrack->mBufferProvider = eabp;
2837 fastTrack->mVolumeProvider = vp;
2838 fastTrack->mSampleRate = track->mSampleRate;
2839 fastTrack->mChannelMask = track->mChannelMask;
2840 fastTrack->mGeneration++;
2841 state->mTrackMask |= 1 << j;
2842 didModify = true;
2843 // no acknowledgement required for newly active tracks
2844 }
2845 // cache the combined master volume and stream type volume for fast mixer; this
2846 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2847 track->mCachedVolume = track->isMuted() ?
2848 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2849 ++fastTracks;
2850 } else {
2851 // was it previously active?
2852 if (state->mTrackMask & (1 << j)) {
2853 fastTrack->mBufferProvider = NULL;
2854 fastTrack->mGeneration++;
2855 state->mTrackMask &= ~(1 << j);
2856 didModify = true;
2857 // If any fast tracks were removed, we must wait for acknowledgement
2858 // because we're about to decrement the last sp<> on those tracks.
2859 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002860 } else {
2861 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002862 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002863 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002864 // Avoids a misleading display in dumpsys
2865 track->mObservedUnderruns &= ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07002866 }
2867 continue;
2868 }
2869
2870 { // local variable scope to avoid goto warning
2871
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872 audio_track_cblk_t* cblk = track->cblk();
2873
2874 // The first time a track is added we wait
2875 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002876 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002877 // make sure that we have enough frames to mix one full buffer.
2878 // enforce this condition only once to enable draining the buffer in case the client
2879 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002880 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002881 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002882 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002883 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002884 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002885 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002886 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002887 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002888 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002889 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002890 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002891 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002892 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2893 // the minimum track buffer size is normally twice the number of frames necessary
2894 // to fill one buffer and the resampler should not leave more than one buffer worth
2895 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002896 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002897 }
2898 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002899 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 !track->isPaused() && !track->isTerminated())
2901 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002902 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903
2904 mixedTracks++;
2905
2906 // track->mainBuffer() != mMixBuffer means there is an effect chain
2907 // connected to the track
2908 chain.clear();
2909 if (track->mainBuffer() != mMixBuffer) {
2910 chain = getEffectChain_l(track->sessionId());
2911 // Delegate volume control to effect in track effect chain if needed
2912 if (chain != 0) {
2913 tracksWithEffect++;
2914 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002915 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002916 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 }
2918 }
2919
2920
2921 int param = AudioMixer::VOLUME;
2922 if (track->mFillingUpStatus == Track::FS_FILLED) {
2923 // no ramp for the first volume setting
2924 track->mFillingUpStatus = Track::FS_ACTIVE;
2925 if (track->mState == TrackBase::RESUMING) {
2926 track->mState = TrackBase::ACTIVE;
2927 param = AudioMixer::RAMP_VOLUME;
2928 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002929 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930 } else if (cblk->server != 0) {
2931 // If the track is stopped before the first frame was mixed,
2932 // do not apply ramp
2933 param = AudioMixer::RAMP_VOLUME;
2934 }
2935
2936 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002937 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002938 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002939 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002940 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 if (track->isPausing()) {
2942 track->setPaused();
2943 }
2944 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002945
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002947 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002949 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002950 vl = vlr & 0xFFFF;
2951 vr = vlr >> 16;
2952 // track volumes come from shared memory, so can't be trusted and must be clamped
2953 if (vl > MAX_GAIN_INT) {
2954 ALOGV("Track left volume out of range: %04X", vl);
2955 vl = MAX_GAIN_INT;
2956 }
2957 if (vr > MAX_GAIN_INT) {
2958 ALOGV("Track right volume out of range: %04X", vr);
2959 vr = MAX_GAIN_INT;
2960 }
2961 // now apply the master volume and stream type volume
2962 vl = (uint32_t)(v * vl) << 12;
2963 vr = (uint32_t)(v * vr) << 12;
2964 // assuming master volume and stream type volume each go up to 1.0,
2965 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966
Glenn Kasten05632a52012-01-03 14:22:33 -08002967 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2968 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002969 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002970 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002971 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002972 }
2973 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002975 // Delegate volume control to effect in track effect chain if needed
2976 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2977 // Do not ramp volume if volume is controlled by effect
2978 param = AudioMixer::VOLUME;
2979 track->mHasVolumeController = true;
2980 } else {
2981 // force no volume ramp when volume controller was just disabled or removed
2982 // from effect chain to avoid volume spike
2983 if (track->mHasVolumeController) {
2984 param = AudioMixer::VOLUME;
2985 }
2986 track->mHasVolumeController = false;
2987 }
2988
2989 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002990 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002991 vl = (vl + (1 << 11)) >> 12;
2992 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2993 vr = (vr + (1 << 11)) >> 12;
2994 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002995
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002996 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 -07002997
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002999 mAudioMixer->setBufferProvider(name, track);
3000 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003002 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3003 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3004 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003006 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 AudioMixer::TRACK,
3008 AudioMixer::FORMAT, (void *)track->format());
3009 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003010 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003012 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003014 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 AudioMixer::RESAMPLE,
3016 AudioMixer::SAMPLE_RATE,
3017 (void *)(cblk->sampleRate));
3018 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003019 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020 AudioMixer::TRACK,
3021 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3022 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003023 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 AudioMixer::TRACK,
3025 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3026
3027 // reset retry count
3028 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003029
Eric Laurent27741442012-01-17 19:20:12 -08003030 // If one track is ready, set the mixer ready if:
3031 // - the mixer was not ready during previous round OR
3032 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003033 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003034 mixerStatus != MIXER_TRACKS_ENABLED) {
3035 mixerStatus = MIXER_TRACKS_READY;
3036 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003038 //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 -07003039 if (track->isStopped()) {
3040 track->reset();
3041 }
Eric Laurent83faee02012-04-27 18:24:29 -07003042 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3043 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 // We have consumed all the buffers of this track.
3045 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003046 // TODO: use actual buffer filling status instead of latency when available from
3047 // audio HAL
3048 size_t audioHALFrames =
3049 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3050 size_t framesWritten =
3051 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3052 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3053 tracksToRemove->add(track);
3054 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 } else {
3056 // No buffers for this track. Give it a few chances to
3057 // fill a buffer, then remove it from active list.
3058 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003059 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003061 // indicate to client process that the track was disabled because of underrun;
3062 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003063 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003064 // If one track is not ready, mark the mixer also not ready if:
3065 // - the mixer was ready during previous round OR
3066 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003067 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003068 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 mixerStatus = MIXER_TRACKS_ENABLED;
3070 }
3071 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003072 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 }
Glenn Kasten58912562012-04-03 10:45:00 -07003074
3075 } // local variable scope to avoid goto warning
3076track_is_ready: ;
3077
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 }
3079
Glenn Kasten288ed212012-04-25 17:52:27 -07003080 // Push the new FastMixer state if necessary
3081 if (didModify) {
3082 state->mFastTracksGen++;
3083 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3084 if (kUseFastMixer == FastMixer_Dynamic &&
3085 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3086 state->mCommand = FastMixerState::COLD_IDLE;
3087 state->mColdFutexAddr = &mFastMixerFutex;
3088 state->mColdGen++;
3089 mFastMixerFutex = 0;
3090 if (kUseFastMixer == FastMixer_Dynamic) {
3091 mNormalSink = mOutputSink;
3092 }
3093 // If we go into cold idle, need to wait for acknowledgement
3094 // so that fast mixer stops doing I/O.
3095 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3096 }
3097 sq->end();
3098 }
3099 if (sq != NULL) {
3100 sq->end(didModify);
3101 sq->push(block);
3102 }
3103
3104 // Now perform the deferred reset on fast tracks that have stopped
3105 while (resetMask != 0) {
3106 size_t i = __builtin_ctz(resetMask);
3107 ALOG_ASSERT(i < count);
3108 resetMask &= ~(1 << i);
3109 sp<Track> t = mActiveTracks[i].promote();
3110 if (t == 0) continue;
3111 Track* track = t.get();
3112 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3113 track->reset();
3114 }
Glenn Kasten58912562012-04-03 10:45:00 -07003115
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 // remove all the tracks that need to be...
3117 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003118 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119 for (size_t i=0 ; i<count ; i++) {
3120 const sp<Track>& track = tracksToRemove->itemAt(i);
3121 mActiveTracks.remove(track);
3122 if (track->mainBuffer() != mMixBuffer) {
3123 chain = getEffectChain_l(track->sessionId());
3124 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003125 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003126 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 }
3128 }
3129 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003130 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003131 }
3132 }
3133 }
3134
3135 // mix buffer must be cleared if all tracks are connected to an
3136 // effect chain as in this case the mixer will not write to
3137 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003138 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3139 // FIXME as a performance optimization, should remember previous zero status
3140 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141 }
3142
Glenn Kasten58912562012-04-03 10:45:00 -07003143 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003144 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003145 if (fastTracks > 0) {
3146 mixerStatus = MIXER_TRACKS_READY;
3147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148 return mixerStatus;
3149}
3150
Glenn Kasten66fcab92012-02-24 14:59:21 -08003151/*
3152The derived values that are cached:
3153 - mixBufferSize from frame count * frame size
3154 - activeSleepTime from activeSleepTimeUs()
3155 - idleSleepTime from idleSleepTimeUs()
3156 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3157 - maxPeriod from frame count and sample rate (MIXER only)
3158
3159The parameters that affect these derived values are:
3160 - frame count
3161 - frame size
3162 - sample rate
3163 - device type: A2DP or not
3164 - device latency
3165 - format: PCM or not
3166 - active sleep time
3167 - idle sleep time
3168*/
3169
3170void AudioFlinger::PlaybackThread::cacheParameters_l()
3171{
Glenn Kasten58912562012-04-03 10:45:00 -07003172 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003173 activeSleepTime = activeSleepTimeUs();
3174 idleSleepTime = idleSleepTimeUs();
3175}
3176
Glenn Kastenfff6d712012-01-12 16:38:12 -08003177void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178{
Steve Block3856b092011-10-20 11:56:00 +01003179 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003180 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003182
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 size_t size = mTracks.size();
3184 for (size_t i = 0; i < size; i++) {
3185 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003186 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003187 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 }
3190 }
3191}
3192
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003194int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003196 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197}
3198
3199// deleteTrackName_l() must be called with ThreadBase::mLock held
3200void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3201{
Steve Block3856b092011-10-20 11:56:00 +01003202 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 mAudioMixer->deleteTrackName(name);
3204}
3205
3206// checkForNewParameters_l() must be called with ThreadBase::mLock held
3207bool AudioFlinger::MixerThread::checkForNewParameters_l()
3208{
Glenn Kasten58912562012-04-03 10:45:00 -07003209 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3210 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 bool reconfig = false;
3212
3213 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003214
3215 if (mFastMixer != NULL) {
3216 FastMixerStateQueue *sq = mFastMixer->sq();
3217 FastMixerState *state = sq->begin();
3218 if (!(state->mCommand & FastMixerState::IDLE)) {
3219 previousCommand = state->mCommand;
3220 state->mCommand = FastMixerState::HOT_IDLE;
3221 sq->end();
3222 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3223 } else {
3224 sq->end(false /*didModify*/);
3225 }
3226 }
3227
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 status_t status = NO_ERROR;
3229 String8 keyValuePair = mNewParameters[0];
3230 AudioParameter param = AudioParameter(keyValuePair);
3231 int value;
3232
3233 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3234 reconfig = true;
3235 }
3236 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003237 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 status = BAD_VALUE;
3239 } else {
3240 reconfig = true;
3241 }
3242 }
3243 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003244 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 status = BAD_VALUE;
3246 } else {
3247 reconfig = true;
3248 }
3249 }
3250 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3251 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003252 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 // if frame count is changed after track creation
3254 if (!mTracks.isEmpty()) {
3255 status = INVALID_OPERATION;
3256 } else {
3257 reconfig = true;
3258 }
3259 }
3260 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003261#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003262 // when changing the audio output device, call addBatteryData to notify
3263 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003264 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003265 uint32_t params = 0;
3266 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003267 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003268 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3269 }
3270
3271 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003272 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003273 // check if any other device (except speaker) is on
3274 if (value & deviceWithoutSpeaker ) {
3275 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3276 }
3277
3278 if (params != 0) {
3279 addBatteryData(params);
3280 }
3281 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003282#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003283
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 // forward device change to effects that have requested to be
3285 // aware of attached audio device.
3286 mDevice = (uint32_t)value;
3287 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003288 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 }
3290 }
3291
3292 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003293 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003294 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003296 mOutput->stream->common.standby(&mOutput->stream->common);
3297 mStandby = true;
3298 mBytesWritten = 0;
3299 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003300 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 }
3302 if (status == NO_ERROR && reconfig) {
3303 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003304 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3305 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003307 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003309 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 if (name < 0) break;
3311 mTracks[i]->mName = name;
3312 // limit track sample rate to 2 x new output sample rate
3313 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3314 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3315 }
3316 }
3317 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3318 }
3319 }
3320
3321 mNewParameters.removeAt(0);
3322
3323 mParamStatus = status;
3324 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003325 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3326 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003327 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 }
Glenn Kasten58912562012-04-03 10:45:00 -07003329
3330 if (!(previousCommand & FastMixerState::IDLE)) {
3331 ALOG_ASSERT(mFastMixer != NULL);
3332 FastMixerStateQueue *sq = mFastMixer->sq();
3333 FastMixerState *state = sq->begin();
3334 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3335 state->mCommand = previousCommand;
3336 sq->end();
3337 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3338 }
3339
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 return reconfig;
3341}
3342
3343status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3344{
3345 const size_t SIZE = 256;
3346 char buffer[SIZE];
3347 String8 result;
3348
3349 PlaybackThread::dumpInternals(fd, args);
3350
3351 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3352 result.append(buffer);
3353 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003354
3355 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3356 FastMixerDumpState copy = mFastMixerDumpState;
3357 copy.dump(fd);
3358
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 return NO_ERROR;
3360}
3361
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003362uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363{
Glenn Kasten58912562012-04-03 10:45:00 -07003364 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365}
3366
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003367uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003368{
Glenn Kasten58912562012-04-03 10:45:00 -07003369 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003370}
3371
Glenn Kasten66fcab92012-02-24 14:59:21 -08003372void AudioFlinger::MixerThread::cacheParameters_l()
3373{
3374 PlaybackThread::cacheParameters_l();
3375
3376 // FIXME: Relaxed timing because of a certain device that can't meet latency
3377 // Should be reduced to 2x after the vendor fixes the driver issue
3378 // increase threshold again due to low power audio mode. The way this warning
3379 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003380 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003381}
3382
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003384AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3385 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003386 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003387 // mLeftVolFloat, mRightVolFloat
3388 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390}
3391
3392AudioFlinger::DirectOutputThread::~DirectOutputThread()
3393{
3394}
3395
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003396AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3397 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003398)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003400 sp<Track> trackToRemove;
3401
Glenn Kastenfec279f2012-03-08 07:47:15 -08003402 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403
Glenn Kasten952eeb22012-03-06 11:30:57 -08003404 // find out which tracks need to be processed
3405 if (mActiveTracks.size() != 0) {
3406 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003407 // The track died recently
3408 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409
Glenn Kasten952eeb22012-03-06 11:30:57 -08003410 Track* const track = t.get();
3411 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412
Glenn Kasten952eeb22012-03-06 11:30:57 -08003413 // The first time a track is added we wait
3414 // for all its buffers to be filled before processing it
3415 if (cblk->framesReady() && track->isReady() &&
3416 !track->isPaused() && !track->isTerminated())
3417 {
3418 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419
Glenn Kasten952eeb22012-03-06 11:30:57 -08003420 if (track->mFillingUpStatus == Track::FS_FILLED) {
3421 track->mFillingUpStatus = Track::FS_ACTIVE;
3422 mLeftVolFloat = mRightVolFloat = 0;
3423 mLeftVolShort = mRightVolShort = 0;
3424 if (track->mState == TrackBase::RESUMING) {
3425 track->mState = TrackBase::ACTIVE;
3426 rampVolume = true;
3427 }
3428 } else if (cblk->server != 0) {
3429 // If the track is stopped before the first frame was mixed,
3430 // do not apply ramp
3431 rampVolume = true;
3432 }
3433 // compute volume for this track
3434 float left, right;
3435 if (track->isMuted() || mMasterMute || track->isPausing() ||
3436 mStreamTypes[track->streamType()].mute) {
3437 left = right = 0;
3438 if (track->isPausing()) {
3439 track->setPaused();
3440 }
3441 } else {
3442 float typeVolume = mStreamTypes[track->streamType()].volume;
3443 float v = mMasterVolume * typeVolume;
3444 uint32_t vlr = cblk->getVolumeLR();
3445 float v_clamped = v * (vlr & 0xFFFF);
3446 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3447 left = v_clamped/MAX_GAIN;
3448 v_clamped = v * (vlr >> 16);
3449 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3450 right = v_clamped/MAX_GAIN;
3451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452
Glenn Kasten952eeb22012-03-06 11:30:57 -08003453 if (left != mLeftVolFloat || right != mRightVolFloat) {
3454 mLeftVolFloat = left;
3455 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456
Glenn Kasten952eeb22012-03-06 11:30:57 -08003457 // If audio HAL implements volume control,
3458 // force software volume to nominal value
3459 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3460 left = 1.0f;
3461 right = 1.0f;
3462 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463
Glenn Kasten952eeb22012-03-06 11:30:57 -08003464 // Convert volumes from float to 8.24
3465 uint32_t vl = (uint32_t)(left * (1 << 24));
3466 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467
Glenn Kasten952eeb22012-03-06 11:30:57 -08003468 // Delegate volume control to effect in track effect chain if needed
3469 // only one effect chain can be present on DirectOutputThread, so if
3470 // there is one, the track is connected to it
3471 if (!mEffectChains.isEmpty()) {
3472 // Do not ramp volume if volume is controlled by effect
3473 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 rampVolume = false;
3475 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477
Glenn Kasten952eeb22012-03-06 11:30:57 -08003478 // Convert volumes from 8.24 to 4.12 format
3479 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3480 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3481 leftVol = (uint16_t)v_clamped;
3482 v_clamped = (vr + (1 << 11)) >> 12;
3483 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3484 rightVol = (uint16_t)v_clamped;
3485 } else {
3486 leftVol = mLeftVolShort;
3487 rightVol = mRightVolShort;
3488 rampVolume = false;
3489 }
3490
3491 // reset retry count
3492 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003493 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003494 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003495 } else {
3496 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3497 if (track->isStopped()) {
3498 track->reset();
3499 }
3500 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3501 // We have consumed all the buffers of this track.
3502 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003503 // TODO: implement behavior for compressed audio
3504 size_t audioHALFrames =
3505 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3506 size_t framesWritten =
3507 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3508 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3509 trackToRemove = track;
3510 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003511 } else {
3512 // No buffers for this track. Give it a few chances to
3513 // fill a buffer, then remove it from active list.
3514 if (--(track->mRetryCount) <= 0) {
3515 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3516 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003518 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 }
3520 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003521 }
3522 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003524 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003525 // remove all the tracks that need to be...
3526 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003527 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003528 mActiveTracks.remove(trackToRemove);
3529 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003530 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003531 trackToRemove->sessionId());
3532 mEffectChains[0]->decActiveTrackCnt();
3533 }
3534 if (trackToRemove->isTerminated()) {
3535 removeTrack_l(trackToRemove);
3536 }
3537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538
Glenn Kastenfec279f2012-03-08 07:47:15 -08003539 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003540}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541
Glenn Kasten000f0e32012-03-01 17:10:56 -08003542void AudioFlinger::DirectOutputThread::threadLoop_mix()
3543{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003544 AudioBufferProvider::Buffer buffer;
3545 size_t frameCount = mFrameCount;
3546 int8_t *curBuf = (int8_t *)mMixBuffer;
3547 // output audio to hardware
3548 while (frameCount) {
3549 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003550 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003551 if (CC_UNLIKELY(buffer.raw == NULL)) {
3552 memset(curBuf, 0, frameCount * mFrameSize);
3553 break;
3554 }
3555 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3556 frameCount -= buffer.frameCount;
3557 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003558 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003559 }
3560 sleepTime = 0;
3561 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003562 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003563
3564 // apply volume
3565
3566 // Do not apply volume on compressed audio
3567 if (!audio_is_linear_pcm(mFormat)) {
3568 return;
3569 }
3570
3571 // convert to signed 16 bit before volume calculation
3572 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3573 size_t count = mFrameCount * mChannelCount;
3574 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3575 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003576 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003577 *dst-- = (int16_t)(*src--^0x80) << 8;
3578 }
3579 }
3580
3581 frameCount = mFrameCount;
3582 int16_t *out = mMixBuffer;
3583 if (rampVolume) {
3584 if (mChannelCount == 1) {
3585 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3586 int32_t vlInc = d / (int32_t)frameCount;
3587 int32_t vl = ((int32_t)mLeftVolShort << 16);
3588 do {
3589 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3590 out++;
3591 vl += vlInc;
3592 } while (--frameCount);
3593
3594 } else {
3595 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3596 int32_t vlInc = d / (int32_t)frameCount;
3597 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3598 int32_t vrInc = d / (int32_t)frameCount;
3599 int32_t vl = ((int32_t)mLeftVolShort << 16);
3600 int32_t vr = ((int32_t)mRightVolShort << 16);
3601 do {
3602 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3603 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3604 out += 2;
3605 vl += vlInc;
3606 vr += vrInc;
3607 } while (--frameCount);
3608 }
3609 } else {
3610 if (mChannelCount == 1) {
3611 do {
3612 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3613 out++;
3614 } while (--frameCount);
3615 } else {
3616 do {
3617 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3618 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3619 out += 2;
3620 } while (--frameCount);
3621 }
3622 }
3623
3624 // convert back to unsigned 8 bit after volume calculation
3625 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3626 size_t count = mFrameCount * mChannelCount;
3627 int16_t *src = mMixBuffer;
3628 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003629 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003630 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3631 }
3632 }
3633
3634 mLeftVolShort = leftVol;
3635 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003636}
3637
3638void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3639{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003640 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003641 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003642 sleepTime = activeSleepTime;
3643 } else {
3644 sleepTime = idleSleepTime;
3645 }
3646 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003647 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003648 sleepTime = 0;
3649 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650}
3651
3652// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003653int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654{
3655 return 0;
3656}
3657
3658// deleteTrackName_l() must be called with ThreadBase::mLock held
3659void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3660{
3661}
3662
3663// checkForNewParameters_l() must be called with ThreadBase::mLock held
3664bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3665{
3666 bool reconfig = false;
3667
3668 while (!mNewParameters.isEmpty()) {
3669 status_t status = NO_ERROR;
3670 String8 keyValuePair = mNewParameters[0];
3671 AudioParameter param = AudioParameter(keyValuePair);
3672 int value;
3673
3674 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3675 // do not accept frame count changes if tracks are open as the track buffer
3676 // size depends on frame count and correct behavior would not be garantied
3677 // if frame count is changed after track creation
3678 if (!mTracks.isEmpty()) {
3679 status = INVALID_OPERATION;
3680 } else {
3681 reconfig = true;
3682 }
3683 }
3684 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003685 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003686 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003688 mOutput->stream->common.standby(&mOutput->stream->common);
3689 mStandby = true;
3690 mBytesWritten = 0;
3691 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003692 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 }
3694 if (status == NO_ERROR && reconfig) {
3695 readOutputParameters();
3696 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3697 }
3698 }
3699
3700 mNewParameters.removeAt(0);
3701
3702 mParamStatus = status;
3703 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003704 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3705 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003706 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707 }
3708 return reconfig;
3709}
3710
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003711uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712{
3713 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003714 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003715 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 } else {
3717 time = 10000;
3718 }
3719 return time;
3720}
3721
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003722uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723{
3724 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003725 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003726 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727 } else {
3728 time = 10000;
3729 }
3730 return time;
3731}
3732
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003733uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003734{
3735 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003736 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003737 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3738 } else {
3739 time = 10000;
3740 }
3741 return time;
3742}
3743
Glenn Kasten66fcab92012-02-24 14:59:21 -08003744void AudioFlinger::DirectOutputThread::cacheParameters_l()
3745{
3746 PlaybackThread::cacheParameters_l();
3747
3748 // use shorter standby delay as on normal output to release
3749 // hardware resources as soon as possible
3750 standbyDelay = microseconds(activeSleepTime*2);
3751}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003752
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753// ----------------------------------------------------------------------------
3754
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003755AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003756 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003757 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3758 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760 addOutputTrack(mainThread);
3761}
3762
3763AudioFlinger::DuplicatingThread::~DuplicatingThread()
3764{
3765 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3766 mOutputTracks[i]->destroy();
3767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768}
3769
Glenn Kasten000f0e32012-03-01 17:10:56 -08003770void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003772 // mix buffers...
3773 if (outputsReady(outputTracks)) {
3774 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3775 } else {
3776 memset(mMixBuffer, 0, mixBufferSize);
3777 }
3778 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003779 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003780}
3781
3782void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3783{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003784 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003785 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003786 sleepTime = activeSleepTime;
3787 } else {
3788 sleepTime = idleSleepTime;
3789 }
3790 } else if (mBytesWritten != 0) {
3791 // flush remaining overflow buffers in output tracks
3792 for (size_t i = 0; i < outputTracks.size(); i++) {
3793 if (outputTracks[i]->isActive()) {
3794 sleepTime = 0;
3795 writeFrames = 0;
3796 memset(mMixBuffer, 0, mixBufferSize);
3797 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003798 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003799 }
3800 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003801}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802
Glenn Kasten000f0e32012-03-01 17:10:56 -08003803void AudioFlinger::DuplicatingThread::threadLoop_write()
3804{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003805 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003806 for (size_t i = 0; i < outputTracks.size(); i++) {
3807 outputTracks[i]->write(mMixBuffer, writeFrames);
3808 }
3809 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003810}
Glenn Kasten688a6402012-02-29 07:57:06 -08003811
Glenn Kasten000f0e32012-03-01 17:10:56 -08003812void AudioFlinger::DuplicatingThread::threadLoop_standby()
3813{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003814 // DuplicatingThread implements standby by stopping all tracks
3815 for (size_t i = 0; i < outputTracks.size(); i++) {
3816 outputTracks[i]->stop();
3817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818}
3819
Glenn Kastenfa26a852012-03-06 11:28:04 -08003820void AudioFlinger::DuplicatingThread::saveOutputTracks()
3821{
3822 outputTracks = mOutputTracks;
3823}
3824
3825void AudioFlinger::DuplicatingThread::clearOutputTracks()
3826{
3827 outputTracks.clear();
3828}
3829
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3831{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003832 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003833 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003834 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003835 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836 this,
3837 mSampleRate,
3838 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003839 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840 frameCount);
3841 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003842 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003844 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003845 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003846 }
3847}
3848
3849void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3850{
3851 Mutex::Autolock _l(mLock);
3852 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003853 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003854 mOutputTracks[i]->destroy();
3855 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003856 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857 return;
3858 }
3859 }
Steve Block3856b092011-10-20 11:56:00 +01003860 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861}
3862
Glenn Kasten438b0362012-03-06 11:24:48 -08003863// caller must hold mLock
3864void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865{
3866 mWaitTimeMs = UINT_MAX;
3867 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3868 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003869 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3871 if (waitTimeMs < mWaitTimeMs) {
3872 mWaitTimeMs = waitTimeMs;
3873 }
3874 }
3875 }
3876}
3877
3878
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003879bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880{
3881 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003882 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003883 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003884 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 return false;
3886 }
3887 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3888 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003889 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003890 return false;
3891 }
3892 }
3893 return true;
3894}
3895
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003896uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897{
3898 return (mWaitTimeMs * 1000) / 2;
3899}
3900
Glenn Kasten66fcab92012-02-24 14:59:21 -08003901void AudioFlinger::DuplicatingThread::cacheParameters_l()
3902{
3903 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3904 updateWaitTime_l();
3905
3906 MixerThread::cacheParameters_l();
3907}
3908
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909// ----------------------------------------------------------------------------
3910
3911// TrackBase constructor must be called with AudioFlinger::mLock held
3912AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003913 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 const sp<Client>& client,
3915 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003916 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003917 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003919 const sp<IMemory>& sharedBuffer,
3920 int sessionId)
3921 : RefBase(),
3922 mThread(thread),
3923 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003924 mCblk(NULL),
3925 // mBuffer
3926 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927 mFrameCount(0),
3928 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003929 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003931 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003933 // mChannelCount
3934 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935{
Steve Block3856b092011-10-20 11:56:00 +01003936 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937
Steve Blockb8a80522011-12-20 16:23:08 +00003938 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003939 size_t size = sizeof(audio_track_cblk_t);
3940 uint8_t channelCount = popcount(channelMask);
3941 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3942 if (sharedBuffer == 0) {
3943 size += bufferSize;
3944 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003946 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947 mCblkMemory = client->heap()->allocate(size);
3948 if (mCblkMemory != 0) {
3949 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003950 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 new(mCblk) audio_track_cblk_t();
3952 // clear all buffers
3953 mCblk->frameCount = frameCount;
3954 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003955// uncomment the following lines to quickly test 32-bit wraparound
3956// mCblk->user = 0xffff0000;
3957// mCblk->server = 0xffff0000;
3958// mCblk->userBase = 0xffff0000;
3959// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003960 mChannelCount = channelCount;
3961 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962 if (sharedBuffer == 0) {
3963 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3964 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3965 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003966 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003967 mCblk->flags = CBLK_UNDERRUN_ON;
3968 } else {
3969 mBuffer = sharedBuffer->pointer();
3970 }
3971 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3972 }
3973 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003974 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003975 client->heap()->dump("AudioTrack");
3976 return;
3977 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003978 } else {
3979 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003980 // construct the shared structure in-place.
3981 new(mCblk) audio_track_cblk_t();
3982 // clear all buffers
3983 mCblk->frameCount = frameCount;
3984 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003985// uncomment the following lines to quickly test 32-bit wraparound
3986// mCblk->user = 0xffff0000;
3987// mCblk->server = 0xffff0000;
3988// mCblk->userBase = 0xffff0000;
3989// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003990 mChannelCount = channelCount;
3991 mChannelMask = channelMask;
3992 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3993 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3994 // Force underrun condition to avoid false underrun callback until first data is
3995 // written to buffer (other flags are cleared)
3996 mCblk->flags = CBLK_UNDERRUN_ON;
3997 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003998 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999}
4000
4001AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4002{
Glenn Kastena0d68332012-01-27 16:47:15 -08004003 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004004 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004006 } else {
4007 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 }
4009 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004010 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004011 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004012 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004014 // If the client's reference count drops to zero, the associated destructor
4015 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4016 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 mClient.clear();
4018 }
4019}
4020
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004021// AudioBufferProvider interface
4022// getNextBuffer() = 0;
4023// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4025{
Glenn Kastene0feee32011-12-13 11:53:26 -08004026 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004028 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004029 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030 buffer->frameCount = 0;
4031}
4032
4033bool AudioFlinger::ThreadBase::TrackBase::step() {
4034 bool result;
4035 audio_track_cblk_t* cblk = this->cblk();
4036
4037 result = cblk->stepServer(mFrameCount);
4038 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004039 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004040 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041 }
4042 return result;
4043}
4044
4045void AudioFlinger::ThreadBase::TrackBase::reset() {
4046 audio_track_cblk_t* cblk = this->cblk();
4047
4048 cblk->user = 0;
4049 cblk->server = 0;
4050 cblk->userBase = 0;
4051 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004052 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004053 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054}
4055
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4057 return (int)mCblk->sampleRate;
4058}
4059
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4061 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004062 size_t frameSize = cblk->frameSize;
4063 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4064 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065
4066 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004067 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4068 "TrackBase::getBuffer buffer out of range:\n"
4069 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4070 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004072 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073
4074 return bufferStart;
4075}
4076
Eric Laurenta011e352012-03-29 15:51:43 -07004077status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4078{
4079 mSyncEvents.add(event);
4080 return NO_ERROR;
4081}
4082
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083// ----------------------------------------------------------------------------
4084
4085// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4086AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004087 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004089 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004091 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004092 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 int frameCount,
4094 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004095 int sessionId,
4096 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004097 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004098 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004099 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004100 // mRetryCount initialized later when needed
4101 mSharedBuffer(sharedBuffer),
4102 mStreamType(streamType),
4103 mName(-1), // see note below
4104 mMainBuffer(thread->mixBuffer()),
4105 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004106 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004107 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004108 mFlags(flags),
4109 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004110 mObservedUnderruns(0),
4111 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004112 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113{
4114 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4116 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004117 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004118 if (flags & IAudioFlinger::TRACK_FAST) {
4119 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4120 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4121 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4122 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004123 // FIXME This is too eager. We allocate a fast track index before the
4124 // fast track becomes active. Since fast tracks are a scarce resource,
4125 // this means we are potentially denying other more important fast tracks from
4126 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004127 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004128 // Read the initial underruns because this field is never cleared by the fast mixer
4129 mObservedUnderruns = thread->getFastTrackUnderruns(i) & ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07004130 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004131 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004132 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004133 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004134 if (mName < 0) {
4135 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004136 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4137 // then we leak a fast track index. Should swap these two sections, or better yet
4138 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004141 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142}
4143
4144AudioFlinger::PlaybackThread::Track::~Track()
4145{
Steve Block3856b092011-10-20 11:56:00 +01004146 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 sp<ThreadBase> thread = mThread.promote();
4148 if (thread != 0) {
4149 Mutex::Autolock _l(thread->mLock);
4150 mState = TERMINATED;
4151 }
4152}
4153
4154void AudioFlinger::PlaybackThread::Track::destroy()
4155{
4156 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4157 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004158 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 // we must acquire a strong reference on this Track before locking mLock
4160 // here so that the destructor is called only when exiting this function.
4161 // On the other hand, as long as Track::destroy() is only called by
4162 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4163 // this Track with its member mTrack.
4164 sp<Track> keep(this);
4165 { // scope for mLock
4166 sp<ThreadBase> thread = mThread.promote();
4167 if (thread != 0) {
4168 if (!isOutputTrack()) {
4169 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004170 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004171
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004172#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004173 // to track the speaker usage
4174 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004175#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 }
4177 AudioSystem::releaseOutput(thread->id());
4178 }
4179 Mutex::Autolock _l(thread->mLock);
4180 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4181 playbackThread->destroyTrack_l(this);
4182 }
4183 }
4184}
4185
Glenn Kasten288ed212012-04-25 17:52:27 -07004186/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4187{
Glenn Kastene213c862012-04-25 13:46:15 -07004188 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4189 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004190}
4191
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4193{
Glenn Kasten83d86532012-01-17 14:39:34 -08004194 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004195 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004196 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004197 } else {
4198 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4199 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004200 track_state state = mState;
4201 char stateChar;
4202 switch (state) {
4203 case IDLE:
4204 stateChar = 'I';
4205 break;
4206 case TERMINATED:
4207 stateChar = 'T';
4208 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004209 case STOPPING_1:
4210 stateChar = 's';
4211 break;
4212 case STOPPING_2:
4213 stateChar = '5';
4214 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004215 case STOPPED:
4216 stateChar = 'S';
4217 break;
4218 case RESUMING:
4219 stateChar = 'R';
4220 break;
4221 case ACTIVE:
4222 stateChar = 'A';
4223 break;
4224 case PAUSING:
4225 stateChar = 'p';
4226 break;
4227 case PAUSED:
4228 stateChar = 'P';
4229 break;
4230 default:
4231 stateChar = '?';
4232 break;
4233 }
4234 bool nowInUnderrun = mObservedUnderruns & 1;
Glenn Kastene213c862012-04-25 13:46:15 -07004235 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4236 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004237 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238 mStreamType,
4239 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004240 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 mSessionId,
4242 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004243 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004244 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245 mMute,
4246 mFillingUpStatus,
4247 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004248 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4249 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 mCblk->server,
4251 mCblk->user,
4252 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004253 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004254 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004255 mUnderrunCount,
4256 nowInUnderrun ? '*' : ' ');
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257}
4258
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004259// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004260status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004261 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004263 audio_track_cblk_t* cblk = this->cblk();
4264 uint32_t framesReady;
4265 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004267 // Check if last stepServer failed, try to step now
4268 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004269 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4270 // Since the fast mixer is higher priority than client callback thread,
4271 // it does not result in priority inversion for client.
4272 // But a non-blocking solution would be preferable to avoid
4273 // fast mixer being unable to tryLock(), and
4274 // to avoid the extra context switches if the client wakes up,
4275 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004276 if (!step()) goto getNextBuffer_exit;
4277 ALOGV("stepServer recovered");
4278 mStepServerFailed = false;
4279 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280
Glenn Kasten288ed212012-04-25 17:52:27 -07004281 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004282 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004284 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 uint32_t s = cblk->server;
4286 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4287
4288 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4289 if (framesReq > framesReady) {
4290 framesReq = framesReady;
4291 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004292 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 framesReq = bufferEnd - s;
4294 }
4295
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004296 buffer->raw = getBuffer(s, framesReq);
4297 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004299 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302
4303getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004304 buffer->raw = NULL;
4305 buffer->frameCount = 0;
4306 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4307 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308}
4309
Glenn Kasten288ed212012-04-25 17:52:27 -07004310// Note that framesReady() takes a mutex on the control block using tryLock().
4311// This could result in priority inversion if framesReady() is called by the normal mixer,
4312// as the normal mixer thread runs at lower
4313// priority than the client's callback thread: there is a short window within framesReady()
4314// during which the normal mixer could be preempted, and the client callback would block.
4315// Another problem can occur if framesReady() is called by the fast mixer:
4316// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4317// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4318size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004319 return mCblk->framesReady();
4320}
4321
Glenn Kasten288ed212012-04-25 17:52:27 -07004322// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004324 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325
John Grossman4ff14ba2012-02-08 16:37:41 -08004326 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4328 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004329 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 return true;
4331 }
4332 return false;
4333}
4334
Glenn Kasten3acbd052012-02-28 10:39:56 -08004335status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004336 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337{
4338 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004339 ALOGV("start(%d), calling pid %d session %d",
4340 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004341
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 sp<ThreadBase> thread = mThread.promote();
4343 if (thread != 0) {
4344 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004345 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 // here the track could be either new, or restarted
4347 // in both cases "unstop" the track
4348 if (mState == PAUSED) {
4349 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004350 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 } else {
4352 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004353 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004354 }
4355
4356 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4357 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004358 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004360
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004361#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004362 // to track the speaker usage
4363 if (status == NO_ERROR) {
4364 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4365 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004366#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004367 }
4368 if (status == NO_ERROR) {
4369 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4370 playbackThread->addTrack_l(this);
4371 } else {
4372 mState = state;
4373 }
4374 } else {
4375 status = BAD_VALUE;
4376 }
4377 return status;
4378}
4379
4380void AudioFlinger::PlaybackThread::Track::stop()
4381{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004382 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383 sp<ThreadBase> thread = mThread.promote();
4384 if (thread != 0) {
4385 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004386 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004387 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 // If the track is not active (PAUSED and buffers full), flush buffers
4389 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4390 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4391 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004392 mState = STOPPED;
4393 } else if (!isFastTrack()) {
4394 mState = STOPPED;
4395 } else {
4396 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4397 // and then to STOPPED and reset() when presentation is complete
4398 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004400 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004401 }
4402 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4403 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004404 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004406
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004407#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004408 // to track the speaker usage
4409 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004410#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411 }
4412 }
4413}
4414
4415void AudioFlinger::PlaybackThread::Track::pause()
4416{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004417 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004418 sp<ThreadBase> thread = mThread.promote();
4419 if (thread != 0) {
4420 Mutex::Autolock _l(thread->mLock);
4421 if (mState == ACTIVE || mState == RESUMING) {
4422 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004423 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424 if (!isOutputTrack()) {
4425 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004426 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004428
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004429#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004430 // to track the speaker usage
4431 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004432#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 }
4434 }
4435 }
4436}
4437
4438void AudioFlinger::PlaybackThread::Track::flush()
4439{
Steve Block3856b092011-10-20 11:56:00 +01004440 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 sp<ThreadBase> thread = mThread.promote();
4442 if (thread != 0) {
4443 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004444 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4445 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446 return;
4447 }
4448 // No point remaining in PAUSED state after a flush => go to
4449 // STOPPED state
4450 mState = STOPPED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004451 // do not reset the track if it is still in the process of being stopped or paused.
4452 // this will be done by prepareTracks_l() when the track is stopped.
Glenn Kastend08f48c2012-05-01 18:14:02 -07004453 // prepareTracks_l() will see mState == STOPPED, then
4454 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004455 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4456 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4457 reset();
4458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 }
4460}
4461
4462void AudioFlinger::PlaybackThread::Track::reset()
4463{
4464 // Do not reset twice to avoid discarding data written just after a flush and before
4465 // the audioflinger thread detects the track is stopped.
4466 if (!mResetDone) {
4467 TrackBase::reset();
4468 // Force underrun condition to avoid false underrun callback until first data is
4469 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004470 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4471 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 mFillingUpStatus = FS_FILLING;
4473 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004474 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 }
4476}
4477
4478void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4479{
4480 mMute = muted;
4481}
4482
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4484{
4485 status_t status = DEAD_OBJECT;
4486 sp<ThreadBase> thread = mThread.promote();
4487 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004488 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4489 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 }
4491 return status;
4492}
4493
4494void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4495{
4496 mAuxEffectId = EffectId;
4497 mAuxBuffer = buffer;
4498}
4499
Eric Laurenta011e352012-03-29 15:51:43 -07004500bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4501 size_t audioHalFrames)
4502{
4503 // a track is considered presented when the total number of frames written to audio HAL
4504 // corresponds to the number of frames written when presentationComplete() is called for the
4505 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4506 if (mPresentationCompleteFrames == 0) {
4507 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4508 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4509 mPresentationCompleteFrames, audioHalFrames);
4510 }
4511 if (framesWritten >= mPresentationCompleteFrames) {
4512 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4513 mSessionId, framesWritten);
4514 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4515 mPresentationCompleteFrames = 0;
4516 return true;
4517 }
4518 return false;
4519}
4520
4521void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4522{
4523 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4524 if (mSyncEvents[i]->type() == type) {
4525 mSyncEvents[i]->trigger();
4526 mSyncEvents.removeAt(i);
4527 i--;
4528 }
4529 }
4530}
4531
Glenn Kasten58912562012-04-03 10:45:00 -07004532// implement VolumeBufferProvider interface
4533
4534uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4535{
4536 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4537 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4538 uint32_t vlr = mCblk->getVolumeLR();
4539 uint32_t vl = vlr & 0xFFFF;
4540 uint32_t vr = vlr >> 16;
4541 // track volumes come from shared memory, so can't be trusted and must be clamped
4542 if (vl > MAX_GAIN_INT) {
4543 vl = MAX_GAIN_INT;
4544 }
4545 if (vr > MAX_GAIN_INT) {
4546 vr = MAX_GAIN_INT;
4547 }
4548 // now apply the cached master volume and stream type volume;
4549 // this is trusted but lacks any synchronization or barrier so may be stale
4550 float v = mCachedVolume;
4551 vl *= v;
4552 vr *= v;
4553 // re-combine into U4.16
4554 vlr = (vr << 16) | (vl & 0xFFFF);
4555 // FIXME look at mute, pause, and stop flags
4556 return vlr;
4557}
Eric Laurenta011e352012-03-29 15:51:43 -07004558
John Grossman4ff14ba2012-02-08 16:37:41 -08004559// timed audio tracks
4560
4561sp<AudioFlinger::PlaybackThread::TimedTrack>
4562AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004563 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004564 const sp<Client>& client,
4565 audio_stream_type_t streamType,
4566 uint32_t sampleRate,
4567 audio_format_t format,
4568 uint32_t channelMask,
4569 int frameCount,
4570 const sp<IMemory>& sharedBuffer,
4571 int sessionId) {
4572 if (!client->reserveTimedTrack())
4573 return NULL;
4574
Glenn Kastena0356762012-03-19 10:38:51 -07004575 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004576 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4577 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004578}
4579
4580AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004581 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004582 const sp<Client>& client,
4583 audio_stream_type_t streamType,
4584 uint32_t sampleRate,
4585 audio_format_t format,
4586 uint32_t channelMask,
4587 int frameCount,
4588 const sp<IMemory>& sharedBuffer,
4589 int sessionId)
4590 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004591 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004592 mQueueHeadInFlight(false),
4593 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004594 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004595 mTimedSilenceBuffer(NULL),
4596 mTimedSilenceBufferSize(0),
4597 mTimedAudioOutputOnTime(false),
4598 mMediaTimeTransformValid(false)
4599{
4600 LocalClock lc;
4601 mLocalTimeFreq = lc.getLocalFreq();
4602
4603 mLocalTimeToSampleTransform.a_zero = 0;
4604 mLocalTimeToSampleTransform.b_zero = 0;
4605 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4606 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4607 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4608 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004609
4610 mMediaTimeToSampleTransform.a_zero = 0;
4611 mMediaTimeToSampleTransform.b_zero = 0;
4612 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4613 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4614 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4615 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004616}
4617
4618AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4619 mClient->releaseTimedTrack();
4620 delete [] mTimedSilenceBuffer;
4621}
4622
4623status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4624 size_t size, sp<IMemory>* buffer) {
4625
4626 Mutex::Autolock _l(mTimedBufferQueueLock);
4627
4628 trimTimedBufferQueue_l();
4629
4630 // lazily initialize the shared memory heap for timed buffers
4631 if (mTimedMemoryDealer == NULL) {
4632 const int kTimedBufferHeapSize = 512 << 10;
4633
4634 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4635 "AudioFlingerTimed");
4636 if (mTimedMemoryDealer == NULL)
4637 return NO_MEMORY;
4638 }
4639
4640 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4641 if (newBuffer == NULL) {
4642 newBuffer = mTimedMemoryDealer->allocate(size);
4643 if (newBuffer == NULL)
4644 return NO_MEMORY;
4645 }
4646
4647 *buffer = newBuffer;
4648 return NO_ERROR;
4649}
4650
4651// caller must hold mTimedBufferQueueLock
4652void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4653 int64_t mediaTimeNow;
4654 {
4655 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4656 if (!mMediaTimeTransformValid)
4657 return;
4658
4659 int64_t targetTimeNow;
4660 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4661 ? mCCHelper.getCommonTime(&targetTimeNow)
4662 : mCCHelper.getLocalTime(&targetTimeNow);
4663
4664 if (OK != res)
4665 return;
4666
4667 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4668 &mediaTimeNow)) {
4669 return;
4670 }
4671 }
4672
John Grossman1c345192012-03-27 14:00:17 -07004673 size_t trimEnd;
4674 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004675 int64_t bufEnd;
4676
John Grossmanc95cfbb2012-04-12 11:53:11 -07004677 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4678 // We have a next buffer. Just use its PTS as the PTS of the frame
4679 // following the last frame in this buffer. If the stream is sparse
4680 // (ie, there are deliberate gaps left in the stream which should be
4681 // filled with silence by the TimedAudioTrack), then this can result
4682 // in one extra buffer being left un-trimmed when it could have
4683 // been. In general, this is not typical, and we would rather
4684 // optimized away the TS calculation below for the more common case
4685 // where PTSes are contiguous.
4686 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4687 } else {
4688 // We have no next buffer. Compute the PTS of the frame following
4689 // the last frame in this buffer by computing the duration of of
4690 // this frame in media time units and adding it to the PTS of the
4691 // buffer.
4692 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4693 / mCblk->frameSize;
4694
4695 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4696 &bufEnd)) {
4697 ALOGE("Failed to convert frame count of %lld to media time"
4698 " duration" " (scale factor %d/%u) in %s",
4699 frameCount,
4700 mMediaTimeToSampleTransform.a_to_b_numer,
4701 mMediaTimeToSampleTransform.a_to_b_denom,
4702 __PRETTY_FUNCTION__);
4703 break;
4704 }
4705 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004706 }
John Grossman9fbdee12012-03-26 17:51:46 -07004707
4708 if (bufEnd > mediaTimeNow)
4709 break;
4710
4711 // Is the buffer we want to use in the middle of a mix operation right
4712 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4713 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004714 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004715 mTrimQueueHeadOnRelease = true;
4716 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004717 }
4718
John Grossman9fbdee12012-03-26 17:51:46 -07004719 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004720 if (trimStart < trimEnd) {
4721 // Update the bookkeeping for framesReady()
4722 for (size_t i = trimStart; i < trimEnd; ++i) {
4723 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4724 }
4725
4726 // Now actually remove the buffers from the queue.
4727 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004728 }
4729}
4730
John Grossman1c345192012-03-27 14:00:17 -07004731void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4732 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004733 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4734 "%s called (reason \"%s\"), but timed buffer queue has no"
4735 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004736
4737 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4738 mTimedBufferQueue.removeAt(0);
4739}
4740
4741void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4742 const TimedBuffer& buf,
4743 const char* logTag) {
4744 uint32_t bufBytes = buf.buffer()->size();
4745 uint32_t consumedAlready = buf.position();
4746
Eric Laurentb388e532012-04-14 13:32:48 -07004747 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004748 "Bad bookkeeping while updating frames pending. Timed buffer is"
4749 " only %u bytes long, but claims to have consumed %u"
4750 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004751 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004752
4753 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004754 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4755 "Bad bookkeeping while updating frames pending. Should have at"
4756 " least %u queued frames, but we think we have only %u. (update"
4757 " reason: \"%s\")",
4758 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004759
4760 mFramesPendingInQueue -= bufFrames;
4761}
4762
John Grossman4ff14ba2012-02-08 16:37:41 -08004763status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4764 const sp<IMemory>& buffer, int64_t pts) {
4765
4766 {
4767 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4768 if (!mMediaTimeTransformValid)
4769 return INVALID_OPERATION;
4770 }
4771
4772 Mutex::Autolock _l(mTimedBufferQueueLock);
4773
John Grossman1c345192012-03-27 14:00:17 -07004774 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4775 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004776 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4777
4778 return NO_ERROR;
4779}
4780
4781status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4782 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4783
John Grossman1c345192012-03-27 14:00:17 -07004784 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4785 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4786 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004787
4788 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4789 target == TimedAudioTrack::COMMON_TIME)) {
4790 return BAD_VALUE;
4791 }
4792
4793 Mutex::Autolock lock(mMediaTimeTransformLock);
4794 mMediaTimeTransform = xform;
4795 mMediaTimeTransformTarget = target;
4796 mMediaTimeTransformValid = true;
4797
4798 return NO_ERROR;
4799}
4800
4801#define min(a, b) ((a) < (b) ? (a) : (b))
4802
4803// implementation of getNextBuffer for tracks whose buffers have timestamps
4804status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4805 AudioBufferProvider::Buffer* buffer, int64_t pts)
4806{
4807 if (pts == AudioBufferProvider::kInvalidPTS) {
4808 buffer->raw = 0;
4809 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004810 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004811 return INVALID_OPERATION;
4812 }
4813
John Grossman4ff14ba2012-02-08 16:37:41 -08004814 Mutex::Autolock _l(mTimedBufferQueueLock);
4815
John Grossman9fbdee12012-03-26 17:51:46 -07004816 ALOG_ASSERT(!mQueueHeadInFlight,
4817 "getNextBuffer called without releaseBuffer!");
4818
John Grossman4ff14ba2012-02-08 16:37:41 -08004819 while (true) {
4820
4821 // if we have no timed buffers, then fail
4822 if (mTimedBufferQueue.isEmpty()) {
4823 buffer->raw = 0;
4824 buffer->frameCount = 0;
4825 return NOT_ENOUGH_DATA;
4826 }
4827
4828 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4829
4830 // calculate the PTS of the head of the timed buffer queue expressed in
4831 // local time
4832 int64_t headLocalPTS;
4833 {
4834 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4835
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004836 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004837
4838 if (mMediaTimeTransform.a_to_b_denom == 0) {
4839 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004840 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004841 return NO_ERROR;
4842 }
4843
4844 int64_t transformedPTS;
4845 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4846 &transformedPTS)) {
4847 // the transform failed. this shouldn't happen, but if it does
4848 // then just drop this buffer
4849 ALOGW("timedGetNextBuffer transform failed");
4850 buffer->raw = 0;
4851 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004852 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004853 return NO_ERROR;
4854 }
4855
4856 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4857 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4858 &headLocalPTS)) {
4859 buffer->raw = 0;
4860 buffer->frameCount = 0;
4861 return INVALID_OPERATION;
4862 }
4863 } else {
4864 headLocalPTS = transformedPTS;
4865 }
4866 }
4867
4868 // adjust the head buffer's PTS to reflect the portion of the head buffer
4869 // that has already been consumed
4870 int64_t effectivePTS = headLocalPTS +
4871 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4872
4873 // Calculate the delta in samples between the head of the input buffer
4874 // queue and the start of the next output buffer that will be written.
4875 // If the transformation fails because of over or underflow, it means
4876 // that the sample's position in the output stream is so far out of
4877 // whack that it should just be dropped.
4878 int64_t sampleDelta;
4879 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4880 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004881 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4882 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004883 continue;
4884 }
4885 if (!mLocalTimeToSampleTransform.doForwardTransform(
4886 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004887 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004888 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004889 continue;
4890 }
4891
John Grossman1c345192012-03-27 14:00:17 -07004892 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4893 " sampleDelta=[%d.%08x]",
4894 head.pts(), head.position(), pts,
4895 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4896 + (sampleDelta >> 32)),
4897 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004898
4899 // if the delta between the ideal placement for the next input sample and
4900 // the current output position is within this threshold, then we will
4901 // concatenate the next input samples to the previous output
4902 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004903 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004904
4905 // if this is the first buffer of audio that we're emitting from this track
4906 // then it should be almost exactly on time.
4907 const int64_t kSampleStartupThreshold = 1LL << 32;
4908
4909 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004910 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004911 // the next input is close enough to being on time, so concatenate it
4912 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004913 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004914
John Grossman1c345192012-03-27 14:00:17 -07004915 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4916 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004917 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004918 }
4919
4920 // Looks like our output is not on time. Reset our on timed status.
4921 // Next time we mix samples from our input queue, then should be within
4922 // the StartupThreshold.
4923 mTimedAudioOutputOnTime = false;
4924 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004925 // the gap between the current output position and the proper start of
4926 // the next input sample is too big, so fill it with silence
4927 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4928
John Grossman9fbdee12012-03-26 17:51:46 -07004929 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004930 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4931 return NO_ERROR;
4932 } else {
4933 // the next input sample is late
4934 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4935 size_t onTimeSamplePosition =
4936 head.position() + lateFrames * mCblk->frameSize;
4937
4938 if (onTimeSamplePosition > head.buffer()->size()) {
4939 // all the remaining samples in the head are too late, so
4940 // drop it and move on
4941 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004942 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004943 continue;
4944 } else {
4945 // skip over the late samples
4946 head.setPosition(onTimeSamplePosition);
4947
4948 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004949 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004950
4951 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4952 return NO_ERROR;
4953 }
4954 }
4955 }
4956}
4957
4958// Yield samples from the timed buffer queue head up to the given output
4959// buffer's capacity.
4960//
4961// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004962void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004963 AudioBufferProvider::Buffer* buffer) {
4964
4965 const TimedBuffer& head = mTimedBufferQueue[0];
4966
4967 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4968 head.position());
4969
4970 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4971 mCblk->frameSize);
4972 size_t framesRequested = buffer->frameCount;
4973 buffer->frameCount = min(framesLeftInHead, framesRequested);
4974
John Grossman9fbdee12012-03-26 17:51:46 -07004975 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004976 mTimedAudioOutputOnTime = true;
4977}
4978
4979// Yield samples of silence up to the given output buffer's capacity
4980//
4981// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004982void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004983 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4984
4985 // lazily allocate a buffer filled with silence
4986 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4987 delete [] mTimedSilenceBuffer;
4988 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4989 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4990 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4991 }
4992
4993 buffer->raw = mTimedSilenceBuffer;
4994 size_t framesRequested = buffer->frameCount;
4995 buffer->frameCount = min(numFrames, framesRequested);
4996
4997 mTimedAudioOutputOnTime = false;
4998}
4999
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005000// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005001void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5002 AudioBufferProvider::Buffer* buffer) {
5003
5004 Mutex::Autolock _l(mTimedBufferQueueLock);
5005
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005006 // If the buffer which was just released is part of the buffer at the head
5007 // of the queue, be sure to update the amt of the buffer which has been
5008 // consumed. If the buffer being returned is not part of the head of the
5009 // queue, its either because the buffer is part of the silence buffer, or
5010 // because the head of the timed queue was trimmed after the mixer called
5011 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005012 if (buffer->raw == mTimedSilenceBuffer) {
5013 ALOG_ASSERT(!mQueueHeadInFlight,
5014 "Queue head in flight during release of silence buffer!");
5015 goto done;
5016 }
5017
5018 ALOG_ASSERT(mQueueHeadInFlight,
5019 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5020 " head in flight.");
5021
5022 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005023 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005024
5025 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005026 void* end = reinterpret_cast<void*>(
5027 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5028 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005029
John Grossman9fbdee12012-03-26 17:51:46 -07005030 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5031 "released buffer not within the head of the timed buffer"
5032 " queue; qHead = [%p, %p], released buffer = %p",
5033 start, end, buffer->raw);
5034
5035 head.setPosition(head.position() +
5036 (buffer->frameCount * mCblk->frameSize));
5037 mQueueHeadInFlight = false;
5038
John Grossman1c345192012-03-27 14:00:17 -07005039 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5040 "Bad bookkeeping during releaseBuffer! Should have at"
5041 " least %u queued frames, but we think we have only %u",
5042 buffer->frameCount, mFramesPendingInQueue);
5043
5044 mFramesPendingInQueue -= buffer->frameCount;
5045
John Grossman9fbdee12012-03-26 17:51:46 -07005046 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5047 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005048 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005049 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005050 }
John Grossman9fbdee12012-03-26 17:51:46 -07005051 } else {
5052 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5053 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005054 }
5055
John Grossman9fbdee12012-03-26 17:51:46 -07005056done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005057 buffer->raw = 0;
5058 buffer->frameCount = 0;
5059}
5060
Glenn Kasten288ed212012-04-25 17:52:27 -07005061size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005062 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005063 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005064}
5065
5066AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5067 : mPTS(0), mPosition(0) {}
5068
5069AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5070 const sp<IMemory>& buffer, int64_t pts)
5071 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5072
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073// ----------------------------------------------------------------------------
5074
5075// RecordTrack constructor must be called with AudioFlinger::mLock held
5076AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005077 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078 const sp<Client>& client,
5079 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005080 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005081 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 int sessionId)
5084 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005085 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 mOverflow(false)
5087{
5088 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005089 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5090 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5091 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5092 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5093 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5094 } else {
5095 mCblk->frameSize = sizeof(int8_t);
5096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097 }
5098}
5099
5100AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5101{
5102 sp<ThreadBase> thread = mThread.promote();
5103 if (thread != 0) {
5104 AudioSystem::releaseInput(thread->id());
5105 }
5106}
5107
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005108// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005109status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110{
5111 audio_track_cblk_t* cblk = this->cblk();
5112 uint32_t framesAvail;
5113 uint32_t framesReq = buffer->frameCount;
5114
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005115 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005116 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005118 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005119 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 }
5121
5122 framesAvail = cblk->framesAvailable_l();
5123
Glenn Kastenf6b16782011-12-15 09:51:17 -08005124 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 uint32_t s = cblk->server;
5126 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5127
5128 if (framesReq > framesAvail) {
5129 framesReq = framesAvail;
5130 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005131 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005132 framesReq = bufferEnd - s;
5133 }
5134
5135 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005136 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005137
5138 buffer->frameCount = framesReq;
5139 return NO_ERROR;
5140 }
5141
5142getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005143 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005144 buffer->frameCount = 0;
5145 return NOT_ENOUGH_DATA;
5146}
5147
Glenn Kasten3acbd052012-02-28 10:39:56 -08005148status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005149 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005150{
5151 sp<ThreadBase> thread = mThread.promote();
5152 if (thread != 0) {
5153 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005154 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 } else {
5156 return BAD_VALUE;
5157 }
5158}
5159
5160void AudioFlinger::RecordThread::RecordTrack::stop()
5161{
5162 sp<ThreadBase> thread = mThread.promote();
5163 if (thread != 0) {
5164 RecordThread *recordThread = (RecordThread *)thread.get();
5165 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005166 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005167 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005168 // read from buffer
5169 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 }
5171}
5172
5173void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5174{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005175 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005176 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005178 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005179 mSessionId,
5180 mFrameCount,
5181 mState,
5182 mCblk->sampleRate,
5183 mCblk->server,
5184 mCblk->user);
5185}
5186
5187
5188// ----------------------------------------------------------------------------
5189
5190AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005191 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005192 DuplicatingThread *sourceThread,
5193 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005194 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005195 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005196 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005197 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5198 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199 mActive(false), mSourceThread(sourceThread)
5200{
5201
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202 if (mCblk != NULL) {
5203 mCblk->flags |= CBLK_DIRECTION_OUT;
5204 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005205 mOutBuffer.frameCount = 0;
5206 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005207 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005208 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5209 mCblk, mBuffer, mCblk->buffers,
5210 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005212 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005213 }
5214}
5215
5216AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5217{
5218 clearBufferQueue();
5219}
5220
Glenn Kasten3acbd052012-02-28 10:39:56 -08005221status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005222 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005223{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005224 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 if (status != NO_ERROR) {
5226 return status;
5227 }
5228
5229 mActive = true;
5230 mRetryCount = 127;
5231 return status;
5232}
5233
5234void AudioFlinger::PlaybackThread::OutputTrack::stop()
5235{
5236 Track::stop();
5237 clearBufferQueue();
5238 mOutBuffer.frameCount = 0;
5239 mActive = false;
5240}
5241
5242bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5243{
5244 Buffer *pInBuffer;
5245 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005246 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005247 bool outputBufferFull = false;
5248 inBuffer.frameCount = frames;
5249 inBuffer.i16 = data;
5250
5251 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5252
5253 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005254 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005255 sp<ThreadBase> thread = mThread.promote();
5256 if (thread != 0) {
5257 MixerThread *mixerThread = (MixerThread *)thread.get();
5258 if (mCblk->frameCount > frames){
5259 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5260 uint32_t startFrames = (mCblk->frameCount - frames);
5261 pInBuffer = new Buffer;
5262 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5263 pInBuffer->frameCount = startFrames;
5264 pInBuffer->i16 = pInBuffer->mBuffer;
5265 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5266 mBufferQueue.add(pInBuffer);
5267 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005268 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005269 }
5270 }
5271 }
5272 }
5273
5274 while (waitTimeLeftMs) {
5275 // First write pending buffers, then new data
5276 if (mBufferQueue.size()) {
5277 pInBuffer = mBufferQueue.itemAt(0);
5278 } else {
5279 pInBuffer = &inBuffer;
5280 }
5281
5282 if (pInBuffer->frameCount == 0) {
5283 break;
5284 }
5285
5286 if (mOutBuffer.frameCount == 0) {
5287 mOutBuffer.frameCount = pInBuffer->frameCount;
5288 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005289 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005290 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005291 outputBufferFull = true;
5292 break;
5293 }
5294 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5295 if (waitTimeLeftMs >= waitTimeMs) {
5296 waitTimeLeftMs -= waitTimeMs;
5297 } else {
5298 waitTimeLeftMs = 0;
5299 }
5300 }
5301
5302 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5303 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5304 mCblk->stepUser(outFrames);
5305 pInBuffer->frameCount -= outFrames;
5306 pInBuffer->i16 += outFrames * channelCount;
5307 mOutBuffer.frameCount -= outFrames;
5308 mOutBuffer.i16 += outFrames * channelCount;
5309
5310 if (pInBuffer->frameCount == 0) {
5311 if (mBufferQueue.size()) {
5312 mBufferQueue.removeAt(0);
5313 delete [] pInBuffer->mBuffer;
5314 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005315 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316 } else {
5317 break;
5318 }
5319 }
5320 }
5321
5322 // If we could not write all frames, allocate a buffer and queue it for next time.
5323 if (inBuffer.frameCount) {
5324 sp<ThreadBase> thread = mThread.promote();
5325 if (thread != 0 && !thread->standby()) {
5326 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5327 pInBuffer = new Buffer;
5328 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5329 pInBuffer->frameCount = inBuffer.frameCount;
5330 pInBuffer->i16 = pInBuffer->mBuffer;
5331 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5332 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005333 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005335 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336 }
5337 }
5338 }
5339
5340 // Calling write() with a 0 length buffer, means that no more data will be written:
5341 // If no more buffers are pending, fill output track buffer to make sure it is started
5342 // by output mixer.
5343 if (frames == 0 && mBufferQueue.size() == 0) {
5344 if (mCblk->user < mCblk->frameCount) {
5345 frames = mCblk->frameCount - mCblk->user;
5346 pInBuffer = new Buffer;
5347 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5348 pInBuffer->frameCount = frames;
5349 pInBuffer->i16 = pInBuffer->mBuffer;
5350 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5351 mBufferQueue.add(pInBuffer);
5352 } else if (mActive) {
5353 stop();
5354 }
5355 }
5356
5357 return outputBufferFull;
5358}
5359
5360status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5361{
5362 int active;
5363 status_t result;
5364 audio_track_cblk_t* cblk = mCblk;
5365 uint32_t framesReq = buffer->frameCount;
5366
Steve Block3856b092011-10-20 11:56:00 +01005367// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 buffer->frameCount = 0;
5369
5370 uint32_t framesAvail = cblk->framesAvailable();
5371
5372
5373 if (framesAvail == 0) {
5374 Mutex::Autolock _l(cblk->lock);
5375 goto start_loop_here;
5376 while (framesAvail == 0) {
5377 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005378 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005379 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005380 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005381 }
5382 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5383 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005384 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385 }
5386 // read the server count again
5387 start_loop_here:
5388 framesAvail = cblk->framesAvailable_l();
5389 }
5390 }
5391
5392// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005393// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394// }
5395
5396 if (framesReq > framesAvail) {
5397 framesReq = framesAvail;
5398 }
5399
5400 uint32_t u = cblk->user;
5401 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5402
Marco Nelissena1472d92012-03-30 14:36:54 -07005403 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404 framesReq = bufferEnd - u;
5405 }
5406
5407 buffer->frameCount = framesReq;
5408 buffer->raw = (void *)cblk->buffer(u);
5409 return NO_ERROR;
5410}
5411
5412
5413void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5414{
5415 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416
5417 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005418 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419 delete [] pBuffer->mBuffer;
5420 delete pBuffer;
5421 }
5422 mBufferQueue.clear();
5423}
5424
5425// ----------------------------------------------------------------------------
5426
5427AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5428 : RefBase(),
5429 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005430 // 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 -07005431 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005432 mPid(pid),
5433 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434{
5435 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5436}
5437
5438// Client destructor must be called with AudioFlinger::mLock held
5439AudioFlinger::Client::~Client()
5440{
5441 mAudioFlinger->removeClient_l(mPid);
5442}
5443
Glenn Kasten435dbe62012-01-30 10:15:48 -08005444sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445{
5446 return mMemoryDealer;
5447}
5448
John Grossman4ff14ba2012-02-08 16:37:41 -08005449// Reserve one of the limited slots for a timed audio track associated
5450// with this client
5451bool AudioFlinger::Client::reserveTimedTrack()
5452{
5453 const int kMaxTimedTracksPerClient = 4;
5454
5455 Mutex::Autolock _l(mTimedTrackLock);
5456
5457 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5458 ALOGW("can not create timed track - pid %d has exceeded the limit",
5459 mPid);
5460 return false;
5461 }
5462
5463 mTimedTrackCount++;
5464 return true;
5465}
5466
5467// Release a slot for a timed audio track
5468void AudioFlinger::Client::releaseTimedTrack()
5469{
5470 Mutex::Autolock _l(mTimedTrackLock);
5471 mTimedTrackCount--;
5472}
5473
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474// ----------------------------------------------------------------------------
5475
5476AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5477 const sp<IAudioFlingerClient>& client,
5478 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005479 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480{
5481}
5482
5483AudioFlinger::NotificationClient::~NotificationClient()
5484{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485}
5486
5487void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5488{
5489 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005490 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491}
5492
5493// ----------------------------------------------------------------------------
5494
5495AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5496 : BnAudioTrack(),
5497 mTrack(track)
5498{
5499}
5500
5501AudioFlinger::TrackHandle::~TrackHandle() {
5502 // just stop the track on deletion, associated resources
5503 // will be freed from the main thread once all pending buffers have
5504 // been played. Unless it's not in the active track list, in which
5505 // case we free everything now...
5506 mTrack->destroy();
5507}
5508
Glenn Kasten90716c52012-01-26 13:40:12 -08005509sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5510 return mTrack->getCblk();
5511}
5512
Glenn Kasten3acbd052012-02-28 10:39:56 -08005513status_t AudioFlinger::TrackHandle::start() {
5514 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515}
5516
5517void AudioFlinger::TrackHandle::stop() {
5518 mTrack->stop();
5519}
5520
5521void AudioFlinger::TrackHandle::flush() {
5522 mTrack->flush();
5523}
5524
5525void AudioFlinger::TrackHandle::mute(bool e) {
5526 mTrack->mute(e);
5527}
5528
5529void AudioFlinger::TrackHandle::pause() {
5530 mTrack->pause();
5531}
5532
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5534{
5535 return mTrack->attachAuxEffect(EffectId);
5536}
5537
John Grossman4ff14ba2012-02-08 16:37:41 -08005538status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5539 sp<IMemory>* buffer) {
5540 if (!mTrack->isTimedTrack())
5541 return INVALID_OPERATION;
5542
5543 PlaybackThread::TimedTrack* tt =
5544 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5545 return tt->allocateTimedBuffer(size, buffer);
5546}
5547
5548status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5549 int64_t pts) {
5550 if (!mTrack->isTimedTrack())
5551 return INVALID_OPERATION;
5552
5553 PlaybackThread::TimedTrack* tt =
5554 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5555 return tt->queueTimedBuffer(buffer, pts);
5556}
5557
5558status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5559 const LinearTransform& xform, int target) {
5560
5561 if (!mTrack->isTimedTrack())
5562 return INVALID_OPERATION;
5563
5564 PlaybackThread::TimedTrack* tt =
5565 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5566 return tt->setMediaTimeTransform(
5567 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5568}
5569
Mathias Agopian65ab4712010-07-14 17:59:35 -07005570status_t AudioFlinger::TrackHandle::onTransact(
5571 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5572{
5573 return BnAudioTrack::onTransact(code, data, reply, flags);
5574}
5575
5576// ----------------------------------------------------------------------------
5577
5578sp<IAudioRecord> AudioFlinger::openRecord(
5579 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005580 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005582 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005583 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005585 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 int *sessionId,
5587 status_t *status)
5588{
5589 sp<RecordThread::RecordTrack> recordTrack;
5590 sp<RecordHandle> recordHandle;
5591 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592 status_t lStatus;
5593 RecordThread *thread;
5594 size_t inFrameCount;
5595 int lSessionId;
5596
5597 // check calling permissions
5598 if (!recordingAllowed()) {
5599 lStatus = PERMISSION_DENIED;
5600 goto Exit;
5601 }
5602
5603 // add client to list
5604 { // scope for mLock
5605 Mutex::Autolock _l(mLock);
5606 thread = checkRecordThread_l(input);
5607 if (thread == NULL) {
5608 lStatus = BAD_VALUE;
5609 goto Exit;
5610 }
5611
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005612 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613
5614 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005615 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616 lSessionId = *sessionId;
5617 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005618 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619 if (sessionId != NULL) {
5620 *sessionId = lSessionId;
5621 }
5622 }
5623 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005624 recordTrack = thread->createRecordTrack_l(client,
5625 sampleRate,
5626 format,
5627 channelMask,
5628 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005629 lSessionId,
5630 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005632 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5634 // destructor is called by the TrackBase destructor with mLock held
5635 client.clear();
5636 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005637 goto Exit;
5638 }
5639
5640 // return to handle to client
5641 recordHandle = new RecordHandle(recordTrack);
5642 lStatus = NO_ERROR;
5643
5644Exit:
5645 if (status) {
5646 *status = lStatus;
5647 }
5648 return recordHandle;
5649}
5650
5651// ----------------------------------------------------------------------------
5652
5653AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5654 : BnAudioRecord(),
5655 mRecordTrack(recordTrack)
5656{
5657}
5658
5659AudioFlinger::RecordHandle::~RecordHandle() {
5660 stop();
5661}
5662
Glenn Kasten90716c52012-01-26 13:40:12 -08005663sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5664 return mRecordTrack->getCblk();
5665}
5666
Glenn Kasten3acbd052012-02-28 10:39:56 -08005667status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005668 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005669 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005670}
5671
5672void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005673 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674 mRecordTrack->stop();
5675}
5676
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677status_t AudioFlinger::RecordHandle::onTransact(
5678 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5679{
5680 return BnAudioRecord::onTransact(code, data, reply, flags);
5681}
5682
5683// ----------------------------------------------------------------------------
5684
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005685AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5686 AudioStreamIn *input,
5687 uint32_t sampleRate,
5688 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005689 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005690 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005691 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005692 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5693 // mRsmpInIndex and mInputBytes set by readInputParameters()
5694 mReqChannelCount(popcount(channels)),
5695 mReqSampleRate(sampleRate)
5696 // mBytesRead is only meaningful while active, and so is cleared in start()
5697 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698{
Glenn Kasten480b4682012-02-28 12:30:08 -08005699 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005700
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 readInputParameters();
5702}
5703
5704
5705AudioFlinger::RecordThread::~RecordThread()
5706{
5707 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005708 delete mResampler;
5709 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710}
5711
5712void AudioFlinger::RecordThread::onFirstRef()
5713{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005714 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715}
5716
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005717status_t AudioFlinger::RecordThread::readyToRun()
5718{
5719 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005720 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005721 return status;
5722}
5723
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724bool AudioFlinger::RecordThread::threadLoop()
5725{
5726 AudioBufferProvider::Buffer buffer;
5727 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005728 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729
Eric Laurent44d98482010-09-30 16:12:31 -07005730 nsecs_t lastWarning = 0;
5731
Eric Laurentfeb0db62011-07-22 09:04:31 -07005732 acquireWakeLock();
5733
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 // start recording
5735 while (!exitPending()) {
5736
5737 processConfigEvents();
5738
5739 { // scope for mLock
5740 Mutex::Autolock _l(mLock);
5741 checkForNewParameters_l();
5742 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5743 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005744 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745 mStandby = true;
5746 }
5747
5748 if (exitPending()) break;
5749
Eric Laurentfeb0db62011-07-22 09:04:31 -07005750 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005751 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005752 // go to sleep
5753 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005754 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005755 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 continue;
5757 }
5758 if (mActiveTrack != 0) {
5759 if (mActiveTrack->mState == TrackBase::PAUSING) {
5760 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005761 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 mStandby = true;
5763 }
5764 mActiveTrack.clear();
5765 mStartStopCond.broadcast();
5766 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5767 if (mReqChannelCount != mActiveTrack->channelCount()) {
5768 mActiveTrack.clear();
5769 mStartStopCond.broadcast();
5770 } else if (mBytesRead != 0) {
5771 // record start succeeds only if first read from audio input
5772 // succeeds
5773 if (mBytesRead > 0) {
5774 mActiveTrack->mState = TrackBase::ACTIVE;
5775 } else {
5776 mActiveTrack.clear();
5777 }
5778 mStartStopCond.broadcast();
5779 }
5780 mStandby = false;
5781 }
5782 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005783 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784 }
5785
5786 if (mActiveTrack != 0) {
5787 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5788 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005789 unlockEffectChains(effectChains);
5790 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791 continue;
5792 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005793 for (size_t i = 0; i < effectChains.size(); i ++) {
5794 effectChains[i]->process_l();
5795 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005796
Mathias Agopian65ab4712010-07-14 17:59:35 -07005797 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005798 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005800 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801 // no resampling
5802 while (framesOut) {
5803 size_t framesIn = mFrameCount - mRsmpInIndex;
5804 if (framesIn) {
5805 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5806 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5807 if (framesIn > framesOut)
5808 framesIn = framesOut;
5809 mRsmpInIndex += framesIn;
5810 framesOut -= framesIn;
5811 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005812 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 memcpy(dst, src, framesIn * mFrameSize);
5814 } else {
5815 int16_t *src16 = (int16_t *)src;
5816 int16_t *dst16 = (int16_t *)dst;
5817 if (mChannelCount == 1) {
5818 while (framesIn--) {
5819 *dst16++ = *src16;
5820 *dst16++ = *src16++;
5821 }
5822 } else {
5823 while (framesIn--) {
5824 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5825 src16 += 2;
5826 }
5827 }
5828 }
5829 }
5830 if (framesOut && mFrameCount == mRsmpInIndex) {
5831 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005832 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005833 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 framesOut = 0;
5835 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005836 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005837 mRsmpInIndex = 0;
5838 }
5839 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005840 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5842 // Force input into standby so that it tries to
5843 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005844 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005845 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846 }
5847 mRsmpInIndex = mFrameCount;
5848 framesOut = 0;
5849 buffer.frameCount = 0;
5850 }
5851 }
5852 }
5853 } else {
5854 // resampling
5855
5856 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5857 // alter output frame count as if we were expecting stereo samples
5858 if (mChannelCount == 1 && mReqChannelCount == 1) {
5859 framesOut >>= 1;
5860 }
5861 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5862 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5863 // are 32 bit aligned which should be always true.
5864 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005865 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866 // the resampler always outputs stereo samples: do post stereo to mono conversion
5867 int16_t *src = (int16_t *)mRsmpOutBuffer;
5868 int16_t *dst = buffer.i16;
5869 while (framesOut--) {
5870 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5871 src += 2;
5872 }
5873 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005874 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 }
5876
5877 }
Eric Laurenta011e352012-03-29 15:51:43 -07005878 if (mFramestoDrop == 0) {
5879 mActiveTrack->releaseBuffer(&buffer);
5880 } else {
5881 if (mFramestoDrop > 0) {
5882 mFramestoDrop -= buffer.frameCount;
5883 if (mFramestoDrop < 0) {
5884 mFramestoDrop = 0;
5885 }
5886 }
5887 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888 mActiveTrack->overflow();
5889 }
5890 // client isn't retrieving buffers fast enough
5891 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005892 if (!mActiveTrack->setOverflow()) {
5893 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005894 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005895 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005896 lastWarning = now;
5897 }
5898 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 // Release the processor for a while before asking for a new buffer.
5900 // This will give the application more chance to read from the buffer and
5901 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005902 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 }
5904 }
Eric Laurentec437d82011-07-26 20:54:46 -07005905 // enable changes in effect chain
5906 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005907 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908 }
5909
5910 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005911 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912 }
5913 mActiveTrack.clear();
5914
5915 mStartStopCond.broadcast();
5916
Eric Laurentfeb0db62011-07-22 09:04:31 -07005917 releaseWakeLock();
5918
Steve Block3856b092011-10-20 11:56:00 +01005919 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 return false;
5921}
5922
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005923
5924sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5925 const sp<AudioFlinger::Client>& client,
5926 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005927 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005928 int channelMask,
5929 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005930 int sessionId,
5931 status_t *status)
5932{
5933 sp<RecordTrack> track;
5934 status_t lStatus;
5935
5936 lStatus = initCheck();
5937 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005938 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005939 goto Exit;
5940 }
5941
5942 { // scope for mLock
5943 Mutex::Autolock _l(mLock);
5944
5945 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005946 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005947
Glenn Kasten7378ca52012-01-20 13:44:40 -08005948 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005949 lStatus = NO_MEMORY;
5950 goto Exit;
5951 }
5952
5953 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005954 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5955 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005956 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005957 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5958 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005959 }
5960 lStatus = NO_ERROR;
5961
5962Exit:
5963 if (status) {
5964 *status = lStatus;
5965 }
5966 return track;
5967}
5968
Eric Laurenta011e352012-03-29 15:51:43 -07005969status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005970 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005971 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972{
Glenn Kasten58912562012-04-03 10:45:00 -07005973 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005974 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005976
5977 if (event == AudioSystem::SYNC_EVENT_NONE) {
5978 mSyncStartEvent.clear();
5979 mFramestoDrop = 0;
5980 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5981 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5982 triggerSession,
5983 recordTrack->sessionId(),
5984 syncStartEventCallback,
5985 this);
5986 mFramestoDrop = -1;
5987 }
5988
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005990 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 if (mActiveTrack != 0) {
5992 if (recordTrack != mActiveTrack.get()) {
5993 status = -EBUSY;
5994 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5995 mActiveTrack->mState = TrackBase::ACTIVE;
5996 }
5997 return status;
5998 }
5999
6000 recordTrack->mState = TrackBase::IDLE;
6001 mActiveTrack = recordTrack;
6002 mLock.unlock();
6003 status_t status = AudioSystem::startInput(mId);
6004 mLock.lock();
6005 if (status != NO_ERROR) {
6006 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006007 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 return status;
6009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 mRsmpInIndex = mFrameCount;
6011 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006012 if (mResampler != NULL) {
6013 mResampler->reset();
6014 }
6015 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006016 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006017 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018 mWaitWorkCV.signal();
6019 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006020 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 mActiveTrack.clear();
6022 status = INVALID_OPERATION;
6023 goto startError;
6024 }
6025 mStartStopCond.wait(mLock);
6026 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006027 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028 status = BAD_VALUE;
6029 goto startError;
6030 }
Steve Block3856b092011-10-20 11:56:00 +01006031 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032 return status;
6033 }
6034startError:
6035 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006036 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 return status;
6038}
6039
Eric Laurenta011e352012-03-29 15:51:43 -07006040void AudioFlinger::RecordThread::clearSyncStartEvent()
6041{
6042 if (mSyncStartEvent != 0) {
6043 mSyncStartEvent->cancel();
6044 }
6045 mSyncStartEvent.clear();
6046}
6047
6048void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6049{
6050 sp<SyncEvent> strongEvent = event.promote();
6051
6052 if (strongEvent != 0) {
6053 RecordThread *me = (RecordThread *)strongEvent->cookie();
6054 me->handleSyncStartEvent(strongEvent);
6055 }
6056}
6057
6058void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6059{
6060 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
6061 mActiveTrack.get(),
6062 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
6063 event->listenerSession());
6064
6065 if (mActiveTrack != 0 &&
6066 event == mSyncStartEvent) {
6067 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6068 // from audio HAL
6069 mFramestoDrop = mFrameCount * 2;
6070 mSyncStartEvent.clear();
6071 }
6072}
6073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006075 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006076 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006077 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006078 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6080 mActiveTrack->mState = TrackBase::PAUSING;
6081 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006082 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 return;
6084 }
6085 mStartStopCond.wait(mLock);
6086 // if we have been restarted, recordTrack == mActiveTrack.get() here
6087 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6088 mLock.unlock();
6089 AudioSystem::stopInput(mId);
6090 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006091 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 }
6093 }
6094 }
6095}
6096
Eric Laurenta011e352012-03-29 15:51:43 -07006097bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6098{
6099 return false;
6100}
6101
6102status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6103{
6104 if (!isValidSyncEvent(event)) {
6105 return BAD_VALUE;
6106 }
6107
6108 Mutex::Autolock _l(mLock);
6109
6110 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6111 mTrack->setSyncEvent(event);
6112 return NO_ERROR;
6113 }
6114 return NAME_NOT_FOUND;
6115}
6116
Mathias Agopian65ab4712010-07-14 17:59:35 -07006117status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6118{
6119 const size_t SIZE = 256;
6120 char buffer[SIZE];
6121 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122
6123 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6124 result.append(buffer);
6125
6126 if (mActiveTrack != 0) {
6127 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006128 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 mActiveTrack->dump(buffer, SIZE);
6130 result.append(buffer);
6131
6132 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6133 result.append(buffer);
6134 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6135 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006136 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006137 result.append(buffer);
6138 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6139 result.append(buffer);
6140 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6141 result.append(buffer);
6142
6143
6144 } else {
6145 result.append("No record client\n");
6146 }
6147 write(fd, result.string(), result.size());
6148
6149 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006150 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151
6152 return NO_ERROR;
6153}
6154
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006155// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006156status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157{
6158 size_t framesReq = buffer->frameCount;
6159 size_t framesReady = mFrameCount - mRsmpInIndex;
6160 int channelCount;
6161
6162 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006163 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006165 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6167 // Force input into standby so that it tries to
6168 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006169 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006170 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006171 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006172 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 buffer->frameCount = 0;
6174 return NOT_ENOUGH_DATA;
6175 }
6176 mRsmpInIndex = 0;
6177 framesReady = mFrameCount;
6178 }
6179
6180 if (framesReq > framesReady) {
6181 framesReq = framesReady;
6182 }
6183
6184 if (mChannelCount == 1 && mReqChannelCount == 2) {
6185 channelCount = 1;
6186 } else {
6187 channelCount = 2;
6188 }
6189 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6190 buffer->frameCount = framesReq;
6191 return NO_ERROR;
6192}
6193
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006194// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6196{
6197 mRsmpInIndex += buffer->frameCount;
6198 buffer->frameCount = 0;
6199}
6200
6201bool AudioFlinger::RecordThread::checkForNewParameters_l()
6202{
6203 bool reconfig = false;
6204
6205 while (!mNewParameters.isEmpty()) {
6206 status_t status = NO_ERROR;
6207 String8 keyValuePair = mNewParameters[0];
6208 AudioParameter param = AudioParameter(keyValuePair);
6209 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006210 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211 int reqSamplingRate = mReqSampleRate;
6212 int reqChannelCount = mReqChannelCount;
6213
6214 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6215 reqSamplingRate = value;
6216 reconfig = true;
6217 }
6218 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006219 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 reconfig = true;
6221 }
6222 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006223 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 reconfig = true;
6225 }
6226 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6227 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006228 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 // if frame count is changed after track creation
6230 if (mActiveTrack != 0) {
6231 status = INVALID_OPERATION;
6232 } else {
6233 reconfig = true;
6234 }
6235 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006236 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6237 // forward device change to effects that have requested to be
6238 // aware of attached audio device.
6239 for (size_t i = 0; i < mEffectChains.size(); i++) {
6240 mEffectChains[i]->setDevice_l(value);
6241 }
6242 // store input device and output device but do not forward output device to audio HAL.
6243 // Note that status is ignored by the caller for output device
6244 // (see AudioFlinger::setParameters()
6245 if (value & AUDIO_DEVICE_OUT_ALL) {
6246 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6247 status = BAD_VALUE;
6248 } else {
6249 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006250 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6251 if (mTrack != NULL) {
6252 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006253 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006254 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6255 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6256 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006257 }
6258 mDevice |= (uint32_t)value;
6259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006261 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006263 mInput->stream->common.standby(&mInput->stream->common);
6264 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6265 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 }
6267 if (reconfig) {
6268 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006269 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006270 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006271 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006272 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6273 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 status = NO_ERROR;
6275 }
6276 if (status == NO_ERROR) {
6277 readInputParameters();
6278 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6279 }
6280 }
6281 }
6282
6283 mNewParameters.removeAt(0);
6284
6285 mParamStatus = status;
6286 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006287 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6288 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006289 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 }
6291 return reconfig;
6292}
6293
6294String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6295{
Dima Zavinfce7a472011-04-19 22:30:36 -07006296 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006297 String8 out_s8 = String8();
6298
6299 Mutex::Autolock _l(mLock);
6300 if (initCheck() != NO_ERROR) {
6301 return out_s8;
6302 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006303
Dima Zavin799a70e2011-04-18 16:57:27 -07006304 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006305 out_s8 = String8(s);
6306 free(s);
6307 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006308}
6309
6310void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6311 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006312 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313
6314 switch (event) {
6315 case AudioSystem::INPUT_OPENED:
6316 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006317 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 desc.samplingRate = mSampleRate;
6319 desc.format = mFormat;
6320 desc.frameCount = mFrameCount;
6321 desc.latency = 0;
6322 param2 = &desc;
6323 break;
6324
6325 case AudioSystem::INPUT_CLOSED:
6326 default:
6327 break;
6328 }
6329 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6330}
6331
6332void AudioFlinger::RecordThread::readInputParameters()
6333{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006334 delete mRsmpInBuffer;
6335 // mRsmpInBuffer is always assigned a new[] below
6336 delete mRsmpOutBuffer;
6337 mRsmpOutBuffer = NULL;
6338 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006339 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340
Dima Zavin799a70e2011-04-18 16:57:27 -07006341 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006342 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6343 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006344 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006345 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006346 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006348 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6350
Glenn Kasten53d76db2012-03-08 12:32:47 -08006351 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 {
6353 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006354 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6355 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 if (mChannelCount == 1 && mReqChannelCount == 2) {
6357 channelCount = 1;
6358 } else {
6359 channelCount = 2;
6360 }
6361 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6362 mResampler->setSampleRate(mSampleRate);
6363 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6364 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6365
6366 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6367 if (mChannelCount == 1 && mReqChannelCount == 1) {
6368 mFrameCount >>= 1;
6369 }
6370
6371 }
6372 mRsmpInIndex = mFrameCount;
6373}
6374
6375unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6376{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006377 Mutex::Autolock _l(mLock);
6378 if (initCheck() != NO_ERROR) {
6379 return 0;
6380 }
6381
Dima Zavin799a70e2011-04-18 16:57:27 -07006382 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383}
6384
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006385uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6386{
6387 Mutex::Autolock _l(mLock);
6388 uint32_t result = 0;
6389 if (getEffectChain_l(sessionId) != 0) {
6390 result = EFFECT_SESSION;
6391 }
6392
6393 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6394 result |= TRACK_SESSION;
6395 }
6396
6397 return result;
6398}
6399
Eric Laurent59bd0da2011-08-01 09:52:20 -07006400AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6401{
6402 Mutex::Autolock _l(mLock);
6403 return mTrack;
6404}
6405
Glenn Kastenaed850d2012-01-26 09:46:34 -08006406AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006407{
6408 Mutex::Autolock _l(mLock);
6409 return mInput;
6410}
6411
6412AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6413{
6414 Mutex::Autolock _l(mLock);
6415 AudioStreamIn *input = mInput;
6416 mInput = NULL;
6417 return input;
6418}
6419
6420// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006421audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006422{
6423 if (mInput == NULL) {
6424 return NULL;
6425 }
6426 return &mInput->stream->common;
6427}
6428
6429
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430// ----------------------------------------------------------------------------
6431
Eric Laurenta4c5a552012-03-29 10:12:40 -07006432audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6433{
6434 if (!settingsAllowed()) {
6435 return 0;
6436 }
6437 Mutex::Autolock _l(mLock);
6438 return loadHwModule_l(name);
6439}
6440
6441// loadHwModule_l() must be called with AudioFlinger::mLock held
6442audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6443{
6444 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6445 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6446 ALOGW("loadHwModule() module %s already loaded", name);
6447 return mAudioHwDevs.keyAt(i);
6448 }
6449 }
6450
Eric Laurenta4c5a552012-03-29 10:12:40 -07006451 audio_hw_device_t *dev;
6452
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006453 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006454 if (rc) {
6455 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6456 return 0;
6457 }
6458
6459 mHardwareStatus = AUDIO_HW_INIT;
6460 rc = dev->init_check(dev);
6461 mHardwareStatus = AUDIO_HW_IDLE;
6462 if (rc) {
6463 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6464 return 0;
6465 }
6466
6467 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6468 (NULL != dev->set_master_volume)) {
6469 AutoMutex lock(mHardwareLock);
6470 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6471 dev->set_master_volume(dev, mMasterVolume);
6472 mHardwareStatus = AUDIO_HW_IDLE;
6473 }
6474
6475 audio_module_handle_t handle = nextUniqueId();
6476 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6477
6478 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006479 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006480
6481 return handle;
6482
6483}
6484
6485audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6486 audio_devices_t *pDevices,
6487 uint32_t *pSamplingRate,
6488 audio_format_t *pFormat,
6489 audio_channel_mask_t *pChannelMask,
6490 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006491 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492{
6493 status_t status;
6494 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006495 struct audio_config config = {
6496 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6497 channel_mask: pChannelMask ? *pChannelMask : 0,
6498 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6499 };
6500 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006501 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502
Eric Laurenta4c5a552012-03-29 10:12:40 -07006503 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6504 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006505 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006506 config.sample_rate,
6507 config.format,
6508 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006509 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510
6511 if (pDevices == NULL || *pDevices == 0) {
6512 return 0;
6513 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006514
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 Mutex::Autolock _l(mLock);
6516
Eric Laurenta4c5a552012-03-29 10:12:40 -07006517 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006518 if (outHwDev == NULL)
6519 return 0;
6520
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006521 audio_io_handle_t id = nextUniqueId();
6522
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006523 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006524
6525 status = outHwDev->open_output_stream(outHwDev,
6526 id,
6527 *pDevices,
6528 (audio_output_flags_t)flags,
6529 &config,
6530 &outStream);
6531
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006532 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006533 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006534 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006535 config.sample_rate,
6536 config.format,
6537 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 status);
6539
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006540 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006541 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006542
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006543 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006544 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6545 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006547 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 } else {
6549 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006550 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 }
6552 mPlaybackThreads.add(id, thread);
6553
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006554 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6555 if (pFormat != NULL) *pFormat = config.format;
6556 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006557 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558
6559 // notify client processes of the new output creation
6560 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006561
6562 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006563 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006564 ALOGI("Using module %d has the primary audio interface", module);
6565 mPrimaryHardwareDev = outHwDev;
6566
6567 AutoMutex lock(mHardwareLock);
6568 mHardwareStatus = AUDIO_HW_SET_MODE;
6569 outHwDev->set_mode(outHwDev, mMode);
6570
6571 // Determine the level of master volume support the primary audio HAL has,
6572 // and set the initial master volume at the same time.
6573 float initialVolume = 1.0;
6574 mMasterVolumeSupportLvl = MVS_NONE;
6575
6576 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6577 if ((NULL != outHwDev->get_master_volume) &&
6578 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6579 mMasterVolumeSupportLvl = MVS_FULL;
6580 } else {
6581 mMasterVolumeSupportLvl = MVS_SETONLY;
6582 initialVolume = 1.0;
6583 }
6584
6585 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6586 if ((NULL == outHwDev->set_master_volume) ||
6587 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6588 mMasterVolumeSupportLvl = MVS_NONE;
6589 }
6590 // now that we have a primary device, initialize master volume on other devices
6591 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6592 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6593
6594 if ((dev != mPrimaryHardwareDev) &&
6595 (NULL != dev->set_master_volume)) {
6596 dev->set_master_volume(dev, initialVolume);
6597 }
6598 }
6599 mHardwareStatus = AUDIO_HW_IDLE;
6600 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6601 ? initialVolume
6602 : 1.0;
6603 mMasterVolume = initialVolume;
6604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605 return id;
6606 }
6607
6608 return 0;
6609}
6610
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006611audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6612 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613{
6614 Mutex::Autolock _l(mLock);
6615 MixerThread *thread1 = checkMixerThread_l(output1);
6616 MixerThread *thread2 = checkMixerThread_l(output2);
6617
6618 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006619 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 return 0;
6621 }
6622
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006623 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6625 thread->addOutputTrack(thread2);
6626 mPlaybackThreads.add(id, thread);
6627 // notify client processes of the new output creation
6628 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6629 return id;
6630}
6631
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006632status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633{
6634 // keep strong reference on the playback thread so that
6635 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006636 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006637 {
6638 Mutex::Autolock _l(mLock);
6639 thread = checkPlaybackThread_l(output);
6640 if (thread == NULL) {
6641 return BAD_VALUE;
6642 }
6643
Steve Block3856b092011-10-20 11:56:00 +01006644 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006646 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006647 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006648 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6650 dupThread->removeOutputTrack((MixerThread *)thread.get());
6651 }
6652 }
6653 }
Glenn Kastena1117922012-01-26 10:53:32 -08006654 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655 mPlaybackThreads.removeItem(output);
6656 }
6657 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006658 // The thread entity (active unit of execution) is no longer running here,
6659 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006661 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006662 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006663 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006664 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006665 out->hwDev->close_output_stream(out->hwDev, out->stream);
6666 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 }
6668 return NO_ERROR;
6669}
6670
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006671status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672{
6673 Mutex::Autolock _l(mLock);
6674 PlaybackThread *thread = checkPlaybackThread_l(output);
6675
6676 if (thread == NULL) {
6677 return BAD_VALUE;
6678 }
6679
Steve Block3856b092011-10-20 11:56:00 +01006680 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681 thread->suspend();
6682
6683 return NO_ERROR;
6684}
6685
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006686status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006687{
6688 Mutex::Autolock _l(mLock);
6689 PlaybackThread *thread = checkPlaybackThread_l(output);
6690
6691 if (thread == NULL) {
6692 return BAD_VALUE;
6693 }
6694
Steve Block3856b092011-10-20 11:56:00 +01006695 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696
6697 thread->restore();
6698
6699 return NO_ERROR;
6700}
6701
Eric Laurenta4c5a552012-03-29 10:12:40 -07006702audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6703 audio_devices_t *pDevices,
6704 uint32_t *pSamplingRate,
6705 audio_format_t *pFormat,
6706 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707{
6708 status_t status;
6709 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006710 struct audio_config config = {
6711 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6712 channel_mask: pChannelMask ? *pChannelMask : 0,
6713 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6714 };
6715 uint32_t reqSamplingRate = config.sample_rate;
6716 audio_format_t reqFormat = config.format;
6717 audio_channel_mask_t reqChannels = config.channel_mask;
6718 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006719 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720
6721 if (pDevices == NULL || *pDevices == 0) {
6722 return 0;
6723 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006724
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 Mutex::Autolock _l(mLock);
6726
Eric Laurenta4c5a552012-03-29 10:12:40 -07006727 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006728 if (inHwDev == NULL)
6729 return 0;
6730
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006731 audio_io_handle_t id = nextUniqueId();
6732
6733 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006734 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006735 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006736 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006737 config.sample_rate,
6738 config.format,
6739 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740 status);
6741
6742 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6743 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6744 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006745 if (status == BAD_VALUE &&
6746 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6747 (config.sample_rate <= 2 * reqSamplingRate) &&
6748 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006749 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006750 inStream = NULL;
6751 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006752 }
6753
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006754 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006755 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6756
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006757 // Start record thread
6758 // RecorThread require both input and output device indication to forward to audio
6759 // pre processing modules
6760 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6761 thread = new RecordThread(this,
6762 input,
6763 reqSamplingRate,
6764 reqChannels,
6765 id,
6766 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006768 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006769 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006770 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006771 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772
Dima Zavin799a70e2011-04-18 16:57:27 -07006773 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774
6775 // notify client processes of the new input creation
6776 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6777 return id;
6778 }
6779
6780 return 0;
6781}
6782
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006783status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006784{
6785 // keep strong reference on the record thread so that
6786 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006787 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 {
6789 Mutex::Autolock _l(mLock);
6790 thread = checkRecordThread_l(input);
6791 if (thread == NULL) {
6792 return BAD_VALUE;
6793 }
6794
Steve Block3856b092011-10-20 11:56:00 +01006795 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006796 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 mRecordThreads.removeItem(input);
6798 }
6799 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006800 // The thread entity (active unit of execution) is no longer running here,
6801 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006802
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006803 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006804 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006805 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006806 in->hwDev->close_input_stream(in->hwDev, in->stream);
6807 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808
6809 return NO_ERROR;
6810}
6811
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006812status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813{
6814 Mutex::Autolock _l(mLock);
6815 MixerThread *dstThread = checkMixerThread_l(output);
6816 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006817 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818 return BAD_VALUE;
6819 }
6820
Steve Block3856b092011-10-20 11:56:00 +01006821 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006822 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6823
6824 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6825 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006826 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827 MixerThread *srcThread = (MixerThread *)thread;
6828 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829 }
Eric Laurentde070132010-07-13 04:45:46 -07006830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831
6832 return NO_ERROR;
6833}
6834
6835
6836int AudioFlinger::newAudioSessionId()
6837{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006838 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839}
6840
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006841void AudioFlinger::acquireAudioSessionId(int audioSession)
6842{
6843 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006844 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006845 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006846 size_t num = mAudioSessionRefs.size();
6847 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006848 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006849 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6850 ref->mCnt++;
6851 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006852 return;
6853 }
6854 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006855 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6856 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006857}
6858
6859void AudioFlinger::releaseAudioSessionId(int audioSession)
6860{
6861 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006862 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006863 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006864 size_t num = mAudioSessionRefs.size();
6865 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006866 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006867 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6868 ref->mCnt--;
6869 ALOGV(" decremented refcount to %d", ref->mCnt);
6870 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006871 mAudioSessionRefs.removeAt(i);
6872 delete ref;
6873 purgeStaleEffects_l();
6874 }
6875 return;
6876 }
6877 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006878 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006879}
6880
6881void AudioFlinger::purgeStaleEffects_l() {
6882
Steve Block3856b092011-10-20 11:56:00 +01006883 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006884
6885 Vector< sp<EffectChain> > chains;
6886
6887 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6888 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6889 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6890 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006891 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6892 chains.push(ec);
6893 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006894 }
6895 }
6896 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6897 sp<RecordThread> t = mRecordThreads.valueAt(i);
6898 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6899 sp<EffectChain> ec = t->mEffectChains[j];
6900 chains.push(ec);
6901 }
6902 }
6903
6904 for (size_t i = 0; i < chains.size(); i++) {
6905 sp<EffectChain> ec = chains[i];
6906 int sessionid = ec->sessionId();
6907 sp<ThreadBase> t = ec->mThread.promote();
6908 if (t == 0) {
6909 continue;
6910 }
6911 size_t numsessionrefs = mAudioSessionRefs.size();
6912 bool found = false;
6913 for (size_t k = 0; k < numsessionrefs; k++) {
6914 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006915 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006916 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006917 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006918 found = true;
6919 break;
6920 }
6921 }
6922 if (!found) {
6923 // remove all effects from the chain
6924 while (ec->mEffects.size()) {
6925 sp<EffectModule> effect = ec->mEffects[0];
6926 effect->unPin();
6927 Mutex::Autolock _l (t->mLock);
6928 t->removeEffect_l(effect);
6929 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6930 sp<EffectHandle> handle = effect->mHandles[j].promote();
6931 if (handle != 0) {
6932 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006933 if (handle->mHasControl && handle->mEnabled) {
6934 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6935 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006936 }
6937 }
6938 AudioSystem::unregisterEffect(effect->id());
6939 }
6940 }
6941 }
6942 return;
6943}
6944
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006946AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947{
Glenn Kastena1117922012-01-26 10:53:32 -08006948 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949}
6950
6951// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006952AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953{
6954 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006955 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956}
6957
6958// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006959AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006960{
Glenn Kastena1117922012-01-26 10:53:32 -08006961 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962}
6963
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006964uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006966 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967}
6968
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006969AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006970{
6971 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6972 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006973 AudioStreamOut *output = thread->getOutput();
6974 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006975 return thread;
6976 }
6977 }
6978 return NULL;
6979}
6980
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006981uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006982{
6983 PlaybackThread *thread = primaryPlaybackThread_l();
6984
6985 if (thread == NULL) {
6986 return 0;
6987 }
6988
6989 return thread->device();
6990}
6991
Eric Laurenta011e352012-03-29 15:51:43 -07006992sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6993 int triggerSession,
6994 int listenerSession,
6995 sync_event_callback_t callBack,
6996 void *cookie)
6997{
6998 Mutex::Autolock _l(mLock);
6999
7000 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7001 status_t playStatus = NAME_NOT_FOUND;
7002 status_t recStatus = NAME_NOT_FOUND;
7003 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7004 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7005 if (playStatus == NO_ERROR) {
7006 return event;
7007 }
7008 }
7009 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7010 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7011 if (recStatus == NO_ERROR) {
7012 return event;
7013 }
7014 }
7015 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7016 mPendingSyncEvents.add(event);
7017 } else {
7018 ALOGV("createSyncEvent() invalid event %d", event->type());
7019 event.clear();
7020 }
7021 return event;
7022}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007023
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024// ----------------------------------------------------------------------------
7025// Effect management
7026// ----------------------------------------------------------------------------
7027
7028
Glenn Kastenf587ba52012-01-26 16:25:10 -08007029status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030{
7031 Mutex::Autolock _l(mLock);
7032 return EffectQueryNumberEffects(numEffects);
7033}
7034
Glenn Kastenf587ba52012-01-26 16:25:10 -08007035status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036{
7037 Mutex::Autolock _l(mLock);
7038 return EffectQueryEffect(index, descriptor);
7039}
7040
Glenn Kasten5e92a782012-01-30 07:40:52 -08007041status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007042 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043{
7044 Mutex::Autolock _l(mLock);
7045 return EffectGetDescriptor(pUuid, descriptor);
7046}
7047
7048
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7050 effect_descriptor_t *pDesc,
7051 const sp<IEffectClient>& effectClient,
7052 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007053 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054 int sessionId,
7055 status_t *status,
7056 int *id,
7057 int *enabled)
7058{
7059 status_t lStatus = NO_ERROR;
7060 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007063 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007064 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065
7066 if (pDesc == NULL) {
7067 lStatus = BAD_VALUE;
7068 goto Exit;
7069 }
7070
Eric Laurent84e9a102010-09-23 16:10:16 -07007071 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007072 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007073 lStatus = PERMISSION_DENIED;
7074 goto Exit;
7075 }
7076
Dima Zavinfce7a472011-04-19 22:30:36 -07007077 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007078 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007079 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007080 lStatus = PERMISSION_DENIED;
7081 goto Exit;
7082 }
7083
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007084 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007085 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007086 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007087 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007088 lStatus = BAD_VALUE;
7089 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007090 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007091 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007092 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007093 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007094 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007095 }
7096 }
7097
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098 {
7099 Mutex::Autolock _l(mLock);
7100
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101
7102 if (!EffectIsNullUuid(&pDesc->uuid)) {
7103 // if uuid is specified, request effect descriptor
7104 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7105 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007106 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 goto Exit;
7108 }
7109 } else {
7110 // if uuid is not specified, look for an available implementation
7111 // of the required type in effect factory
7112 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007113 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114 lStatus = BAD_VALUE;
7115 goto Exit;
7116 }
7117 uint32_t numEffects = 0;
7118 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007119 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120 bool found = false;
7121
7122 lStatus = EffectQueryNumberEffects(&numEffects);
7123 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007124 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 goto Exit;
7126 }
7127 for (uint32_t i = 0; i < numEffects; i++) {
7128 lStatus = EffectQueryEffect(i, &desc);
7129 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007130 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131 continue;
7132 }
7133 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7134 // If matching type found save effect descriptor. If the session is
7135 // 0 and the effect is not auxiliary, continue enumeration in case
7136 // an auxiliary version of this effect type is available
7137 found = true;
7138 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007139 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7141 break;
7142 }
7143 }
7144 }
7145 if (!found) {
7146 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007147 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148 goto Exit;
7149 }
7150 // For same effect type, chose auxiliary version over insert version if
7151 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007152 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7154 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7155 }
7156 }
7157
7158 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007159 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7161 lStatus = INVALID_OPERATION;
7162 goto Exit;
7163 }
7164
Eric Laurent59255e42011-07-27 19:49:51 -07007165 // check recording permission for visualizer
7166 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7167 !recordingAllowed()) {
7168 lStatus = PERMISSION_DENIED;
7169 goto Exit;
7170 }
7171
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 // return effect descriptor
7173 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7174
7175 // If output is not specified try to find a matching audio session ID in one of the
7176 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007177 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7178 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007179 // Note: io is never 0 when creating an effect on an input
7180 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007181 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007182 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7183 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007184 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007185 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007188 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007189 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7190 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7191 io = mRecordThreads.keyAt(i);
7192 break;
7193 }
7194 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007195 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007196 // If no output thread contains the requested session ID, default to
7197 // first output. The effect chain will be moved to the correct output
7198 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007199 if (io == 0 && mPlaybackThreads.size()) {
7200 io = mPlaybackThreads.keyAt(0);
7201 }
Steve Block3856b092011-10-20 11:56:00 +01007202 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007203 }
7204 ThreadBase *thread = checkRecordThread_l(io);
7205 if (thread == NULL) {
7206 thread = checkPlaybackThread_l(io);
7207 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007208 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007209 lStatus = BAD_VALUE;
7210 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007213
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007214 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007215
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007216 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007217 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7218 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007219 if (handle != 0 && id != NULL) {
7220 *id = handle->id();
7221 }
7222 }
7223
7224Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007225 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 *status = lStatus;
7227 }
7228 return handle;
7229}
7230
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007231status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7232 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007233{
Steve Block3856b092011-10-20 11:56:00 +01007234 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007235 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007236 Mutex::Autolock _l(mLock);
7237 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007238 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007239 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240 }
Eric Laurentde070132010-07-13 04:45:46 -07007241 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7242 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007243 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007244 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245 }
Eric Laurentde070132010-07-13 04:45:46 -07007246 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7247 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007248 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007249 return BAD_VALUE;
7250 }
7251
7252 Mutex::Autolock _dl(dstThread->mLock);
7253 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007254 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007255
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256 return NO_ERROR;
7257}
7258
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007259// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007260status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007261 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007262 AudioFlinger::PlaybackThread *dstThread,
7263 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007264{
Steve Block3856b092011-10-20 11:56:00 +01007265 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007266 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007267
Eric Laurent59255e42011-07-27 19:49:51 -07007268 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007269 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007270 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007271 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007272 return INVALID_OPERATION;
7273 }
7274
Eric Laurent39e94f82010-07-28 01:32:47 -07007275 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007276 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007277 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007278 // removed.
7279 srcThread->removeEffectChain_l(chain);
7280
7281 // transfer all effects one by one so that new effect chain is created on new thread with
7282 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007283 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007284 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007285 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007286 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7287 while (effect != 0) {
7288 srcThread->removeEffect_l(effect);
7289 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007290 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7291 if (effect->state() == EffectModule::ACTIVE ||
7292 effect->state() == EffectModule::STOPPING) {
7293 effect->start();
7294 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007295 // if the move request is not received from audio policy manager, the effect must be
7296 // re-registered with the new strategy and output
7297 if (dstChain == 0) {
7298 dstChain = effect->chain().promote();
7299 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007300 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007301 srcThread->addEffect_l(effect);
7302 return NO_INIT;
7303 }
7304 strategy = dstChain->strategy();
7305 }
7306 if (reRegister) {
7307 AudioSystem::unregisterEffect(effect->id());
7308 AudioSystem::registerEffect(&effect->desc(),
7309 dstOutput,
7310 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007311 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007312 effect->id());
7313 }
Eric Laurentde070132010-07-13 04:45:46 -07007314 effect = chain->getEffectFromId_l(0);
7315 }
7316
7317 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318}
7319
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007320
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007322sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323 const sp<AudioFlinger::Client>& client,
7324 const sp<IEffectClient>& effectClient,
7325 int32_t priority,
7326 int sessionId,
7327 effect_descriptor_t *desc,
7328 int *enabled,
7329 status_t *status
7330 )
7331{
7332 sp<EffectModule> effect;
7333 sp<EffectHandle> handle;
7334 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007336 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 bool effectCreated = false;
7338 bool effectRegistered = false;
7339
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007340 lStatus = initCheck();
7341 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007342 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 goto Exit;
7344 }
7345
7346 // Do not allow effects with session ID 0 on direct output or duplicating threads
7347 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007348 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007349 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007350 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351 lStatus = BAD_VALUE;
7352 goto Exit;
7353 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007354 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007355 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007356 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007357 desc->name, desc->flags, mType);
7358 lStatus = BAD_VALUE;
7359 goto Exit;
7360 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361
Steve Block3856b092011-10-20 11:56:00 +01007362 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363
7364 { // scope for mLock
7365 Mutex::Autolock _l(mLock);
7366
7367 // check for existing effect chain with the requested audio session
7368 chain = getEffectChain_l(sessionId);
7369 if (chain == 0) {
7370 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007371 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 chain = new EffectChain(this, sessionId);
7373 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007374 chain->setStrategy(getStrategyForSession_l(sessionId));
7375 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007377 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 }
7379
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007380 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381
7382 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007383 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007385 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386 if (lStatus != NO_ERROR) {
7387 goto Exit;
7388 }
7389 effectRegistered = true;
7390 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007391 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 lStatus = effect->status();
7393 if (lStatus != NO_ERROR) {
7394 goto Exit;
7395 }
Eric Laurentcab11242010-07-15 12:50:15 -07007396 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 if (lStatus != NO_ERROR) {
7398 goto Exit;
7399 }
7400 effectCreated = true;
7401
7402 effect->setDevice(mDevice);
7403 effect->setMode(mAudioFlinger->getMode());
7404 }
7405 // create effect handle and connect it to effect module
7406 handle = new EffectHandle(effect, client, effectClient, priority);
7407 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007408 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409 *enabled = (int)effect->isEnabled();
7410 }
7411 }
7412
7413Exit:
7414 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007415 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007417 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007418 }
7419 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007420 AudioSystem::unregisterEffect(effect->id());
7421 }
7422 if (chainCreated) {
7423 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 }
7425 handle.clear();
7426 }
7427
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007428 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 *status = lStatus;
7430 }
7431 return handle;
7432}
7433
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007434sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7435{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007436 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007437 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007438}
7439
Eric Laurentde070132010-07-13 04:45:46 -07007440// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7441// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007442status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007443{
7444 // check for existing effect chain with the requested audio session
7445 int sessionId = effect->sessionId();
7446 sp<EffectChain> chain = getEffectChain_l(sessionId);
7447 bool chainCreated = false;
7448
7449 if (chain == 0) {
7450 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007451 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007452 chain = new EffectChain(this, sessionId);
7453 addEffectChain_l(chain);
7454 chain->setStrategy(getStrategyForSession_l(sessionId));
7455 chainCreated = true;
7456 }
Steve Block3856b092011-10-20 11:56:00 +01007457 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007458
7459 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007460 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007461 this, effect->desc().name, chain.get());
7462 return BAD_VALUE;
7463 }
7464
7465 status_t status = chain->addEffect_l(effect);
7466 if (status != NO_ERROR) {
7467 if (chainCreated) {
7468 removeEffectChain_l(chain);
7469 }
7470 return status;
7471 }
7472
7473 effect->setDevice(mDevice);
7474 effect->setMode(mAudioFlinger->getMode());
7475 return NO_ERROR;
7476}
7477
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007478void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007479
Steve Block3856b092011-10-20 11:56:00 +01007480 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007482 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7483 detachAuxEffect_l(effect->id());
7484 }
7485
7486 sp<EffectChain> chain = effect->chain().promote();
7487 if (chain != 0) {
7488 // remove effect chain if removing last effect
7489 if (chain->removeEffect_l(effect) == 0) {
7490 removeEffectChain_l(chain);
7491 }
7492 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007493 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007494 }
7495}
7496
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007497void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007498 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007499{
7500 effectChains = mEffectChains;
7501 for (size_t i = 0; i < mEffectChains.size(); i++) {
7502 mEffectChains[i]->lock();
7503 }
7504}
7505
7506void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007507 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007508{
7509 for (size_t i = 0; i < effectChains.size(); i++) {
7510 effectChains[i]->unlock();
7511 }
7512}
7513
7514sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7515{
7516 Mutex::Autolock _l(mLock);
7517 return getEffectChain_l(sessionId);
7518}
7519
7520sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7521{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007522 size_t size = mEffectChains.size();
7523 for (size_t i = 0; i < size; i++) {
7524 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007525 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007526 }
7527 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007528 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007529}
7530
Glenn Kastenf78aee72012-01-04 11:00:47 -08007531void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007532{
7533 Mutex::Autolock _l(mLock);
7534 size_t size = mEffectChains.size();
7535 for (size_t i = 0; i < size; i++) {
7536 mEffectChains[i]->setMode_l(mode);
7537 }
7538}
7539
7540void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007541 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007542 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007543
Mathias Agopian65ab4712010-07-14 17:59:35 -07007544 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007545 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007546 // delete the effect module if removing last handle on it
7547 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007548 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007549 removeEffect_l(effect);
7550 AudioSystem::unregisterEffect(effect->id());
7551 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007552 }
7553}
7554
7555status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7556{
7557 int session = chain->sessionId();
7558 int16_t *buffer = mMixBuffer;
7559 bool ownsBuffer = false;
7560
Steve Block3856b092011-10-20 11:56:00 +01007561 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007562 if (session > 0) {
7563 // Only one effect chain can be present in direct output thread and it uses
7564 // the mix buffer as input
7565 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007566 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 buffer = new int16_t[numSamples];
7568 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007569 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007570 ownsBuffer = true;
7571 }
7572
7573 // Attach all tracks with same session ID to this chain.
7574 for (size_t i = 0; i < mTracks.size(); ++i) {
7575 sp<Track> track = mTracks[i];
7576 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007577 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007579 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007580 }
7581 }
7582
7583 // indicate all active tracks in the chain
7584 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7585 sp<Track> track = mActiveTracks[i].promote();
7586 if (track == 0) continue;
7587 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007588 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007589 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 }
7591 }
7592 }
7593
7594 chain->setInBuffer(buffer, ownsBuffer);
7595 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007596 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007597 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007598 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7599 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007601 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7602 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007603 // Effect chain for other sessions are inserted at beginning of effect
7604 // chains list to be processed before output mix effects. Relative order between other
7605 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 size_t size = mEffectChains.size();
7607 size_t i = 0;
7608 for (i = 0; i < size; i++) {
7609 if (mEffectChains[i]->sessionId() < session) break;
7610 }
7611 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007612 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613
7614 return NO_ERROR;
7615}
7616
7617size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7618{
7619 int session = chain->sessionId();
7620
Steve Block3856b092011-10-20 11:56:00 +01007621 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622
7623 for (size_t i = 0; i < mEffectChains.size(); i++) {
7624 if (chain == mEffectChains[i]) {
7625 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007626 // detach all active tracks from the chain
7627 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7628 sp<Track> track = mActiveTracks[i].promote();
7629 if (track == 0) continue;
7630 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007631 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007632 chain.get(), session);
7633 chain->decActiveTrackCnt();
7634 }
7635 }
7636
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 // detach all tracks with same session ID from this chain
7638 for (size_t i = 0; i < mTracks.size(); ++i) {
7639 sp<Track> track = mTracks[i];
7640 if (session == track->sessionId()) {
7641 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007642 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643 }
7644 }
Eric Laurentde070132010-07-13 04:45:46 -07007645 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007646 }
7647 }
7648 return mEffectChains.size();
7649}
7650
Eric Laurentde070132010-07-13 04:45:46 -07007651status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7652 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007653{
7654 Mutex::Autolock _l(mLock);
7655 return attachAuxEffect_l(track, EffectId);
7656}
7657
Eric Laurentde070132010-07-13 04:45:46 -07007658status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7659 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007660{
7661 status_t status = NO_ERROR;
7662
7663 if (EffectId == 0) {
7664 track->setAuxBuffer(0, NULL);
7665 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007666 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7667 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007668 if (effect != 0) {
7669 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7670 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7671 } else {
7672 status = INVALID_OPERATION;
7673 }
7674 } else {
7675 status = BAD_VALUE;
7676 }
7677 }
7678 return status;
7679}
7680
7681void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7682{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007683 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007684 sp<Track> track = mTracks[i];
7685 if (track->auxEffectId() == effectId) {
7686 attachAuxEffect_l(track, 0);
7687 }
7688 }
7689}
7690
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007691status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7692{
7693 // only one chain per input thread
7694 if (mEffectChains.size() != 0) {
7695 return INVALID_OPERATION;
7696 }
Steve Block3856b092011-10-20 11:56:00 +01007697 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007698
7699 chain->setInBuffer(NULL);
7700 chain->setOutBuffer(NULL);
7701
Eric Laurent59255e42011-07-27 19:49:51 -07007702 checkSuspendOnAddEffectChain_l(chain);
7703
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007704 mEffectChains.add(chain);
7705
7706 return NO_ERROR;
7707}
7708
7709size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7710{
Steve Block3856b092011-10-20 11:56:00 +01007711 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007712 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007713 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7714 chain.get(), mEffectChains.size(), this);
7715 if (mEffectChains.size() == 1) {
7716 mEffectChains.removeAt(0);
7717 }
7718 return 0;
7719}
7720
Mathias Agopian65ab4712010-07-14 17:59:35 -07007721// ----------------------------------------------------------------------------
7722// EffectModule implementation
7723// ----------------------------------------------------------------------------
7724
7725#undef LOG_TAG
7726#define LOG_TAG "AudioFlinger::EffectModule"
7727
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007728AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729 const wp<AudioFlinger::EffectChain>& chain,
7730 effect_descriptor_t *desc,
7731 int id,
7732 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007733 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007734 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007735{
Steve Block3856b092011-10-20 11:56:00 +01007736 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007737 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007738 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007739 return;
7740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007741
7742 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7743
7744 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007745 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746
7747 if (mStatus != NO_ERROR) {
7748 return;
7749 }
7750 lStatus = init();
7751 if (lStatus < 0) {
7752 mStatus = lStatus;
7753 goto Error;
7754 }
7755
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007756 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7757 mPinned = true;
7758 }
Steve Block3856b092011-10-20 11:56:00 +01007759 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760 return;
7761Error:
7762 EffectRelease(mEffectInterface);
7763 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007764 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007765}
7766
7767AudioFlinger::EffectModule::~EffectModule()
7768{
Steve Block3856b092011-10-20 11:56:00 +01007769 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007771 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7772 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7773 sp<ThreadBase> thread = mThread.promote();
7774 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007775 audio_stream_t *stream = thread->stream();
7776 if (stream != NULL) {
7777 stream->remove_audio_effect(stream, mEffectInterface);
7778 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007779 }
7780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781 // release effect engine
7782 EffectRelease(mEffectInterface);
7783 }
7784}
7785
Glenn Kasten435dbe62012-01-30 10:15:48 -08007786status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007787{
7788 status_t status;
7789
7790 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 int priority = handle->priority();
7792 size_t size = mHandles.size();
7793 sp<EffectHandle> h;
7794 size_t i;
7795 for (i = 0; i < size; i++) {
7796 h = mHandles[i].promote();
7797 if (h == 0) continue;
7798 if (h->priority() <= priority) break;
7799 }
7800 // if inserted in first place, move effect control from previous owner to this handle
7801 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007802 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007804 enabled = h->enabled();
7805 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 }
Eric Laurent59255e42011-07-27 19:49:51 -07007807 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007808 status = NO_ERROR;
7809 } else {
7810 status = ALREADY_EXISTS;
7811 }
Steve Block3856b092011-10-20 11:56:00 +01007812 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007813 mHandles.insertAt(handle, i);
7814 return status;
7815}
7816
7817size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7818{
7819 Mutex::Autolock _l(mLock);
7820 size_t size = mHandles.size();
7821 size_t i;
7822 for (i = 0; i < size; i++) {
7823 if (mHandles[i] == handle) break;
7824 }
7825 if (i == size) {
7826 return size;
7827 }
Steve Block3856b092011-10-20 11:56:00 +01007828 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007829
7830 bool enabled = false;
7831 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007832 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007833 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007834 enabled = hdl->enabled();
7835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836 mHandles.removeAt(i);
7837 size = mHandles.size();
7838 // if removed from first place, move effect control from this handle to next in line
7839 if (i == 0 && size != 0) {
7840 sp<EffectHandle> h = mHandles[0].promote();
7841 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007842 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007843 }
7844 }
7845
Eric Laurentec437d82011-07-26 20:54:46 -07007846 // Prevent calls to process() and other functions on effect interface from now on.
7847 // The effect engine will be released by the destructor when the last strong reference on
7848 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007849 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007850 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007851 }
7852
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853 return size;
7854}
7855
Eric Laurent59255e42011-07-27 19:49:51 -07007856sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7857{
7858 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007859 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007860}
7861
Glenn Kasten58123c32012-02-03 10:32:24 -08007862void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007864 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 // keep a strong reference on this EffectModule to avoid calling the
7866 // destructor before we exit
7867 sp<EffectModule> keep(this);
7868 {
7869 sp<ThreadBase> thread = mThread.promote();
7870 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007871 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872 }
7873 }
7874}
7875
7876void AudioFlinger::EffectModule::updateState() {
7877 Mutex::Autolock _l(mLock);
7878
7879 switch (mState) {
7880 case RESTART:
7881 reset_l();
7882 // FALL THROUGH
7883
7884 case STARTING:
7885 // clear auxiliary effect input buffer for next accumulation
7886 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7887 memset(mConfig.inputCfg.buffer.raw,
7888 0,
7889 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7890 }
7891 start_l();
7892 mState = ACTIVE;
7893 break;
7894 case STOPPING:
7895 stop_l();
7896 mDisableWaitCnt = mMaxDisableWaitCnt;
7897 mState = STOPPED;
7898 break;
7899 case STOPPED:
7900 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7901 // turn off sequence.
7902 if (--mDisableWaitCnt == 0) {
7903 reset_l();
7904 mState = IDLE;
7905 }
7906 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007907 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908 break;
7909 }
7910}
7911
7912void AudioFlinger::EffectModule::process()
7913{
7914 Mutex::Autolock _l(mLock);
7915
Eric Laurentec437d82011-07-26 20:54:46 -07007916 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007917 mConfig.inputCfg.buffer.raw == NULL ||
7918 mConfig.outputCfg.buffer.raw == NULL) {
7919 return;
7920 }
7921
Eric Laurent8f45bd72010-08-31 13:50:07 -07007922 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007923 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7924 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007925 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007926 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007927 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007928 }
7929
7930 // do the actual processing in the effect engine
7931 int ret = (*mEffectInterface)->process(mEffectInterface,
7932 &mConfig.inputCfg.buffer,
7933 &mConfig.outputCfg.buffer);
7934
7935 // force transition to IDLE state when engine is ready
7936 if (mState == STOPPED && ret == -ENODATA) {
7937 mDisableWaitCnt = 1;
7938 }
7939
7940 // clear auxiliary effect input buffer for next accumulation
7941 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007942 memset(mConfig.inputCfg.buffer.raw, 0,
7943 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 }
7945 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007946 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7947 // If an insert effect is idle and input buffer is different from output buffer,
7948 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007950 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007951 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7952 int16_t *in = mConfig.inputCfg.buffer.s16;
7953 int16_t *out = mConfig.outputCfg.buffer.s16;
7954 for (size_t i = 0; i < frameCnt; i++) {
7955 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007957 }
7958 }
7959}
7960
7961void AudioFlinger::EffectModule::reset_l()
7962{
7963 if (mEffectInterface == NULL) {
7964 return;
7965 }
7966 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7967}
7968
7969status_t AudioFlinger::EffectModule::configure()
7970{
7971 uint32_t channels;
7972 if (mEffectInterface == NULL) {
7973 return NO_INIT;
7974 }
7975
7976 sp<ThreadBase> thread = mThread.promote();
7977 if (thread == 0) {
7978 return DEAD_OBJECT;
7979 }
7980
7981 // TODO: handle configuration of effects replacing track process
7982 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007983 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007985 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007986 }
7987
7988 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007989 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990 } else {
7991 mConfig.inputCfg.channels = channels;
7992 }
7993 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007994 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7995 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996 mConfig.inputCfg.samplingRate = thread->sampleRate();
7997 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7998 mConfig.inputCfg.bufferProvider.cookie = NULL;
7999 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8000 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8001 mConfig.outputCfg.bufferProvider.cookie = NULL;
8002 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8003 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8004 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8005 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008006 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008007 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008008 // - in other sessions:
8009 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8010 // other effect: overwrites output buffer: input buffer == output buffer
8011 // Auxiliary effect:
8012 // accumulates in output buffer: input buffer != output buffer
8013 // Therefore: accumulate <=> input buffer != output buffer
8014 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8015 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8016 } else {
8017 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8018 }
8019 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8020 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8021 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8022 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8023
Steve Block3856b092011-10-20 11:56:00 +01008024 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008025 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8026
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008028 uint32_t size = sizeof(int);
8029 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008030 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008031 sizeof(effect_config_t),
8032 &mConfig,
8033 &size,
8034 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008035 if (status == 0) {
8036 status = cmdStatus;
8037 }
8038
8039 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8040 (1000 * mConfig.outputCfg.buffer.frameCount);
8041
8042 return status;
8043}
8044
8045status_t AudioFlinger::EffectModule::init()
8046{
8047 Mutex::Autolock _l(mLock);
8048 if (mEffectInterface == NULL) {
8049 return NO_INIT;
8050 }
8051 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008052 uint32_t size = sizeof(status_t);
8053 status_t status = (*mEffectInterface)->command(mEffectInterface,
8054 EFFECT_CMD_INIT,
8055 0,
8056 NULL,
8057 &size,
8058 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059 if (status == 0) {
8060 status = cmdStatus;
8061 }
8062 return status;
8063}
8064
Eric Laurentec35a142011-10-05 17:42:25 -07008065status_t AudioFlinger::EffectModule::start()
8066{
8067 Mutex::Autolock _l(mLock);
8068 return start_l();
8069}
8070
Mathias Agopian65ab4712010-07-14 17:59:35 -07008071status_t AudioFlinger::EffectModule::start_l()
8072{
8073 if (mEffectInterface == NULL) {
8074 return NO_INIT;
8075 }
8076 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008077 uint32_t size = sizeof(status_t);
8078 status_t status = (*mEffectInterface)->command(mEffectInterface,
8079 EFFECT_CMD_ENABLE,
8080 0,
8081 NULL,
8082 &size,
8083 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084 if (status == 0) {
8085 status = cmdStatus;
8086 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008087 if (status == 0 &&
8088 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8089 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8090 sp<ThreadBase> thread = mThread.promote();
8091 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008092 audio_stream_t *stream = thread->stream();
8093 if (stream != NULL) {
8094 stream->add_audio_effect(stream, mEffectInterface);
8095 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008096 }
8097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098 return status;
8099}
8100
Eric Laurentec437d82011-07-26 20:54:46 -07008101status_t AudioFlinger::EffectModule::stop()
8102{
8103 Mutex::Autolock _l(mLock);
8104 return stop_l();
8105}
8106
Mathias Agopian65ab4712010-07-14 17:59:35 -07008107status_t AudioFlinger::EffectModule::stop_l()
8108{
8109 if (mEffectInterface == NULL) {
8110 return NO_INIT;
8111 }
8112 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008113 uint32_t size = sizeof(status_t);
8114 status_t status = (*mEffectInterface)->command(mEffectInterface,
8115 EFFECT_CMD_DISABLE,
8116 0,
8117 NULL,
8118 &size,
8119 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120 if (status == 0) {
8121 status = cmdStatus;
8122 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008123 if (status == 0 &&
8124 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8125 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8126 sp<ThreadBase> thread = mThread.promote();
8127 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008128 audio_stream_t *stream = thread->stream();
8129 if (stream != NULL) {
8130 stream->remove_audio_effect(stream, mEffectInterface);
8131 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008132 }
8133 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008134 return status;
8135}
8136
Eric Laurent25f43952010-07-28 05:40:18 -07008137status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8138 uint32_t cmdSize,
8139 void *pCmdData,
8140 uint32_t *replySize,
8141 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008142{
8143 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008144// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008145
Eric Laurentec437d82011-07-26 20:54:46 -07008146 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008147 return NO_INIT;
8148 }
Eric Laurent25f43952010-07-28 05:40:18 -07008149 status_t status = (*mEffectInterface)->command(mEffectInterface,
8150 cmdCode,
8151 cmdSize,
8152 pCmdData,
8153 replySize,
8154 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008156 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157 for (size_t i = 1; i < mHandles.size(); i++) {
8158 sp<EffectHandle> h = mHandles[i].promote();
8159 if (h != 0) {
8160 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8161 }
8162 }
8163 }
8164 return status;
8165}
8166
8167status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8168{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008169
Mathias Agopian65ab4712010-07-14 17:59:35 -07008170 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008171 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172
8173 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008174 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8175 if (enabled && status != NO_ERROR) {
8176 return status;
8177 }
8178
Mathias Agopian65ab4712010-07-14 17:59:35 -07008179 switch (mState) {
8180 // going from disabled to enabled
8181 case IDLE:
8182 mState = STARTING;
8183 break;
8184 case STOPPED:
8185 mState = RESTART;
8186 break;
8187 case STOPPING:
8188 mState = ACTIVE;
8189 break;
8190
8191 // going from enabled to disabled
8192 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008193 mState = STOPPED;
8194 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195 case STARTING:
8196 mState = IDLE;
8197 break;
8198 case ACTIVE:
8199 mState = STOPPING;
8200 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008201 case DESTROYED:
8202 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008203 }
8204 for (size_t i = 1; i < mHandles.size(); i++) {
8205 sp<EffectHandle> h = mHandles[i].promote();
8206 if (h != 0) {
8207 h->setEnabled(enabled);
8208 }
8209 }
8210 }
8211 return NO_ERROR;
8212}
8213
Glenn Kastenc59c0042012-02-02 14:06:11 -08008214bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215{
8216 switch (mState) {
8217 case RESTART:
8218 case STARTING:
8219 case ACTIVE:
8220 return true;
8221 case IDLE:
8222 case STOPPING:
8223 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008224 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008225 default:
8226 return false;
8227 }
8228}
8229
Glenn Kastenc59c0042012-02-02 14:06:11 -08008230bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008231{
8232 switch (mState) {
8233 case RESTART:
8234 case ACTIVE:
8235 case STOPPING:
8236 case STOPPED:
8237 return true;
8238 case IDLE:
8239 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008240 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008241 default:
8242 return false;
8243 }
8244}
8245
Mathias Agopian65ab4712010-07-14 17:59:35 -07008246status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8247{
8248 Mutex::Autolock _l(mLock);
8249 status_t status = NO_ERROR;
8250
8251 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8252 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008253 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008254 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8255 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256 status_t cmdStatus;
8257 uint32_t volume[2];
8258 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008259 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008260 volume[0] = *left;
8261 volume[1] = *right;
8262 if (controller) {
8263 pVolume = volume;
8264 }
Eric Laurent25f43952010-07-28 05:40:18 -07008265 status = (*mEffectInterface)->command(mEffectInterface,
8266 EFFECT_CMD_SET_VOLUME,
8267 size,
8268 volume,
8269 &size,
8270 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8272 *left = volume[0];
8273 *right = volume[1];
8274 }
8275 }
8276 return status;
8277}
8278
8279status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8280{
8281 Mutex::Autolock _l(mLock);
8282 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008283 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8284 // audio pre processing modules on RecordThread can receive both output and
8285 // input device indication in the same call
8286 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8287 if (dev) {
8288 status_t cmdStatus;
8289 uint32_t size = sizeof(status_t);
8290
8291 status = (*mEffectInterface)->command(mEffectInterface,
8292 EFFECT_CMD_SET_DEVICE,
8293 sizeof(uint32_t),
8294 &dev,
8295 &size,
8296 &cmdStatus);
8297 if (status == NO_ERROR) {
8298 status = cmdStatus;
8299 }
8300 }
8301 dev = device & AUDIO_DEVICE_IN_ALL;
8302 if (dev) {
8303 status_t cmdStatus;
8304 uint32_t size = sizeof(status_t);
8305
8306 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8307 EFFECT_CMD_SET_INPUT_DEVICE,
8308 sizeof(uint32_t),
8309 &dev,
8310 &size,
8311 &cmdStatus);
8312 if (status2 == NO_ERROR) {
8313 status2 = cmdStatus;
8314 }
8315 if (status == NO_ERROR) {
8316 status = status2;
8317 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008318 }
8319 }
8320 return status;
8321}
8322
Glenn Kastenf78aee72012-01-04 11:00:47 -08008323status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008324{
8325 Mutex::Autolock _l(mLock);
8326 status_t status = NO_ERROR;
8327 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008328 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008329 uint32_t size = sizeof(status_t);
8330 status = (*mEffectInterface)->command(mEffectInterface,
8331 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008332 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008333 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008334 &size,
8335 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 if (status == NO_ERROR) {
8337 status = cmdStatus;
8338 }
8339 }
8340 return status;
8341}
8342
Eric Laurent59255e42011-07-27 19:49:51 -07008343void AudioFlinger::EffectModule::setSuspended(bool suspended)
8344{
8345 Mutex::Autolock _l(mLock);
8346 mSuspended = suspended;
8347}
Glenn Kastena3a85482012-01-04 11:01:11 -08008348
8349bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008350{
8351 Mutex::Autolock _l(mLock);
8352 return mSuspended;
8353}
8354
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8356{
8357 const size_t SIZE = 256;
8358 char buffer[SIZE];
8359 String8 result;
8360
8361 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8362 result.append(buffer);
8363
8364 bool locked = tryLock(mLock);
8365 // failed to lock - AudioFlinger is probably deadlocked
8366 if (!locked) {
8367 result.append("\t\tCould not lock Fx mutex:\n");
8368 }
8369
8370 result.append("\t\tSession Status State Engine:\n");
8371 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8372 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8373 result.append(buffer);
8374
8375 result.append("\t\tDescriptor:\n");
8376 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8377 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8378 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8379 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8380 result.append(buffer);
8381 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8382 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8383 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8384 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8385 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008386 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 mDescriptor.apiVersion,
8388 mDescriptor.flags);
8389 result.append(buffer);
8390 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8391 mDescriptor.name);
8392 result.append(buffer);
8393 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8394 mDescriptor.implementor);
8395 result.append(buffer);
8396
8397 result.append("\t\t- Input configuration:\n");
8398 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8399 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8400 (uint32_t)mConfig.inputCfg.buffer.raw,
8401 mConfig.inputCfg.buffer.frameCount,
8402 mConfig.inputCfg.samplingRate,
8403 mConfig.inputCfg.channels,
8404 mConfig.inputCfg.format);
8405 result.append(buffer);
8406
8407 result.append("\t\t- Output configuration:\n");
8408 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8409 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8410 (uint32_t)mConfig.outputCfg.buffer.raw,
8411 mConfig.outputCfg.buffer.frameCount,
8412 mConfig.outputCfg.samplingRate,
8413 mConfig.outputCfg.channels,
8414 mConfig.outputCfg.format);
8415 result.append(buffer);
8416
8417 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8418 result.append(buffer);
8419 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8420 for (size_t i = 0; i < mHandles.size(); ++i) {
8421 sp<EffectHandle> handle = mHandles[i].promote();
8422 if (handle != 0) {
8423 handle->dump(buffer, SIZE);
8424 result.append(buffer);
8425 }
8426 }
8427
8428 result.append("\n");
8429
8430 write(fd, result.string(), result.length());
8431
8432 if (locked) {
8433 mLock.unlock();
8434 }
8435
8436 return NO_ERROR;
8437}
8438
8439// ----------------------------------------------------------------------------
8440// EffectHandle implementation
8441// ----------------------------------------------------------------------------
8442
8443#undef LOG_TAG
8444#define LOG_TAG "AudioFlinger::EffectHandle"
8445
8446AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8447 const sp<AudioFlinger::Client>& client,
8448 const sp<IEffectClient>& effectClient,
8449 int32_t priority)
8450 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008451 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008452 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008453{
Steve Block3856b092011-10-20 11:56:00 +01008454 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008456 if (client == 0) {
8457 return;
8458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008459 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8460 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8461 if (mCblkMemory != 0) {
8462 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8463
Glenn Kastena0d68332012-01-27 16:47:15 -08008464 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465 new(mCblk) effect_param_cblk_t();
8466 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008468 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008469 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470 return;
8471 }
8472}
8473
8474AudioFlinger::EffectHandle::~EffectHandle()
8475{
Steve Block3856b092011-10-20 11:56:00 +01008476 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008477 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008478 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008479}
8480
8481status_t AudioFlinger::EffectHandle::enable()
8482{
Steve Block3856b092011-10-20 11:56:00 +01008483 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008484 if (!mHasControl) return INVALID_OPERATION;
8485 if (mEffect == 0) return DEAD_OBJECT;
8486
Eric Laurentdb7c0792011-08-10 10:37:50 -07008487 if (mEnabled) {
8488 return NO_ERROR;
8489 }
8490
Eric Laurent59255e42011-07-27 19:49:51 -07008491 mEnabled = true;
8492
8493 sp<ThreadBase> thread = mEffect->thread().promote();
8494 if (thread != 0) {
8495 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8496 }
8497
8498 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8499 if (mEffect->suspended()) {
8500 return NO_ERROR;
8501 }
8502
Eric Laurentdb7c0792011-08-10 10:37:50 -07008503 status_t status = mEffect->setEnabled(true);
8504 if (status != NO_ERROR) {
8505 if (thread != 0) {
8506 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8507 }
8508 mEnabled = false;
8509 }
8510 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511}
8512
8513status_t AudioFlinger::EffectHandle::disable()
8514{
Steve Block3856b092011-10-20 11:56:00 +01008515 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008516 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008517 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518
Eric Laurentdb7c0792011-08-10 10:37:50 -07008519 if (!mEnabled) {
8520 return NO_ERROR;
8521 }
Eric Laurent59255e42011-07-27 19:49:51 -07008522 mEnabled = false;
8523
8524 if (mEffect->suspended()) {
8525 return NO_ERROR;
8526 }
8527
8528 status_t status = mEffect->setEnabled(false);
8529
8530 sp<ThreadBase> thread = mEffect->thread().promote();
8531 if (thread != 0) {
8532 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8533 }
8534
8535 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008536}
8537
8538void AudioFlinger::EffectHandle::disconnect()
8539{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008540 disconnect(true);
8541}
8542
Glenn Kasten58123c32012-02-03 10:32:24 -08008543void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008544{
Glenn Kasten58123c32012-02-03 10:32:24 -08008545 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008546 if (mEffect == 0) {
8547 return;
8548 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008549 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008550
Eric Laurenta85a74a2011-10-19 11:44:54 -07008551 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008552 sp<ThreadBase> thread = mEffect->thread().promote();
8553 if (thread != 0) {
8554 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8555 }
Eric Laurent59255e42011-07-27 19:49:51 -07008556 }
8557
Mathias Agopian65ab4712010-07-14 17:59:35 -07008558 // release sp on module => module destructor can be called now
8559 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008561 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008562 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008563 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8564 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008565 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008566 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008567 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8568 mClient.clear();
8569 }
8570}
8571
Eric Laurent25f43952010-07-28 05:40:18 -07008572status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8573 uint32_t cmdSize,
8574 void *pCmdData,
8575 uint32_t *replySize,
8576 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008577{
Steve Block3856b092011-10-20 11:56:00 +01008578// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008579// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008580
8581 // only get parameter command is permitted for applications not controlling the effect
8582 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8583 return INVALID_OPERATION;
8584 }
8585 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008586 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008587
8588 // handle commands that are not forwarded transparently to effect engine
8589 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8590 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8591 // no risk to block the whole media server process or mixer threads is we are stuck here
8592 Mutex::Autolock _l(mCblk->lock);
8593 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8594 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8595 mCblk->serverIndex = 0;
8596 mCblk->clientIndex = 0;
8597 return BAD_VALUE;
8598 }
8599 status_t status = NO_ERROR;
8600 while (mCblk->serverIndex < mCblk->clientIndex) {
8601 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008602 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008603 int *p = (int *)(mBuffer + mCblk->serverIndex);
8604 int size = *p++;
8605 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008606 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008607 break;
8608 }
8609 effect_param_t *param = (effect_param_t *)p;
8610 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008611 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612 mCblk->serverIndex += size;
8613 continue;
8614 }
Eric Laurent25f43952010-07-28 05:40:18 -07008615 uint32_t psize = sizeof(effect_param_t) +
8616 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8617 param->vsize;
8618 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8619 psize,
8620 p,
8621 &rsize,
8622 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008623 // stop at first error encountered
8624 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008626 *(int *)pReplyData = reply;
8627 break;
8628 } else if (reply != NO_ERROR) {
8629 *(int *)pReplyData = reply;
8630 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008631 }
8632 mCblk->serverIndex += size;
8633 }
8634 mCblk->serverIndex = 0;
8635 mCblk->clientIndex = 0;
8636 return status;
8637 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008638 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008639 return enable();
8640 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008641 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008642 return disable();
8643 }
8644
8645 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8646}
8647
Eric Laurent59255e42011-07-27 19:49:51 -07008648void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008649{
Steve Block3856b092011-10-20 11:56:00 +01008650 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651
8652 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008653 mEnabled = enabled;
8654
Mathias Agopian65ab4712010-07-14 17:59:35 -07008655 if (signal && mEffectClient != 0) {
8656 mEffectClient->controlStatusChanged(hasControl);
8657 }
8658}
8659
Eric Laurent25f43952010-07-28 05:40:18 -07008660void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8661 uint32_t cmdSize,
8662 void *pCmdData,
8663 uint32_t replySize,
8664 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008665{
8666 if (mEffectClient != 0) {
8667 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8668 }
8669}
8670
8671
8672
8673void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8674{
8675 if (mEffectClient != 0) {
8676 mEffectClient->enableStatusChanged(enabled);
8677 }
8678}
8679
8680status_t AudioFlinger::EffectHandle::onTransact(
8681 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8682{
8683 return BnEffect::onTransact(code, data, reply, flags);
8684}
8685
8686
8687void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8688{
Glenn Kastena0d68332012-01-27 16:47:15 -08008689 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690
8691 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008692 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008693 mPriority,
8694 mHasControl,
8695 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008696 mCblk ? mCblk->clientIndex : 0,
8697 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008698 );
8699
8700 if (locked) {
8701 mCblk->lock.unlock();
8702 }
8703}
8704
8705#undef LOG_TAG
8706#define LOG_TAG "AudioFlinger::EffectChain"
8707
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008708AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008709 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008710 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008711 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8712 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008713{
Dima Zavinfce7a472011-04-19 22:30:36 -07008714 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008715 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008716 return;
8717 }
8718 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8719 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008720}
8721
8722AudioFlinger::EffectChain::~EffectChain()
8723{
8724 if (mOwnInBuffer) {
8725 delete mInBuffer;
8726 }
8727
8728}
8729
Eric Laurent59255e42011-07-27 19:49:51 -07008730// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008731sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008732{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008733 size_t size = mEffects.size();
8734
8735 for (size_t i = 0; i < size; i++) {
8736 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008737 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008738 }
8739 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008740 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008741}
8742
Eric Laurent59255e42011-07-27 19:49:51 -07008743// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008744sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008745{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746 size_t size = mEffects.size();
8747
8748 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008749 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8750 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008751 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752 }
8753 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008754 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755}
8756
Eric Laurent59255e42011-07-27 19:49:51 -07008757// getEffectFromType_l() must be called with ThreadBase::mLock held
8758sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8759 const effect_uuid_t *type)
8760{
Eric Laurent59255e42011-07-27 19:49:51 -07008761 size_t size = mEffects.size();
8762
8763 for (size_t i = 0; i < size; i++) {
8764 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008765 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008766 }
8767 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008768 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008769}
8770
Mathias Agopian65ab4712010-07-14 17:59:35 -07008771// Must be called with EffectChain::mLock locked
8772void AudioFlinger::EffectChain::process_l()
8773{
Eric Laurentdac69112010-09-28 14:09:57 -07008774 sp<ThreadBase> thread = mThread.promote();
8775 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008776 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008777 return;
8778 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008779 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8780 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008781 // always process effects unless no more tracks are on the session and the effect tail
8782 // has been rendered
8783 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008784 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008785 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008786
Eric Laurent544fe9b2011-11-11 15:42:52 -08008787 if (!tracksOnSession && mTailBufferCount == 0) {
8788 doProcess = false;
8789 }
8790
8791 if (activeTrackCnt() == 0) {
8792 // if no track is active and the effect tail has not been rendered,
8793 // the input buffer must be cleared here as the mixer process will not do it
8794 if (tracksOnSession || mTailBufferCount > 0) {
8795 size_t numSamples = thread->frameCount() * thread->channelCount();
8796 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8797 if (mTailBufferCount > 0) {
8798 mTailBufferCount--;
8799 }
8800 }
8801 }
Eric Laurentdac69112010-09-28 14:09:57 -07008802 }
8803
Mathias Agopian65ab4712010-07-14 17:59:35 -07008804 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008805 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008806 for (size_t i = 0; i < size; i++) {
8807 mEffects[i]->process();
8808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008809 }
8810 for (size_t i = 0; i < size; i++) {
8811 mEffects[i]->updateState();
8812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813}
8814
Eric Laurentcab11242010-07-15 12:50:15 -07008815// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008816status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008817{
8818 effect_descriptor_t desc = effect->desc();
8819 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8820
8821 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008822 effect->setChain(this);
8823 sp<ThreadBase> thread = mThread.promote();
8824 if (thread == 0) {
8825 return NO_INIT;
8826 }
8827 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008828
8829 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8830 // Auxiliary effects are inserted at the beginning of mEffects vector as
8831 // they are processed first and accumulated in chain input buffer
8832 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008833
Mathias Agopian65ab4712010-07-14 17:59:35 -07008834 // the input buffer for auxiliary effect contains mono samples in
8835 // 32 bit format. This is to avoid saturation in AudoMixer
8836 // accumulation stage. Saturation is done in EffectModule::process() before
8837 // calling the process in effect engine
8838 size_t numSamples = thread->frameCount();
8839 int32_t *buffer = new int32_t[numSamples];
8840 memset(buffer, 0, numSamples * sizeof(int32_t));
8841 effect->setInBuffer((int16_t *)buffer);
8842 // auxiliary effects output samples to chain input buffer for further processing
8843 // by insert effects
8844 effect->setOutBuffer(mInBuffer);
8845 } else {
8846 // Insert effects are inserted at the end of mEffects vector as they are processed
8847 // after track and auxiliary effects.
8848 // Insert effect order as a function of indicated preference:
8849 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8850 // another effect is present
8851 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8852 // last effect claiming first position
8853 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8854 // first effect claiming last position
8855 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8856 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8857 // already present
8858
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008859 size_t size = mEffects.size();
8860 size_t idx_insert = size;
8861 ssize_t idx_insert_first = -1;
8862 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008863
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008864 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008865 effect_descriptor_t d = mEffects[i]->desc();
8866 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8867 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8868 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8869 // check invalid effect chaining combinations
8870 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8871 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008872 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008873 return INVALID_OPERATION;
8874 }
8875 // remember position of first insert effect and by default
8876 // select this as insert position for new effect
8877 if (idx_insert == size) {
8878 idx_insert = i;
8879 }
8880 // remember position of last insert effect claiming
8881 // first position
8882 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8883 idx_insert_first = i;
8884 }
8885 // remember position of first insert effect claiming
8886 // last position
8887 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8888 idx_insert_last == -1) {
8889 idx_insert_last = i;
8890 }
8891 }
8892 }
8893
8894 // modify idx_insert from first position if needed
8895 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8896 if (idx_insert_last != -1) {
8897 idx_insert = idx_insert_last;
8898 } else {
8899 idx_insert = size;
8900 }
8901 } else {
8902 if (idx_insert_first != -1) {
8903 idx_insert = idx_insert_first + 1;
8904 }
8905 }
8906
8907 // always read samples from chain input buffer
8908 effect->setInBuffer(mInBuffer);
8909
8910 // if last effect in the chain, output samples to chain
8911 // output buffer, otherwise to chain input buffer
8912 if (idx_insert == size) {
8913 if (idx_insert != 0) {
8914 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8915 mEffects[idx_insert-1]->configure();
8916 }
8917 effect->setOutBuffer(mOutBuffer);
8918 } else {
8919 effect->setOutBuffer(mInBuffer);
8920 }
8921 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922
Steve Block3856b092011-10-20 11:56:00 +01008923 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008924 }
8925 effect->configure();
8926 return NO_ERROR;
8927}
8928
Eric Laurentcab11242010-07-15 12:50:15 -07008929// removeEffect_l() must be called with PlaybackThread::mLock held
8930size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931{
8932 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008933 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008934 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8935
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008936 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008937 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008938 // calling stop here will remove pre-processing effect from the audio HAL.
8939 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8940 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008941 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8942 mEffects[i]->state() == EffectModule::STOPPING) {
8943 mEffects[i]->stop();
8944 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008945 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8946 delete[] effect->inBuffer();
8947 } else {
8948 if (i == size - 1 && i != 0) {
8949 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8950 mEffects[i - 1]->configure();
8951 }
8952 }
8953 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008954 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008955 break;
8956 }
8957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008958
8959 return mEffects.size();
8960}
8961
Eric Laurentcab11242010-07-15 12:50:15 -07008962// setDevice_l() must be called with PlaybackThread::mLock held
8963void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008964{
8965 size_t size = mEffects.size();
8966 for (size_t i = 0; i < size; i++) {
8967 mEffects[i]->setDevice(device);
8968 }
8969}
8970
Eric Laurentcab11242010-07-15 12:50:15 -07008971// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008972void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008973{
8974 size_t size = mEffects.size();
8975 for (size_t i = 0; i < size; i++) {
8976 mEffects[i]->setMode(mode);
8977 }
8978}
8979
Eric Laurentcab11242010-07-15 12:50:15 -07008980// setVolume_l() must be called with PlaybackThread::mLock held
8981bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008982{
8983 uint32_t newLeft = *left;
8984 uint32_t newRight = *right;
8985 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008986 int ctrlIdx = -1;
8987 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008988
Eric Laurentcab11242010-07-15 12:50:15 -07008989 // first update volume controller
8990 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008991 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008992 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8993 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008994 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008995 break;
8996 }
8997 }
8998
8999 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009000 if (hasControl) {
9001 *left = mNewLeftVolume;
9002 *right = mNewRightVolume;
9003 }
9004 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009005 }
9006
9007 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009008 mLeftVolume = newLeft;
9009 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009010
9011 // second get volume update from volume controller
9012 if (ctrlIdx >= 0) {
9013 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009014 mNewLeftVolume = newLeft;
9015 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016 }
9017 // then indicate volume to all other effects in chain.
9018 // Pass altered volume to effects before volume controller
9019 // and requested volume to effects after controller
9020 uint32_t lVol = newLeft;
9021 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009022
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009024 if ((int)i == ctrlIdx) continue;
9025 // this also works for ctrlIdx == -1 when there is no volume controller
9026 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027 lVol = *left;
9028 rVol = *right;
9029 }
9030 mEffects[i]->setVolume(&lVol, &rVol, false);
9031 }
9032 *left = newLeft;
9033 *right = newRight;
9034
9035 return hasControl;
9036}
9037
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9039{
9040 const size_t SIZE = 256;
9041 char buffer[SIZE];
9042 String8 result;
9043
9044 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9045 result.append(buffer);
9046
9047 bool locked = tryLock(mLock);
9048 // failed to lock - AudioFlinger is probably deadlocked
9049 if (!locked) {
9050 result.append("\tCould not lock mutex:\n");
9051 }
9052
Eric Laurentcab11242010-07-15 12:50:15 -07009053 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9054 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009055 mEffects.size(),
9056 (uint32_t)mInBuffer,
9057 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009058 mActiveTrackCnt);
9059 result.append(buffer);
9060 write(fd, result.string(), result.size());
9061
9062 for (size_t i = 0; i < mEffects.size(); ++i) {
9063 sp<EffectModule> effect = mEffects[i];
9064 if (effect != 0) {
9065 effect->dump(fd, args);
9066 }
9067 }
9068
9069 if (locked) {
9070 mLock.unlock();
9071 }
9072
9073 return NO_ERROR;
9074}
9075
Eric Laurent59255e42011-07-27 19:49:51 -07009076// must be called with ThreadBase::mLock held
9077void AudioFlinger::EffectChain::setEffectSuspended_l(
9078 const effect_uuid_t *type, bool suspend)
9079{
9080 sp<SuspendedEffectDesc> desc;
9081 // use effect type UUID timelow as key as there is no real risk of identical
9082 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009083 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009084 if (suspend) {
9085 if (index >= 0) {
9086 desc = mSuspendedEffects.valueAt(index);
9087 } else {
9088 desc = new SuspendedEffectDesc();
9089 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9090 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009091 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009092 }
9093 if (desc->mRefCount++ == 0) {
9094 sp<EffectModule> effect = getEffectIfEnabled(type);
9095 if (effect != 0) {
9096 desc->mEffect = effect;
9097 effect->setSuspended(true);
9098 effect->setEnabled(false);
9099 }
9100 }
9101 } else {
9102 if (index < 0) {
9103 return;
9104 }
9105 desc = mSuspendedEffects.valueAt(index);
9106 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009107 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009108 desc->mRefCount = 1;
9109 }
9110 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009111 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009112 if (desc->mEffect != 0) {
9113 sp<EffectModule> effect = desc->mEffect.promote();
9114 if (effect != 0) {
9115 effect->setSuspended(false);
9116 sp<EffectHandle> handle = effect->controlHandle();
9117 if (handle != 0) {
9118 effect->setEnabled(handle->enabled());
9119 }
9120 }
9121 desc->mEffect.clear();
9122 }
9123 mSuspendedEffects.removeItemsAt(index);
9124 }
9125 }
9126}
9127
9128// must be called with ThreadBase::mLock held
9129void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9130{
9131 sp<SuspendedEffectDesc> desc;
9132
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009133 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009134 if (suspend) {
9135 if (index >= 0) {
9136 desc = mSuspendedEffects.valueAt(index);
9137 } else {
9138 desc = new SuspendedEffectDesc();
9139 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009140 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009141 }
9142 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009143 Vector< sp<EffectModule> > effects;
9144 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009145 for (size_t i = 0; i < effects.size(); i++) {
9146 setEffectSuspended_l(&effects[i]->desc().type, true);
9147 }
9148 }
9149 } else {
9150 if (index < 0) {
9151 return;
9152 }
9153 desc = mSuspendedEffects.valueAt(index);
9154 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009155 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009156 desc->mRefCount = 1;
9157 }
9158 if (--desc->mRefCount == 0) {
9159 Vector<const effect_uuid_t *> types;
9160 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9161 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9162 continue;
9163 }
9164 types.add(&mSuspendedEffects.valueAt(i)->mType);
9165 }
9166 for (size_t i = 0; i < types.size(); i++) {
9167 setEffectSuspended_l(types[i], false);
9168 }
Steve Block3856b092011-10-20 11:56:00 +01009169 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009170 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9171 }
9172 }
9173}
9174
Eric Laurent6bffdb82011-09-23 08:40:41 -07009175
9176// The volume effect is used for automated tests only
9177#ifndef OPENSL_ES_H_
9178static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9179 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9180const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9181#endif //OPENSL_ES_H_
9182
Eric Laurentdb7c0792011-08-10 10:37:50 -07009183bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9184{
9185 // auxiliary effects and visualizer are never suspended on output mix
9186 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9187 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009188 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9189 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009190 return false;
9191 }
9192 return true;
9193}
9194
Glenn Kastend0539712012-01-30 12:56:03 -08009195void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009196{
Glenn Kastend0539712012-01-30 12:56:03 -08009197 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009198 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009199 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9200 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009201 }
Eric Laurent59255e42011-07-27 19:49:51 -07009202 }
Eric Laurent59255e42011-07-27 19:49:51 -07009203}
9204
9205sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9206 const effect_uuid_t *type)
9207{
Glenn Kasten090f0192012-01-30 13:00:02 -08009208 sp<EffectModule> effect = getEffectFromType_l(type);
9209 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009210}
9211
9212void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9213 bool enabled)
9214{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009215 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009216 if (enabled) {
9217 if (index < 0) {
9218 // if the effect is not suspend check if all effects are suspended
9219 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9220 if (index < 0) {
9221 return;
9222 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009223 if (!isEffectEligibleForSuspend(effect->desc())) {
9224 return;
9225 }
Eric Laurent59255e42011-07-27 19:49:51 -07009226 setEffectSuspended_l(&effect->desc().type, enabled);
9227 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009228 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009229 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009230 return;
9231 }
Eric Laurent59255e42011-07-27 19:49:51 -07009232 }
Steve Block3856b092011-10-20 11:56:00 +01009233 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009234 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009235 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9236 // if effect is requested to suspended but was not yet enabled, supend it now.
9237 if (desc->mEffect == 0) {
9238 desc->mEffect = effect;
9239 effect->setEnabled(false);
9240 effect->setSuspended(true);
9241 }
9242 } else {
9243 if (index < 0) {
9244 return;
9245 }
Steve Block3856b092011-10-20 11:56:00 +01009246 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009247 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009248 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9249 desc->mEffect.clear();
9250 effect->setSuspended(false);
9251 }
9252}
9253
Mathias Agopian65ab4712010-07-14 17:59:35 -07009254#undef LOG_TAG
9255#define LOG_TAG "AudioFlinger"
9256
9257// ----------------------------------------------------------------------------
9258
9259status_t AudioFlinger::onTransact(
9260 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9261{
9262 return BnAudioFlinger::onTransact(code, data, reply, flags);
9263}
9264
Mathias Agopian65ab4712010-07-14 17:59:35 -07009265}; // namespace android