blob: 67dbfe9dfcbee4b8e0e6711e66c2b092a49851a2 [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
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
79#include "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
Glenn Kastenfbae5da2012-05-21 09:17:20 -070082#include "Pipe.h"
83#include "PipeReader.h"
Glenn Kasten58912562012-04-03 10:45:00 -070084#include "SourceAudioBufferProvider.h"
85
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#ifdef HAVE_REQUEST_PRIORITY
87#include "SchedulingPolicyService.h"
88#endif
89
Glenn Kasten58912562012-04-03 10:45:00 -070090#ifdef SOAKER
91#include "Soaker.h"
92#endif
93
Mathias Agopian65ab4712010-07-14 17:59:35 -070094// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
John Grossman1c345192012-03-27 14:00:17 -070096// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
Eric Laurentde070132010-07-13 04:45:46 -0700108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800111static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
112static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800115static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116
117// retry counts for buffer fill timeout
118// 50 * ~20msecs = 1 second
119static const int8_t kMaxTrackRetries = 50;
120static const int8_t kMaxTrackStartupRetries = 50;
121// allow less retry attempts on direct output thread.
122// direct outputs can be a scarce resource in audio hardware and should
123// be released as quickly as possible.
124static const int8_t kMaxTrackRetriesDirect = 2;
125
126static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800127static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// don't warn about blocked writes or record buffer overflows more often than this
130static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700132// RecordThread loop sleep time upon application overrun or audio HAL read error
133static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Glenn Kasten7dede872011-12-13 11:04:14 -0800135// maximum time to wait for setParameters to complete
136static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700137
Eric Laurent7cafbb32011-11-22 18:50:29 -0800138// minimum sleep time for the mixer thread loop when tracks are active but in underrun
139static const uint32_t kMinThreadSleepTimeUs = 5000;
140// maximum divider applied to the active sleep time in the mixer thread loop
141static const uint32_t kMaxThreadSleepTimeShift = 2;
142
Glenn Kasten58912562012-04-03 10:45:00 -0700143// minimum normal mix buffer size, expressed in milliseconds rather than frames
144static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700145// maximum normal mix buffer size
146static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700147
John Grossman4ff14ba2012-02-08 16:37:41 -0800148nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800149
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700150// Whether to use fast mixer
151static const enum {
152 FastMixer_Never, // never initialize or use: for debugging only
153 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
154 // normal mixer multiplier is 1
155 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700156 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700157 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700158 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700159 // FIXME for FastMixer_Dynamic:
160 // Supporting this option will require fixing HALs that can't handle large writes.
161 // For example, one HAL implementation returns an error from a large write,
162 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
163 // We could either fix the HAL implementations, or provide a wrapper that breaks
164 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
165} kUseFastMixer = FastMixer_Static;
166
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167// ----------------------------------------------------------------------------
168
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700169#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800170// To collect the amplifier usage
171static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800172 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
173 if (service == NULL) {
174 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800175 return;
176 }
177
178 service->addBatteryData(params);
179}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700180#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800181
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700182static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700183{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700184 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 int rc;
186
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700187 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
188 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
189 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
190 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700191 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192 }
193 rc = audio_hw_device_open(mod, dev);
194 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
195 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
196 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700197 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700198 }
199 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
200 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
201 rc = BAD_VALUE;
202 goto out;
203 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 return 0;
205
206out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 *dev = NULL;
208 return rc;
209}
210
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211// ----------------------------------------------------------------------------
212
213AudioFlinger::AudioFlinger()
214 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800215 mPrimaryHardwareDev(NULL),
216 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
217 mMasterVolume(1.0f),
218 mMasterVolumeSupportLvl(MVS_NONE),
219 mMasterMute(false),
220 mNextUniqueId(1),
221 mMode(AUDIO_MODE_INVALID),
222 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700224}
225
226void AudioFlinger::onFirstRef()
227{
Dima Zavin799a70e2011-04-18 16:57:27 -0700228 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700229
Eric Laurent93575202011-01-18 18:39:02 -0800230 Mutex::Autolock _l(mLock);
231
Dima Zavin799a70e2011-04-18 16:57:27 -0700232 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800233 char val_str[PROPERTY_VALUE_MAX] = { 0 };
234 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
235 uint32_t int_val;
236 if (1 == sscanf(val_str, "%u", &int_val)) {
237 mStandbyTimeInNsecs = milliseconds(int_val);
238 ALOGI("Using %u mSec as standby time.", int_val);
239 } else {
240 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
241 ALOGI("Using default %u mSec as standby time.",
242 (uint32_t)(mStandbyTimeInNsecs / 1000000));
243 }
244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245
Eric Laurenta4c5a552012-03-29 10:12:40 -0700246 mMode = AUDIO_MODE_NORMAL;
247 mMasterVolumeSW = 1.0;
248 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800249 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250}
251
252AudioFlinger::~AudioFlinger()
253{
Dima Zavin799a70e2011-04-18 16:57:27 -0700254
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255 while (!mRecordThreads.isEmpty()) {
256 // closeInput() will remove first entry from mRecordThreads
257 closeInput(mRecordThreads.keyAt(0));
258 }
259 while (!mPlaybackThreads.isEmpty()) {
260 // closeOutput() will remove first entry from mPlaybackThreads
261 closeOutput(mPlaybackThreads.keyAt(0));
262 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700263
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800264 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
265 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700266 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
267 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700268 }
269}
270
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271static const char * const audio_interfaces[] = {
272 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
273 AUDIO_HARDWARE_MODULE_ID_A2DP,
274 AUDIO_HARDWARE_MODULE_ID_USB,
275};
276#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
277
278audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700279{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700280 // if module is 0, the request comes from an old policy manager and we should load
281 // well known modules
282 if (module == 0) {
283 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
284 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
285 loadHwModule_l(audio_interfaces[i]);
286 }
287 } else {
288 // check a match for the requested module handle
289 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
290 if (audioHwdevice != NULL) {
291 return audioHwdevice->hwDevice();
292 }
293 }
294 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700296 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700297 if ((dev->get_supported_devices(dev) & devices) == devices)
298 return dev;
299 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700300
Dima Zavin799a70e2011-04-18 16:57:27 -0700301 return NULL;
302}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303
304status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
305{
306 const size_t SIZE = 256;
307 char buffer[SIZE];
308 String8 result;
309
310 result.append("Clients:\n");
311 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800312 sp<Client> client = mClients.valueAt(i).promote();
313 if (client != 0) {
314 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
315 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700316 }
317 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700318
319 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800320 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
322 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800323 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700324 result.append(buffer);
325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326 write(fd, result.string(), result.size());
327 return NO_ERROR;
328}
329
330
331status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
332{
333 const size_t SIZE = 256;
334 char buffer[SIZE];
335 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800336 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337
John Grossman4ff14ba2012-02-08 16:37:41 -0800338 snprintf(buffer, SIZE, "Hardware status: %d\n"
339 "Standby Time mSec: %u\n",
340 hardwareStatus,
341 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342 result.append(buffer);
343 write(fd, result.string(), result.size());
344 return NO_ERROR;
345}
346
347status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
348{
349 const size_t SIZE = 256;
350 char buffer[SIZE];
351 String8 result;
352 snprintf(buffer, SIZE, "Permission Denial: "
353 "can't dump AudioFlinger from pid=%d, uid=%d\n",
354 IPCThreadState::self()->getCallingPid(),
355 IPCThreadState::self()->getCallingUid());
356 result.append(buffer);
357 write(fd, result.string(), result.size());
358 return NO_ERROR;
359}
360
361static bool tryLock(Mutex& mutex)
362{
363 bool locked = false;
364 for (int i = 0; i < kDumpLockRetries; ++i) {
365 if (mutex.tryLock() == NO_ERROR) {
366 locked = true;
367 break;
368 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800369 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 }
371 return locked;
372}
373
374status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
375{
Glenn Kasten44deb052012-02-05 18:09:08 -0800376 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377 dumpPermissionDenial(fd, args);
378 } else {
379 // get state of hardware lock
380 bool hardwareLocked = tryLock(mHardwareLock);
381 if (!hardwareLocked) {
382 String8 result(kHardwareLockedString);
383 write(fd, result.string(), result.size());
384 } else {
385 mHardwareLock.unlock();
386 }
387
388 bool locked = tryLock(mLock);
389
390 // failed to lock - AudioFlinger is probably deadlocked
391 if (!locked) {
392 String8 result(kDeadlockedString);
393 write(fd, result.string(), result.size());
394 }
395
396 dumpClients(fd, args);
397 dumpInternals(fd, args);
398
399 // dump playback threads
400 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
401 mPlaybackThreads.valueAt(i)->dump(fd, args);
402 }
403
404 // dump record threads
405 for (size_t i = 0; i < mRecordThreads.size(); i++) {
406 mRecordThreads.valueAt(i)->dump(fd, args);
407 }
408
Dima Zavin799a70e2011-04-18 16:57:27 -0700409 // dump all hardware devs
410 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700411 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700412 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700413 }
414 if (locked) mLock.unlock();
415 }
416 return NO_ERROR;
417}
418
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800419sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
420{
421 // If pid is already in the mClients wp<> map, then use that entry
422 // (for which promote() is always != 0), otherwise create a new entry and Client.
423 sp<Client> client = mClients.valueFor(pid).promote();
424 if (client == 0) {
425 client = new Client(this, pid);
426 mClients.add(pid, client);
427 }
428
429 return client;
430}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431
432// IAudioFlinger interface
433
434
435sp<IAudioTrack> AudioFlinger::createTrack(
436 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800437 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800439 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700440 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800442 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800444 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800445 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 int *sessionId,
447 status_t *status)
448{
449 sp<PlaybackThread::Track> track;
450 sp<TrackHandle> trackHandle;
451 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 status_t lStatus;
453 int lSessionId;
454
Glenn Kasten263709e2012-01-06 08:40:01 -0800455 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
456 // but if someone uses binder directly they could bypass that and cause us to crash
457 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000458 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459 lStatus = BAD_VALUE;
460 goto Exit;
461 }
462
463 {
464 Mutex::Autolock _l(mLock);
465 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700466 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000468 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 lStatus = BAD_VALUE;
470 goto Exit;
471 }
472
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800473 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474
Steve Block3856b092011-10-20 11:56:00 +0100475 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700476 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700477 // check if an effect chain with the same session ID is present on another
478 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
481 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700483 if (sessions & PlaybackThread::EFFECT_SESSION) {
484 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700485 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700486 }
Eric Laurentde070132010-07-13 04:45:46 -0700487 }
488 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 lSessionId = *sessionId;
490 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700491 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700492 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 if (sessionId != NULL) {
494 *sessionId = lSessionId;
495 }
496 }
Steve Block3856b092011-10-20 11:56:00 +0100497 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498
499 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800500 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700501
502 // move effect chain to this output thread if an effect on same session was waiting
503 // for a track to be created
504 if (lStatus == NO_ERROR && effectThread != NULL) {
505 Mutex::Autolock _dl(thread->mLock);
506 Mutex::Autolock _sl(effectThread->mLock);
507 moveEffectChain_l(lSessionId, effectThread, thread, true);
508 }
Eric Laurenta011e352012-03-29 15:51:43 -0700509
510 // Look for sync events awaiting for a session to be used.
511 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
512 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
513 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700514 if (lStatus == NO_ERROR) {
515 track->setSyncEvent(mPendingSyncEvents[i]);
516 } else {
517 mPendingSyncEvents[i]->cancel();
518 }
Eric Laurenta011e352012-03-29 15:51:43 -0700519 mPendingSyncEvents.removeAt(i);
520 i--;
521 }
522 }
523 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524 }
525 if (lStatus == NO_ERROR) {
526 trackHandle = new TrackHandle(track);
527 } else {
528 // remove local strong reference to Client before deleting the Track so that the Client
529 // destructor is called by the TrackBase destructor with mLock held
530 client.clear();
531 track.clear();
532 }
533
534Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700535 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536 *status = lStatus;
537 }
538 return trackHandle;
539}
540
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800541uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542{
543 Mutex::Autolock _l(mLock);
544 PlaybackThread *thread = checkPlaybackThread_l(output);
545 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000546 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547 return 0;
548 }
549 return thread->sampleRate();
550}
551
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800552int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553{
554 Mutex::Autolock _l(mLock);
555 PlaybackThread *thread = checkPlaybackThread_l(output);
556 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000557 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 return 0;
559 }
560 return thread->channelCount();
561}
562
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800563audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700564{
565 Mutex::Autolock _l(mLock);
566 PlaybackThread *thread = checkPlaybackThread_l(output);
567 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000568 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800569 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570 }
571 return thread->format();
572}
573
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800574size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575{
576 Mutex::Autolock _l(mLock);
577 PlaybackThread *thread = checkPlaybackThread_l(output);
578 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000579 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 return 0;
581 }
Glenn Kasten58912562012-04-03 10:45:00 -0700582 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
583 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 return thread->frameCount();
585}
586
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800587uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588{
589 Mutex::Autolock _l(mLock);
590 PlaybackThread *thread = checkPlaybackThread_l(output);
591 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000592 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593 return 0;
594 }
595 return thread->latency();
596}
597
598status_t AudioFlinger::setMasterVolume(float value)
599{
Eric Laurenta1884f92011-08-23 08:25:03 -0700600 status_t ret = initCheck();
601 if (ret != NO_ERROR) {
602 return ret;
603 }
604
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 // check calling permissions
606 if (!settingsAllowed()) {
607 return PERMISSION_DENIED;
608 }
609
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 float swmv = value;
611
Eric Laurenta4c5a552012-03-29 10:12:40 -0700612 Mutex::Autolock _l(mLock);
613
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800615 if (MVS_NONE != mMasterVolumeSupportLvl) {
616 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
617 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700618 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800619
620 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
621 if (NULL != dev->set_master_volume) {
622 dev->set_master_volume(dev, value);
623 }
624 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800625 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800626
627 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
John Grossman4ff14ba2012-02-08 16:37:41 -0800630 mMasterVolume = value;
631 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800632 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700633 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634
635 return NO_ERROR;
636}
637
Glenn Kastenf78aee72012-01-04 11:00:47 -0800638status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639{
Eric Laurenta1884f92011-08-23 08:25:03 -0700640 status_t ret = initCheck();
641 if (ret != NO_ERROR) {
642 return ret;
643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644
645 // check calling permissions
646 if (!settingsAllowed()) {
647 return PERMISSION_DENIED;
648 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800649 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000650 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651 return BAD_VALUE;
652 }
653
654 { // scope for the lock
655 AutoMutex lock(mHardwareLock);
656 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700657 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 mHardwareStatus = AUDIO_HW_IDLE;
659 }
660
661 if (NO_ERROR == ret) {
662 Mutex::Autolock _l(mLock);
663 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800664 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700665 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 }
667
668 return ret;
669}
670
671status_t AudioFlinger::setMicMute(bool state)
672{
Eric Laurenta1884f92011-08-23 08:25:03 -0700673 status_t ret = initCheck();
674 if (ret != NO_ERROR) {
675 return ret;
676 }
677
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 // check calling permissions
679 if (!settingsAllowed()) {
680 return PERMISSION_DENIED;
681 }
682
683 AutoMutex lock(mHardwareLock);
684 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700685 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 mHardwareStatus = AUDIO_HW_IDLE;
687 return ret;
688}
689
690bool AudioFlinger::getMicMute() const
691{
Eric Laurenta1884f92011-08-23 08:25:03 -0700692 status_t ret = initCheck();
693 if (ret != NO_ERROR) {
694 return false;
695 }
696
Dima Zavinfce7a472011-04-19 22:30:36 -0700697 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800698 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700700 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 mHardwareStatus = AUDIO_HW_IDLE;
702 return state;
703}
704
705status_t AudioFlinger::setMasterMute(bool muted)
706{
707 // check calling permissions
708 if (!settingsAllowed()) {
709 return PERMISSION_DENIED;
710 }
711
Eric Laurent93575202011-01-18 18:39:02 -0800712 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800713 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800715 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700716 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717
718 return NO_ERROR;
719}
720
721float AudioFlinger::masterVolume() const
722{
Glenn Kasten98067102011-12-13 11:47:54 -0800723 Mutex::Autolock _l(mLock);
724 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725}
726
John Grossman4ff14ba2012-02-08 16:37:41 -0800727float AudioFlinger::masterVolumeSW() const
728{
729 Mutex::Autolock _l(mLock);
730 return masterVolumeSW_l();
731}
732
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733bool AudioFlinger::masterMute() const
734{
Glenn Kasten98067102011-12-13 11:47:54 -0800735 Mutex::Autolock _l(mLock);
736 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737}
738
John Grossman4ff14ba2012-02-08 16:37:41 -0800739float AudioFlinger::masterVolume_l() const
740{
741 if (MVS_FULL == mMasterVolumeSupportLvl) {
742 float ret_val;
743 AutoMutex lock(mHardwareLock);
744
745 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800746 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
747 (NULL != mPrimaryHardwareDev->get_master_volume),
748 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800749
750 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
751 mHardwareStatus = AUDIO_HW_IDLE;
752 return ret_val;
753 }
754
755 return mMasterVolume;
756}
757
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800758status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
759 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760{
761 // check calling permissions
762 if (!settingsAllowed()) {
763 return PERMISSION_DENIED;
764 }
765
Glenn Kasten263709e2012-01-06 08:40:01 -0800766 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000767 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768 return BAD_VALUE;
769 }
770
771 AutoMutex lock(mLock);
772 PlaybackThread *thread = NULL;
773 if (output) {
774 thread = checkPlaybackThread_l(output);
775 if (thread == NULL) {
776 return BAD_VALUE;
777 }
778 }
779
780 mStreamTypes[stream].volume = value;
781
782 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800783 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700784 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 }
786 } else {
787 thread->setStreamVolume(stream, value);
788 }
789
790 return NO_ERROR;
791}
792
Glenn Kastenfff6d712012-01-12 16:38:12 -0800793status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794{
795 // check calling permissions
796 if (!settingsAllowed()) {
797 return PERMISSION_DENIED;
798 }
799
Glenn Kasten263709e2012-01-06 08:40:01 -0800800 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700801 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000802 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803 return BAD_VALUE;
804 }
805
Eric Laurent93575202011-01-18 18:39:02 -0800806 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 mStreamTypes[stream].mute = muted;
808 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700809 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810
811 return NO_ERROR;
812}
813
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800814float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815{
Glenn Kasten263709e2012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return 0.0f;
818 }
819
820 AutoMutex lock(mLock);
821 float volume;
822 if (output) {
823 PlaybackThread *thread = checkPlaybackThread_l(output);
824 if (thread == NULL) {
825 return 0.0f;
826 }
827 volume = thread->streamVolume(stream);
828 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800829 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 }
831
832 return volume;
833}
834
Glenn Kastenfff6d712012-01-12 16:38:12 -0800835bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836{
Glenn Kasten263709e2012-01-06 08:40:01 -0800837 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 return true;
839 }
840
Glenn Kasten6637baa2012-01-09 09:40:36 -0800841 AutoMutex lock(mLock);
842 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843}
844
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800845status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800847 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
849 // check calling permissions
850 if (!settingsAllowed()) {
851 return PERMISSION_DENIED;
852 }
853
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 // ioHandle == 0 means the parameters are global to the audio hardware interface
855 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700856 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700857 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800858 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700859 AutoMutex lock(mHardwareLock);
860 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
861 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
862 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
863 status_t result = dev->set_parameters(dev, keyValuePairs.string());
864 final_result = result ?: final_result;
865 }
866 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800867 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700868 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
869 AudioParameter param = AudioParameter(keyValuePairs);
870 String8 value;
871 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700872 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
873 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700874 for (size_t i = 0; i < mRecordThreads.size(); i++) {
875 sp<RecordThread> thread = mRecordThreads.valueAt(i);
876 RecordThread::RecordTrack *track = thread->track();
877 if (track != NULL) {
878 audio_devices_t device = (audio_devices_t)(
879 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700880 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700881 thread->setEffectSuspended(FX_IID_AEC,
882 suspend,
883 track->sessionId());
884 thread->setEffectSuspended(FX_IID_NS,
885 suspend,
886 track->sessionId());
887 }
888 }
Eric Laurentbee53372011-08-29 12:42:48 -0700889 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700890 }
891 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700892 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 }
894
895 // hold a strong ref on thread in case closeOutput() or closeInput() is called
896 // and the thread is exited once the lock is released
897 sp<ThreadBase> thread;
898 {
899 Mutex::Autolock _l(mLock);
900 thread = checkPlaybackThread_l(ioHandle);
901 if (thread == NULL) {
902 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800903 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700904 // indicate output device change to all input threads for pre processing
905 AudioParameter param = AudioParameter(keyValuePairs);
906 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700907 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
908 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700909 for (size_t i = 0; i < mRecordThreads.size(); i++) {
910 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
911 }
912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800915 if (thread != 0) {
916 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918 return BAD_VALUE;
919}
920
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800921String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800923// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
925
Eric Laurenta4c5a552012-03-29 10:12:40 -0700926 Mutex::Autolock _l(mLock);
927
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700929 String8 out_s8;
930
Dima Zavin799a70e2011-04-18 16:57:27 -0700931 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800932 char *s;
933 {
934 AutoMutex lock(mHardwareLock);
935 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700936 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800937 s = dev->get_parameters(dev, keys.string());
938 mHardwareStatus = AUDIO_HW_IDLE;
939 }
John Grossmanef7740b2012-02-09 11:28:36 -0800940 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700941 free(s);
942 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700943 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 }
945
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
947 if (playbackThread != NULL) {
948 return playbackThread->getParameters(keys);
949 }
950 RecordThread *recordThread = checkRecordThread_l(ioHandle);
951 if (recordThread != NULL) {
952 return recordThread->getParameters(keys);
953 }
954 return String8("");
955}
956
Glenn Kastenf587ba52012-01-26 16:25:10 -0800957size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958{
Eric Laurenta1884f92011-08-23 08:25:03 -0700959 status_t ret = initCheck();
960 if (ret != NO_ERROR) {
961 return 0;
962 }
963
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800964 AutoMutex lock(mHardwareLock);
965 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700966 struct audio_config config = {
967 sample_rate: sampleRate,
968 channel_mask: audio_channel_in_mask_from_count(channelCount),
969 format: format,
970 };
971 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800972 mHardwareStatus = AUDIO_HW_IDLE;
973 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974}
975
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800976unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977{
978 if (ioHandle == 0) {
979 return 0;
980 }
981
982 Mutex::Autolock _l(mLock);
983
984 RecordThread *recordThread = checkRecordThread_l(ioHandle);
985 if (recordThread != NULL) {
986 return recordThread->getInputFramesLost();
987 }
988 return 0;
989}
990
991status_t AudioFlinger::setVoiceVolume(float value)
992{
Eric Laurenta1884f92011-08-23 08:25:03 -0700993 status_t ret = initCheck();
994 if (ret != NO_ERROR) {
995 return ret;
996 }
997
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998 // check calling permissions
999 if (!settingsAllowed()) {
1000 return PERMISSION_DENIED;
1001 }
1002
1003 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001004 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001005 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 mHardwareStatus = AUDIO_HW_IDLE;
1007
1008 return ret;
1009}
1010
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001011status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1012 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013{
1014 status_t status;
1015
1016 Mutex::Autolock _l(mLock);
1017
1018 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1019 if (playbackThread != NULL) {
1020 return playbackThread->getRenderPosition(halFrames, dspFrames);
1021 }
1022
1023 return BAD_VALUE;
1024}
1025
1026void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1027{
1028
1029 Mutex::Autolock _l(mLock);
1030
Glenn Kastenbb001922012-02-03 11:10:26 -08001031 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 if (mNotificationClients.indexOfKey(pid) < 0) {
1033 sp<NotificationClient> notificationClient = new NotificationClient(this,
1034 client,
1035 pid);
Steve Block3856b092011-10-20 11:56:00 +01001036 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037
1038 mNotificationClients.add(pid, notificationClient);
1039
1040 sp<IBinder> binder = client->asBinder();
1041 binder->linkToDeath(notificationClient);
1042
1043 // the config change is always sent from playback or record threads to avoid deadlock
1044 // with AudioSystem::gLock
1045 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1046 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1047 }
1048
1049 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1050 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1051 }
1052 }
1053}
1054
1055void AudioFlinger::removeNotificationClient(pid_t pid)
1056{
1057 Mutex::Autolock _l(mLock);
1058
Glenn Kastena3b09252012-01-20 09:19:01 -08001059 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001060
Steve Block3856b092011-10-20 11:56:00 +01001061 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001062 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001064 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001065 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001066 ALOGV(" pid %d @ %d", ref->mPid, i);
1067 if (ref->mPid == pid) {
1068 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001069 mAudioSessionRefs.removeAt(i);
1070 delete ref;
1071 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001072 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001073 } else {
1074 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001075 }
1076 }
1077 if (removed) {
1078 purgeStaleEffects_l();
1079 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080}
1081
1082// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001083void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084{
1085 size_t size = mNotificationClients.size();
1086 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001087 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1088 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 }
1090}
1091
1092// removeClient_l() must be called with AudioFlinger::mLock held
1093void AudioFlinger::removeClient_l(pid_t pid)
1094{
Steve Block3856b092011-10-20 11:56:00 +01001095 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 mClients.removeItem(pid);
1097}
1098
1099
1100// ----------------------------------------------------------------------------
1101
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001102AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1103 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001105 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001106 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001107 // mChannelMask
1108 mChannelCount(0),
1109 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1110 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001111 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001112 mDevice(device),
1113 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114{
1115}
1116
1117AudioFlinger::ThreadBase::~ThreadBase()
1118{
1119 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001120 // do not lock the mutex in destructor
1121 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001122 if (mPowerManager != 0) {
1123 sp<IBinder> binder = mPowerManager->asBinder();
1124 binder->unlinkToDeath(mDeathRecipient);
1125 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126}
1127
1128void AudioFlinger::ThreadBase::exit()
1129{
Steve Block3856b092011-10-20 11:56:00 +01001130 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001132 // This lock prevents the following race in thread (uniprocessor for illustration):
1133 // if (!exitPending()) {
1134 // // context switch from here to exit()
1135 // // exit() calls requestExit(), what exitPending() observes
1136 // // exit() calls signal(), which is dropped since no waiters
1137 // // context switch back from exit() to here
1138 // mWaitWorkCV.wait(...);
1139 // // now thread is hung
1140 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001141 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 requestExit();
1143 mWaitWorkCV.signal();
1144 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001145 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1146 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 requestExitAndWait();
1148}
1149
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1151{
1152 status_t status;
1153
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 Mutex::Autolock _l(mLock);
1156
1157 mNewParameters.add(keyValuePairs);
1158 mWaitWorkCV.signal();
1159 // wait condition with timeout in case the thread loop has exited
1160 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001161 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 status = mParamStatus;
1163 mWaitWorkCV.signal();
1164 } else {
1165 status = TIMED_OUT;
1166 }
1167 return status;
1168}
1169
1170void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1171{
1172 Mutex::Autolock _l(mLock);
1173 sendConfigEvent_l(event, param);
1174}
1175
1176// sendConfigEvent_l() must be called with ThreadBase::mLock held
1177void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1178{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001179 ConfigEvent configEvent;
1180 configEvent.mEvent = event;
1181 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001183 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 mWaitWorkCV.signal();
1185}
1186
1187void AudioFlinger::ThreadBase::processConfigEvents()
1188{
1189 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001190 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001191 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001192 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 mConfigEvents.removeAt(0);
1194 // release mLock before locking AudioFlinger mLock: lock order is always
1195 // AudioFlinger then ThreadBase to avoid cross deadlock
1196 mLock.unlock();
1197 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001198 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 mLock.lock();
1201 }
1202 mLock.unlock();
1203}
1204
1205status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1206{
1207 const size_t SIZE = 256;
1208 char buffer[SIZE];
1209 String8 result;
1210
1211 bool locked = tryLock(mLock);
1212 if (!locked) {
1213 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1214 write(fd, buffer, strlen(buffer));
1215 }
1216
Eric Laurent612bbb52012-03-14 15:03:26 -07001217 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1218 result.append(buffer);
1219 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1220 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1222 result.append(buffer);
1223 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1224 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001225 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1226 result.append(buffer);
1227 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228 result.append(buffer);
1229 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1230 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001231 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1232 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001233 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1234 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001235 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 result.append(buffer);
1237
1238 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1239 result.append(buffer);
1240 result.append(" Index Command");
1241 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1242 snprintf(buffer, SIZE, "\n %02d ", i);
1243 result.append(buffer);
1244 result.append(mNewParameters[i]);
1245 }
1246
1247 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1248 result.append(buffer);
1249 snprintf(buffer, SIZE, " Index event param\n");
1250 result.append(buffer);
1251 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001252 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 result.append(buffer);
1254 }
1255 result.append("\n");
1256
1257 write(fd, result.string(), result.size());
1258
1259 if (locked) {
1260 mLock.unlock();
1261 }
1262 return NO_ERROR;
1263}
1264
Eric Laurent1d2bff02011-07-24 17:49:51 -07001265status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1266{
1267 const size_t SIZE = 256;
1268 char buffer[SIZE];
1269 String8 result;
1270
1271 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1272 write(fd, buffer, strlen(buffer));
1273
1274 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1275 sp<EffectChain> chain = mEffectChains[i];
1276 if (chain != 0) {
1277 chain->dump(fd, args);
1278 }
1279 }
1280 return NO_ERROR;
1281}
1282
Eric Laurentfeb0db62011-07-22 09:04:31 -07001283void AudioFlinger::ThreadBase::acquireWakeLock()
1284{
1285 Mutex::Autolock _l(mLock);
1286 acquireWakeLock_l();
1287}
1288
1289void AudioFlinger::ThreadBase::acquireWakeLock_l()
1290{
1291 if (mPowerManager == 0) {
1292 // use checkService() to avoid blocking if power service is not up yet
1293 sp<IBinder> binder =
1294 defaultServiceManager()->checkService(String16("power"));
1295 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001296 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001297 } else {
1298 mPowerManager = interface_cast<IPowerManager>(binder);
1299 binder->linkToDeath(mDeathRecipient);
1300 }
1301 }
1302 if (mPowerManager != 0) {
1303 sp<IBinder> binder = new BBinder();
1304 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1305 binder,
1306 String16(mName));
1307 if (status == NO_ERROR) {
1308 mWakeLockToken = binder;
1309 }
Steve Block3856b092011-10-20 11:56:00 +01001310 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001311 }
1312}
1313
1314void AudioFlinger::ThreadBase::releaseWakeLock()
1315{
1316 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001317 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001318}
1319
1320void AudioFlinger::ThreadBase::releaseWakeLock_l()
1321{
1322 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001323 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001324 if (mPowerManager != 0) {
1325 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1326 }
1327 mWakeLockToken.clear();
1328 }
1329}
1330
1331void AudioFlinger::ThreadBase::clearPowerManager()
1332{
1333 Mutex::Autolock _l(mLock);
1334 releaseWakeLock_l();
1335 mPowerManager.clear();
1336}
1337
1338void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1339{
1340 sp<ThreadBase> thread = mThread.promote();
1341 if (thread != 0) {
1342 thread->clearPowerManager();
1343 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001344 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001345}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001346
Eric Laurent59255e42011-07-27 19:49:51 -07001347void AudioFlinger::ThreadBase::setEffectSuspended(
1348 const effect_uuid_t *type, bool suspend, int sessionId)
1349{
1350 Mutex::Autolock _l(mLock);
1351 setEffectSuspended_l(type, suspend, sessionId);
1352}
1353
1354void AudioFlinger::ThreadBase::setEffectSuspended_l(
1355 const effect_uuid_t *type, bool suspend, int sessionId)
1356{
Glenn Kasten090f0192012-01-30 13:00:02 -08001357 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001358 if (chain != 0) {
1359 if (type != NULL) {
1360 chain->setEffectSuspended_l(type, suspend);
1361 } else {
1362 chain->setEffectSuspendedAll_l(suspend);
1363 }
1364 }
1365
1366 updateSuspendedSessions_l(type, suspend, sessionId);
1367}
1368
1369void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1370{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001371 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001372 if (index < 0) {
1373 return;
1374 }
1375
1376 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1377 mSuspendedSessions.editValueAt(index);
1378
1379 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001380 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001381 for (int j = 0; j < desc->mRefCount; j++) {
1382 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1383 chain->setEffectSuspendedAll_l(true);
1384 } else {
Steve Block3856b092011-10-20 11:56:00 +01001385 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001386 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001387 chain->setEffectSuspended_l(&desc->mType, true);
1388 }
1389 }
1390 }
1391}
1392
Eric Laurent59255e42011-07-27 19:49:51 -07001393void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1394 bool suspend,
1395 int sessionId)
1396{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001397 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001398
1399 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1400
1401 if (suspend) {
1402 if (index >= 0) {
1403 sessionEffects = mSuspendedSessions.editValueAt(index);
1404 } else {
1405 mSuspendedSessions.add(sessionId, sessionEffects);
1406 }
1407 } else {
1408 if (index < 0) {
1409 return;
1410 }
1411 sessionEffects = mSuspendedSessions.editValueAt(index);
1412 }
1413
1414
1415 int key = EffectChain::kKeyForSuspendAll;
1416 if (type != NULL) {
1417 key = type->timeLow;
1418 }
1419 index = sessionEffects.indexOfKey(key);
1420
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001421 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001422 if (suspend) {
1423 if (index >= 0) {
1424 desc = sessionEffects.valueAt(index);
1425 } else {
1426 desc = new SuspendedSessionDesc();
1427 if (type != NULL) {
1428 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1429 }
1430 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001431 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001432 }
1433 desc->mRefCount++;
1434 } else {
1435 if (index < 0) {
1436 return;
1437 }
1438 desc = sessionEffects.valueAt(index);
1439 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001440 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001441 sessionEffects.removeItemsAt(index);
1442 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001443 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001444 sessionId);
1445 mSuspendedSessions.removeItem(sessionId);
1446 }
1447 }
1448 }
1449 if (!sessionEffects.isEmpty()) {
1450 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1451 }
1452}
1453
1454void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1455 bool enabled,
1456 int sessionId)
1457{
1458 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001459 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1460}
Eric Laurent59255e42011-07-27 19:49:51 -07001461
Eric Laurenta85a74a2011-10-19 11:44:54 -07001462void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1463 bool enabled,
1464 int sessionId)
1465{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001466 if (mType != RECORD) {
1467 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1468 // another session. This gives the priority to well behaved effect control panels
1469 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001470 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1471 // global effects
1472 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001473 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1474 }
1475 }
Eric Laurent59255e42011-07-27 19:49:51 -07001476
1477 sp<EffectChain> chain = getEffectChain_l(sessionId);
1478 if (chain != 0) {
1479 chain->checkSuspendOnEffectEnabled(effect, enabled);
1480 }
1481}
1482
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483// ----------------------------------------------------------------------------
1484
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001485AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1486 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001487 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001488 uint32_t device,
1489 type_t type)
1490 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001491 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1492 // Assumes constructor is called by AudioFlinger with it's mLock held,
1493 // but it would be safer to explicitly pass initial masterMute as parameter
1494 mMasterMute(audioFlinger->masterMute_l()),
1495 // mStreamTypes[] initialized in constructor body
1496 mOutput(output),
1497 // Assumes constructor is called by AudioFlinger with it's mLock held,
1498 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001499 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001500 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001501 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001502 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001503 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten288ed212012-04-25 17:52:27 -07001504 // index 0 is reserved for normal mixer's submix
1505 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506{
Glenn Kasten480b4682012-02-28 12:30:08 -08001507 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001508
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 readOutputParameters();
1510
Glenn Kasten263709e2012-01-06 08:40:01 -08001511 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001512 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1513 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1514 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001515 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1516 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001518 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1519 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520}
1521
1522AudioFlinger::PlaybackThread::~PlaybackThread()
1523{
1524 delete [] mMixBuffer;
1525}
1526
1527status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1528{
1529 dumpInternals(fd, args);
1530 dumpTracks(fd, args);
1531 dumpEffectChains(fd, args);
1532 return NO_ERROR;
1533}
1534
1535status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1536{
1537 const size_t SIZE = 256;
1538 char buffer[SIZE];
1539 String8 result;
1540
Glenn Kasten58912562012-04-03 10:45:00 -07001541 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1542 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1543 const stream_type_t *st = &mStreamTypes[i];
1544 if (i > 0) {
1545 result.appendFormat(", ");
1546 }
1547 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1548 if (st->mute) {
1549 result.append("M");
1550 }
1551 }
1552 result.append("\n");
1553 write(fd, result.string(), result.length());
1554 result.clear();
1555
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1557 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001558 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559 for (size_t i = 0; i < mTracks.size(); ++i) {
1560 sp<Track> track = mTracks[i];
1561 if (track != 0) {
1562 track->dump(buffer, SIZE);
1563 result.append(buffer);
1564 }
1565 }
1566
1567 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1568 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001569 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001571 sp<Track> track = mActiveTracks[i].promote();
1572 if (track != 0) {
1573 track->dump(buffer, SIZE);
1574 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575 }
1576 }
1577 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001578
1579 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1580 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1581 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1582 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1583
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 return NO_ERROR;
1585}
1586
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1588{
1589 const size_t SIZE = 256;
1590 char buffer[SIZE];
1591 String8 result;
1592
1593 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1596 result.append(buffer);
1597 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1598 result.append(buffer);
1599 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1600 result.append(buffer);
1601 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1602 result.append(buffer);
1603 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1604 result.append(buffer);
1605 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1606 result.append(buffer);
1607 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001608 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609
1610 dumpBase(fd, args);
1611
1612 return NO_ERROR;
1613}
1614
1615// Thread virtuals
1616status_t AudioFlinger::PlaybackThread::readyToRun()
1617{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001618 status_t status = initCheck();
1619 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001620 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001621 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001622 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001624 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625}
1626
1627void AudioFlinger::PlaybackThread::onFirstRef()
1628{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001629 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630}
1631
1632// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001633sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001635 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001637 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001638 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 int frameCount,
1640 const sp<IMemory>& sharedBuffer,
1641 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001642 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001643 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644 status_t *status)
1645{
1646 sp<Track> track;
1647 status_t lStatus;
1648
Glenn Kasten73d22752012-03-19 13:38:30 -07001649 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1650
1651 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001652 if (flags & IAudioFlinger::TRACK_FAST) {
1653 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001654 // not timed
1655 (!isTimed) &&
1656 // either of these use cases:
1657 (
1658 // use case 1: shared buffer with any frame count
1659 (
1660 (sharedBuffer != 0)
1661 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001662 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001663 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001664 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001665 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001666 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001667 )
1668 ) &&
1669 // PCM data
1670 audio_is_linear_pcm(format) &&
1671 // mono or stereo
1672 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1673 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001674#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001675 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001676 (sampleRate == mSampleRate) &&
1677#endif
1678 // normal mixer has an associated fast mixer
1679 hasFastMixer() &&
1680 // there are sufficient fast track slots available
1681 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001682 // FIXME test that MixerThread for this fast track has a capable output HAL
1683 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001684 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001685 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1686 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001687 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001688 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001689 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001690 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001691 } else {
1692 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001693 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1694 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1695 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1696 audio_is_linear_pcm(format),
1697 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001698 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001699 // For compatibility with AudioTrack calculation, buffer depth is forced
1700 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1701 // This is probably too conservative, but legacy application code may depend on it.
1702 // If you change this calculation, also review the start threshold which is related.
1703 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1704 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1705 if (minBufCount < 2) {
1706 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001707 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001708 int minFrameCount = mNormalFrameCount * minBufCount;
1709 if (frameCount < minFrameCount) {
1710 frameCount = minFrameCount;
1711 }
1712 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001713 }
1714
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001716 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1717 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001718 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001719 "for output %p with format %d",
1720 sampleRate, format, channelMask, mOutput, mFormat);
1721 lStatus = BAD_VALUE;
1722 goto Exit;
1723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 }
1725 } else {
1726 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1727 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001728 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 lStatus = BAD_VALUE;
1730 goto Exit;
1731 }
1732 }
1733
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001734 lStatus = initCheck();
1735 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001736 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737 goto Exit;
1738 }
1739
1740 { // scope for mLock
1741 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001742
1743 // all tracks in same audio session must share the same routing strategy otherwise
1744 // conflicts will happen when tracks are moved from one output to another by audio policy
1745 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001746 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001747 for (size_t i = 0; i < mTracks.size(); ++i) {
1748 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001749 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001750 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001751 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001752 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001753 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001754 lStatus = BAD_VALUE;
1755 goto Exit;
1756 }
1757 }
1758 }
1759
John Grossman4ff14ba2012-02-08 16:37:41 -08001760 if (!isTimed) {
1761 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001762 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001763 } else {
1764 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1765 channelMask, frameCount, sharedBuffer, sessionId);
1766 }
1767 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 lStatus = NO_MEMORY;
1769 goto Exit;
1770 }
1771 mTracks.add(track);
1772
1773 sp<EffectChain> chain = getEffectChain_l(sessionId);
1774 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001775 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001777 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001778 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 }
1780 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001781
1782#ifdef HAVE_REQUEST_PRIORITY
1783 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1784 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1785 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1786 // so ask activity manager to do this on our behalf
1787 int err = requestPriority(callingPid, tid, 1);
1788 if (err != 0) {
1789 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1790 1, callingPid, tid, err);
1791 }
1792 }
1793#endif
1794
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 lStatus = NO_ERROR;
1796
1797Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001798 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 *status = lStatus;
1800 }
1801 return track;
1802}
1803
Eric Laurente737cda2012-05-22 18:55:44 -07001804uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1805{
1806 if (mFastMixer != NULL) {
1807 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1808 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1809 }
1810 return latency;
1811}
1812
1813uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1814{
1815 return latency;
1816}
1817
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818uint32_t AudioFlinger::PlaybackThread::latency() const
1819{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001820 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001821 return latency_l();
1822}
1823uint32_t AudioFlinger::PlaybackThread::latency_l() const
1824{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001825 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001826 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001827 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 return 0;
1829 }
1830}
1831
Glenn Kasten6637baa2012-01-09 09:40:36 -08001832void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001834 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836}
1837
Glenn Kasten6637baa2012-01-09 09:40:36 -08001838void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001840 Mutex::Autolock _l(mLock);
1841 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842}
1843
Glenn Kasten6637baa2012-01-09 09:40:36 -08001844void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001846 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848}
1849
Glenn Kasten6637baa2012-01-09 09:40:36 -08001850void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001852 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854}
1855
Glenn Kastenfff6d712012-01-12 16:38:12 -08001856float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001858 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 return mStreamTypes[stream].volume;
1860}
1861
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862// addTrack_l() must be called with ThreadBase::mLock held
1863status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1864{
1865 status_t status = ALREADY_EXISTS;
1866
1867 // set retry count for buffer fill
1868 track->mRetryCount = kMaxTrackStartupRetries;
1869 if (mActiveTracks.indexOf(track) < 0) {
1870 // the track is newly added, make sure it fills up all its
1871 // buffers before playing. This is to ensure the client will
1872 // effectively get the latency it requested.
1873 track->mFillingUpStatus = Track::FS_FILLING;
1874 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001875 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 mActiveTracks.add(track);
1877 if (track->mainBuffer() != mMixBuffer) {
1878 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1879 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001880 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001881 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882 }
1883 }
1884
1885 status = NO_ERROR;
1886 }
1887
Steve Block3856b092011-10-20 11:56:00 +01001888 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 mWaitWorkCV.broadcast();
1890
1891 return status;
1892}
1893
1894// destroyTrack_l() must be called with ThreadBase::mLock held
1895void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1896{
1897 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001898 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001900 removeTrack_l(track);
1901 }
1902}
1903
1904void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1905{
Eric Laurent29864602012-05-08 18:57:51 -07001906 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001907 mTracks.remove(track);
1908 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001909 // redundant as track is about to be destroyed, for dumpsys only
1910 track->mName = -1;
1911 if (track->isFastTrack()) {
1912 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001913 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001914 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1915 mFastTrackAvailMask |= 1 << index;
1916 // redundant as track is about to be destroyed, for dumpsys only
1917 track->mFastIndex = -1;
1918 }
Eric Laurentb469b942011-05-09 12:09:06 -07001919 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1920 if (chain != 0) {
1921 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 }
1923}
1924
1925String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1926{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001927 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001928 char *s;
1929
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001930 Mutex::Autolock _l(mLock);
1931 if (initCheck() != NO_ERROR) {
1932 return out_s8;
1933 }
1934
Dima Zavin799a70e2011-04-18 16:57:27 -07001935 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001936 out_s8 = String8(s);
1937 free(s);
1938 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939}
1940
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001941// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1943 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001944 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945
Steve Block3856b092011-10-20 11:56:00 +01001946 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947
1948 switch (event) {
1949 case AudioSystem::OUTPUT_OPENED:
1950 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001951 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 desc.samplingRate = mSampleRate;
1953 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001954 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 desc.latency = latency();
1956 param2 = &desc;
1957 break;
1958
1959 case AudioSystem::STREAM_CONFIG_CHANGED:
1960 param2 = &param;
1961 case AudioSystem::OUTPUT_CLOSED:
1962 default:
1963 break;
1964 }
1965 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1966}
1967
1968void AudioFlinger::PlaybackThread::readOutputParameters()
1969{
Dima Zavin799a70e2011-04-18 16:57:27 -07001970 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001971 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1972 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001973 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001974 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001975 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001976 if (mFrameCount & 15) {
1977 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1978 mFrameCount);
1979 }
1980
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001981 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001982 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001983 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001984 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001985 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1986 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1987 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1988 maxNormalFrameCount = maxNormalFrameCount & ~15;
1989 if (maxNormalFrameCount < minNormalFrameCount) {
1990 maxNormalFrameCount = minNormalFrameCount;
1991 }
1992 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1993 if (multiplier <= 1.0) {
1994 multiplier = 1.0;
1995 } else if (multiplier <= 2.0) {
1996 if (2 * mFrameCount <= maxNormalFrameCount) {
1997 multiplier = 2.0;
1998 } else {
1999 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2000 }
2001 } else {
2002 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2003 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2004 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2005 // FIXME this rounding up should not be done if no HAL SRC
2006 uint32_t truncMult = (uint32_t) multiplier;
2007 if ((truncMult & 1)) {
2008 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2009 ++truncMult;
2010 }
2011 }
2012 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002013 }
Glenn Kasten58912562012-04-03 10:45:00 -07002014 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002015 mNormalFrameCount = multiplier * mFrameCount;
2016 // round up to nearest 16 frames to satisfy AudioMixer
2017 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002018 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019
Glenn Kastene9dd0172012-01-27 18:08:45 -08002020 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002021 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2022 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023
Eric Laurentde070132010-07-13 04:45:46 -07002024 // force reconfiguration of effect chains and engines to take new buffer size and audio
2025 // parameters into account
2026 // Note that mLock is not held when readOutputParameters() is called from the constructor
2027 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2028 // matter.
2029 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2030 Vector< sp<EffectChain> > effectChains = mEffectChains;
2031 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002032 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002033 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034}
2035
Eric Laurente737cda2012-05-22 18:55:44 -07002036
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2038{
Glenn Kastena0d68332012-01-27 16:47:15 -08002039 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 return BAD_VALUE;
2041 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002042 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002043 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 return INVALID_OPERATION;
2045 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002046 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047
Dima Zavin799a70e2011-04-18 16:57:27 -07002048 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049}
2050
Eric Laurent39e94f82010-07-28 01:32:47 -07002051uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052{
2053 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002054 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002056 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 }
2058
2059 for (size_t i = 0; i < mTracks.size(); ++i) {
2060 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002061 if (sessionId == track->sessionId() &&
2062 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002063 result |= TRACK_SESSION;
2064 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 }
2066 }
2067
Eric Laurent39e94f82010-07-28 01:32:47 -07002068 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069}
2070
Eric Laurentde070132010-07-13 04:45:46 -07002071uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2072{
Dima Zavinfce7a472011-04-19 22:30:36 -07002073 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002074 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002075 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2076 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002077 }
2078 for (size_t i = 0; i < mTracks.size(); i++) {
2079 sp<Track> track = mTracks[i];
2080 if (sessionId == track->sessionId() &&
2081 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002082 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002083 }
2084 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002085 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002086}
2087
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088
Glenn Kastenaed850d2012-01-26 09:46:34 -08002089AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002090{
2091 Mutex::Autolock _l(mLock);
2092 return mOutput;
2093}
2094
2095AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2096{
2097 Mutex::Autolock _l(mLock);
2098 AudioStreamOut *output = mOutput;
2099 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002100 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2101 // must push a NULL and wait for ack
2102 mOutputSink.clear();
2103 mPipeSink.clear();
2104 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002105 return output;
2106}
2107
2108// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002109audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002110{
2111 if (mOutput == NULL) {
2112 return NULL;
2113 }
2114 return &mOutput->stream->common;
2115}
2116
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002117uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002118{
Eric Laurentab9071b2012-06-04 13:45:29 -07002119 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002120}
2121
Eric Laurenta011e352012-03-29 15:51:43 -07002122status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2123{
2124 if (!isValidSyncEvent(event)) {
2125 return BAD_VALUE;
2126 }
2127
2128 Mutex::Autolock _l(mLock);
2129
2130 for (size_t i = 0; i < mTracks.size(); ++i) {
2131 sp<Track> track = mTracks[i];
2132 if (event->triggerSession() == track->sessionId()) {
2133 track->setSyncEvent(event);
2134 return NO_ERROR;
2135 }
2136 }
2137
2138 return NAME_NOT_FOUND;
2139}
2140
2141bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2142{
2143 switch (event->type()) {
2144 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2145 return true;
2146 default:
2147 break;
2148 }
2149 return false;
2150}
2151
Eric Laurent44a957f2012-05-15 15:26:05 -07002152void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2153{
2154 size_t count = tracksToRemove.size();
2155 if (CC_UNLIKELY(count)) {
2156 for (size_t i = 0 ; i < count ; i++) {
2157 const sp<Track>& track = tracksToRemove.itemAt(i);
2158 if ((track->sharedBuffer() != 0) &&
2159 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2160 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2161 }
2162 }
2163 }
2164
2165}
2166
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167// ----------------------------------------------------------------------------
2168
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002169AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002170 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002171 : PlaybackThread(audioFlinger, output, id, device, type),
2172 // mAudioMixer below
2173#ifdef SOAKER
2174 mSoaker(NULL),
2175#endif
2176 // mFastMixer below
2177 mFastMixerFutex(0)
2178 // mOutputSink below
2179 // mPipeSink below
2180 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181{
Glenn Kasten58912562012-04-03 10:45:00 -07002182 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2183 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2184 "mFrameCount=%d, mNormalFrameCount=%d",
2185 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2186 mNormalFrameCount);
2187 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2188
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 // FIXME - Current mixer implementation only supports stereo output
2190 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002191 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 }
Glenn Kasten58912562012-04-03 10:45:00 -07002193
2194 // create an NBAIO sink for the HAL output stream, and negotiate
2195 mOutputSink = new AudioStreamOutSink(output->stream);
2196 size_t numCounterOffers = 0;
2197 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2198 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2199 ALOG_ASSERT(index == 0);
2200
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002201 // initialize fast mixer depending on configuration
2202 bool initFastMixer;
2203 switch (kUseFastMixer) {
2204 case FastMixer_Never:
2205 initFastMixer = false;
2206 break;
2207 case FastMixer_Always:
2208 initFastMixer = true;
2209 break;
2210 case FastMixer_Static:
2211 case FastMixer_Dynamic:
2212 initFastMixer = mFrameCount < mNormalFrameCount;
2213 break;
2214 }
2215 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002216
2217 // create a MonoPipe to connect our submix to FastMixer
2218 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002219 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2220 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2221 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2222 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002223 const NBAIO_Format offers[1] = {format};
2224 size_t numCounterOffers = 0;
2225 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2226 ALOG_ASSERT(index == 0);
2227 mPipeSink = monoPipe;
2228
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002229#ifdef TEE_SINK_FRAMES
2230 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2231 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2232 numCounterOffers = 0;
2233 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2234 ALOG_ASSERT(index == 0);
2235 mTeeSink = teeSink;
2236 PipeReader *teeSource = new PipeReader(*teeSink);
2237 numCounterOffers = 0;
2238 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2239 ALOG_ASSERT(index == 0);
2240 mTeeSource = teeSource;
2241#endif
2242
Glenn Kasten58912562012-04-03 10:45:00 -07002243#ifdef SOAKER
2244 // create a soaker as workaround for governor issues
2245 mSoaker = new Soaker();
2246 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2247 mSoaker->run("Soaker", PRIORITY_LOWEST);
2248#endif
2249
2250 // create fast mixer and configure it initially with just one fast track for our submix
2251 mFastMixer = new FastMixer();
2252 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002253#ifdef STATE_QUEUE_DUMP
2254 sq->setObserverDump(&mStateQueueObserverDump);
2255 sq->setMutatorDump(&mStateQueueMutatorDump);
2256#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002257 FastMixerState *state = sq->begin();
2258 FastTrack *fastTrack = &state->mFastTracks[0];
2259 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2260 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2261 fastTrack->mVolumeProvider = NULL;
2262 fastTrack->mGeneration++;
2263 state->mFastTracksGen++;
2264 state->mTrackMask = 1;
2265 // fast mixer will use the HAL output sink
2266 state->mOutputSink = mOutputSink.get();
2267 state->mOutputSinkGen++;
2268 state->mFrameCount = mFrameCount;
2269 state->mCommand = FastMixerState::COLD_IDLE;
2270 // already done in constructor initialization list
2271 //mFastMixerFutex = 0;
2272 state->mColdFutexAddr = &mFastMixerFutex;
2273 state->mColdGen++;
2274 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002275 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002276 sq->end();
2277 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2278
2279 // start the fast mixer
2280 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2281#ifdef HAVE_REQUEST_PRIORITY
2282 pid_t tid = mFastMixer->getTid();
2283 int err = requestPriority(getpid_cached, tid, 2);
2284 if (err != 0) {
2285 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2286 2, getpid_cached, tid, err);
2287 }
2288#endif
2289
2290 } else {
2291 mFastMixer = NULL;
2292 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002293
2294 switch (kUseFastMixer) {
2295 case FastMixer_Never:
2296 case FastMixer_Dynamic:
2297 mNormalSink = mOutputSink;
2298 break;
2299 case FastMixer_Always:
2300 mNormalSink = mPipeSink;
2301 break;
2302 case FastMixer_Static:
2303 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2304 break;
2305 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306}
2307
2308AudioFlinger::MixerThread::~MixerThread()
2309{
Glenn Kasten58912562012-04-03 10:45:00 -07002310 if (mFastMixer != NULL) {
2311 FastMixerStateQueue *sq = mFastMixer->sq();
2312 FastMixerState *state = sq->begin();
2313 if (state->mCommand == FastMixerState::COLD_IDLE) {
2314 int32_t old = android_atomic_inc(&mFastMixerFutex);
2315 if (old == -1) {
2316 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2317 }
2318 }
2319 state->mCommand = FastMixerState::EXIT;
2320 sq->end();
2321 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2322 mFastMixer->join();
2323 // Though the fast mixer thread has exited, it's state queue is still valid.
2324 // We'll use that extract the final state which contains one remaining fast track
2325 // corresponding to our sub-mix.
2326 state = sq->begin();
2327 ALOG_ASSERT(state->mTrackMask == 1);
2328 FastTrack *fastTrack = &state->mFastTracks[0];
2329 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2330 delete fastTrack->mBufferProvider;
2331 sq->end(false /*didModify*/);
2332 delete mFastMixer;
2333#ifdef SOAKER
2334 if (mSoaker != NULL) {
2335 mSoaker->requestExitAndWait();
2336 }
2337 delete mSoaker;
2338#endif
2339 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 delete mAudioMixer;
2341}
2342
Glenn Kasten83efdd02012-02-24 07:21:32 -08002343class CpuStats {
2344public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002345 CpuStats();
2346 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002347#ifdef DEBUG_CPU_USAGE
2348private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002349 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2350 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2351
2352 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2353
2354 int mCpuNum; // thread's current CPU number
2355 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002356#endif
2357};
2358
Glenn Kasten190a46f2012-03-06 11:27:10 -08002359CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002360#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002361 : mCpuNum(-1), mCpukHz(-1)
2362#endif
2363{
2364}
2365
2366void CpuStats::sample(const String8 &title) {
2367#ifdef DEBUG_CPU_USAGE
2368 // get current thread's delta CPU time in wall clock ns
2369 double wcNs;
2370 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2371
2372 // record sample for wall clock statistics
2373 if (valid) {
2374 mWcStats.sample(wcNs);
2375 }
2376
2377 // get the current CPU number
2378 int cpuNum = sched_getcpu();
2379
2380 // get the current CPU frequency in kHz
2381 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2382
2383 // check if either CPU number or frequency changed
2384 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2385 mCpuNum = cpuNum;
2386 mCpukHz = cpukHz;
2387 // ignore sample for purposes of cycles
2388 valid = false;
2389 }
2390
2391 // if no change in CPU number or frequency, then record sample for cycle statistics
2392 if (valid && mCpukHz > 0) {
2393 double cycles = wcNs * cpukHz * 0.000001;
2394 mHzStats.sample(cycles);
2395 }
2396
2397 unsigned n = mWcStats.n();
2398 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002399 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002400 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2402 double perLoop = elapsed / (double) n;
2403 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002404 double perLoop1k = perLoop * 0.001;
2405 double mean = mWcStats.mean();
2406 double stddev = mWcStats.stddev();
2407 double minimum = mWcStats.minimum();
2408 double maximum = mWcStats.maximum();
2409 double meanCycles = mHzStats.mean();
2410 double stddevCycles = mHzStats.stddev();
2411 double minCycles = mHzStats.minimum();
2412 double maxCycles = mHzStats.maximum();
2413 mCpuUsage.resetElapsed();
2414 mWcStats.reset();
2415 mHzStats.reset();
2416 ALOGD("CPU usage for %s over past %.1f secs\n"
2417 " (%u mixer loops at %.1f mean ms per loop):\n"
2418 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2419 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2420 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2421 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002422 elapsed * .000000001, n, perLoop * .000001,
2423 mean * .001,
2424 stddev * .001,
2425 minimum * .001,
2426 maximum * .001,
2427 mean / perLoop100,
2428 stddev / perLoop100,
2429 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002430 maximum / perLoop100,
2431 meanCycles / perLoop1k,
2432 stddevCycles / perLoop1k,
2433 minCycles / perLoop1k,
2434 maxCycles / perLoop1k);
2435
Glenn Kasten83efdd02012-02-24 07:21:32 -08002436 }
2437 }
2438#endif
2439};
2440
Glenn Kasten37d825e2012-02-24 07:21:48 -08002441void AudioFlinger::PlaybackThread::checkSilentMode_l()
2442{
2443 if (!mMasterMute) {
2444 char value[PROPERTY_VALUE_MAX];
2445 if (property_get("ro.audio.silent", value, "0") > 0) {
2446 char *endptr;
2447 unsigned long ul = strtoul(value, &endptr, 0);
2448 if (*endptr == '\0' && ul != 0) {
2449 ALOGD("Silence is golden");
2450 // The setprop command will not allow a property to be changed after
2451 // the first time it is set, so we don't have to worry about un-muting.
2452 setMasterMute_l(true);
2453 }
2454 }
2455 }
2456}
2457
Glenn Kasten000f0e32012-03-01 17:10:56 -08002458bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459{
2460 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002461
Glenn Kasten000f0e32012-03-01 17:10:56 -08002462 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002463
2464 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002466if (mType == MIXER) {
2467 longStandbyExit = false;
2468}
Glenn Kasten688a6402012-02-29 07:57:06 -08002469
Glenn Kasten000f0e32012-03-01 17:10:56 -08002470 // DUPLICATING
2471 // FIXME could this be made local to while loop?
2472 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002473
Glenn Kasten66fcab92012-02-24 14:59:21 -08002474 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475 sleepTime = idleSleepTime;
2476
2477if (mType == MIXER) {
2478 sleepTimeShift = 0;
2479}
2480
Glenn Kasten83efdd02012-02-24 07:21:32 -08002481 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002482 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483
Eric Laurentfeb0db62011-07-22 09:04:31 -07002484 acquireWakeLock();
2485
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 while (!exitPending())
2487 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002488 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002489
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002490 Vector< sp<EffectChain> > effectChains;
2491
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 processConfigEvents();
2493
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 { // scope for mLock
2495
2496 Mutex::Autolock _l(mLock);
2497
2498 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002499 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 }
2501
Glenn Kastenfa26a852012-03-06 11:28:04 -08002502 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002505 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002506 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508
2509 threadLoop_standby();
2510
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 mStandby = true;
2512 mBytesWritten = 0;
2513 }
2514
Glenn Kasten3e074702012-02-28 18:40:35 -08002515 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 // we're about to wait, flush the binder command buffer
2517 IPCThreadState::self()->flushCommands();
2518
Glenn Kastenfa26a852012-03-06 11:28:04 -08002519 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 if (exitPending()) break;
2522
Eric Laurentfeb0db62011-07-22 09:04:31 -07002523 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002525 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002527 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002528 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529
Eric Laurentda747442012-04-25 18:53:13 -07002530 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002531 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002532
Glenn Kasten37d825e2012-02-24 07:21:48 -08002533 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534
Glenn Kasten000f0e32012-03-01 17:10:56 -08002535 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002537 if (mType == MIXER) {
2538 sleepTimeShift = 0;
2539 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002540
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 continue;
2542 }
2543 }
2544
Glenn Kasten81028042012-04-30 18:15:12 -07002545 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002546 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547
2548 // prevent any changes in effect chain list and in each effect chain
2549 // during mixing and effect process as the audio buffers could be deleted
2550 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002551 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553
Glenn Kastenfec279f2012-03-08 07:47:15 -08002554 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002555 threadLoop_mix();
2556 } else {
2557 threadLoop_sleepTime();
2558 }
2559
2560 if (mSuspended > 0) {
2561 sleepTime = suspendSleepTimeUs();
2562 }
2563
2564 // only process effects if we're going to write
2565 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002566 for (size_t i = 0; i < effectChains.size(); i ++) {
2567 effectChains[i]->process_l();
2568 }
2569 }
2570
2571 // enable changes in effect chain
2572 unlockEffectChains(effectChains);
2573
2574 // sleepTime == 0 means we must write to audio hardware
2575 if (sleepTime == 0) {
2576
2577 threadLoop_write();
2578
2579if (mType == MIXER) {
2580 // write blocked detection
2581 nsecs_t now = systemTime();
2582 nsecs_t delta = now - mLastWriteTime;
2583 if (!mStandby && delta > maxPeriod) {
2584 mNumDelayedWrites++;
2585 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002586#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002587 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002588#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002589 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2590 ns2ms(delta), mNumDelayedWrites, this);
2591 lastWarning = now;
2592 }
2593 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2594 // a different threshold. Or completely removed for what it is worth anyway...
2595 if (mStandby) {
2596 longStandbyExit = true;
2597 }
2598 }
2599}
2600
2601 mStandby = false;
2602 } else {
2603 usleep(sleepTime);
2604 }
2605
Glenn Kasten58912562012-04-03 10:45:00 -07002606 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002607 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002608 // same lock. This will also mutate and push a new fast mixer state.
2609 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002610 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002611
Glenn Kastenfa26a852012-03-06 11:28:04 -08002612 // FIXME I don't understand the need for this here;
2613 // it was in the original code but maybe the
2614 // assignment in saveOutputTracks() makes this unnecessary?
2615 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002616
2617 // Effect chains will be actually deleted here if they were removed from
2618 // mEffectChains list during mixing or effects processing
2619 effectChains.clear();
2620
2621 // FIXME Note that the above .clear() is no longer necessary since effectChains
2622 // is now local to this block, but will keep it for now (at least until merge done).
2623 }
2624
2625if (mType == MIXER || mType == DIRECT) {
2626 // put output stream into standby mode
2627 if (!mStandby) {
2628 mOutput->stream->common.standby(&mOutput->stream->common);
2629 }
2630}
2631if (mType == DUPLICATING) {
2632 // for DuplicatingThread, standby mode is handled by the outputTracks
2633}
2634
2635 releaseWakeLock();
2636
2637 ALOGV("Thread %p type %d exiting", this, mType);
2638 return false;
2639}
2640
Glenn Kasten58912562012-04-03 10:45:00 -07002641void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2642{
Glenn Kasten58912562012-04-03 10:45:00 -07002643 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2644}
2645
2646void AudioFlinger::MixerThread::threadLoop_write()
2647{
2648 // FIXME we should only do one push per cycle; confirm this is true
2649 // Start the fast mixer if it's not already running
2650 if (mFastMixer != NULL) {
2651 FastMixerStateQueue *sq = mFastMixer->sq();
2652 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002653 if (state->mCommand != FastMixerState::MIX_WRITE &&
2654 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002655 if (state->mCommand == FastMixerState::COLD_IDLE) {
2656 int32_t old = android_atomic_inc(&mFastMixerFutex);
2657 if (old == -1) {
2658 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2659 }
2660 }
2661 state->mCommand = FastMixerState::MIX_WRITE;
2662 sq->end();
2663 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002664 if (kUseFastMixer == FastMixer_Dynamic) {
2665 mNormalSink = mPipeSink;
2666 }
Glenn Kasten58912562012-04-03 10:45:00 -07002667 } else {
2668 sq->end(false /*didModify*/);
2669 }
2670 }
2671 PlaybackThread::threadLoop_write();
2672}
2673
Glenn Kasten000f0e32012-03-01 17:10:56 -08002674// shared by MIXER and DIRECT, overridden by DUPLICATING
2675void AudioFlinger::PlaybackThread::threadLoop_write()
2676{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002677 // FIXME rewrite to reduce number of system calls
2678 mLastWriteTime = systemTime();
2679 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002680 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002681
Eric Laurent67c0a582012-05-01 19:31:12 -07002682 // If an NBAIO sink is present, use it to write the normal mixer's submix
2683 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002684#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002685 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002686#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002687 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002688#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002689 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002690#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002691 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002692#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002693 if (framesWritten > 0) {
2694 bytesWritten = framesWritten << mBitShift;
2695 } else {
2696 bytesWritten = framesWritten;
2697 }
2698 // otherwise use the HAL / AudioStreamOut directly
2699 } else {
2700 // Direct output thread.
2701 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002702 }
2703
Eric Laurent67c0a582012-05-01 19:31:12 -07002704 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002705 mNumWrites++;
2706 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002707}
2708
Glenn Kasten58912562012-04-03 10:45:00 -07002709void AudioFlinger::MixerThread::threadLoop_standby()
2710{
2711 // Idle the fast mixer if it's currently running
2712 if (mFastMixer != NULL) {
2713 FastMixerStateQueue *sq = mFastMixer->sq();
2714 FastMixerState *state = sq->begin();
2715 if (!(state->mCommand & FastMixerState::IDLE)) {
2716 state->mCommand = FastMixerState::COLD_IDLE;
2717 state->mColdFutexAddr = &mFastMixerFutex;
2718 state->mColdGen++;
2719 mFastMixerFutex = 0;
2720 sq->end();
2721 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2722 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002723 if (kUseFastMixer == FastMixer_Dynamic) {
2724 mNormalSink = mOutputSink;
2725 }
Glenn Kasten58912562012-04-03 10:45:00 -07002726 } else {
2727 sq->end(false /*didModify*/);
2728 }
2729 }
2730 PlaybackThread::threadLoop_standby();
2731}
2732
Glenn Kasten000f0e32012-03-01 17:10:56 -08002733// shared by MIXER and DIRECT, overridden by DUPLICATING
2734void AudioFlinger::PlaybackThread::threadLoop_standby()
2735{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002736 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2737 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002738}
2739
2740void AudioFlinger::MixerThread::threadLoop_mix()
2741{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002742 // obtain the presentation timestamp of the next output buffer
2743 int64_t pts;
2744 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002745
Glenn Kasten952eeb22012-03-06 11:30:57 -08002746 if (NULL != mOutput->stream->get_next_write_timestamp) {
2747 status = mOutput->stream->get_next_write_timestamp(
2748 mOutput->stream, &pts);
2749 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002750
Glenn Kasten952eeb22012-03-06 11:30:57 -08002751 if (status != NO_ERROR) {
2752 pts = AudioBufferProvider::kInvalidPTS;
2753 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002754
Glenn Kasten952eeb22012-03-06 11:30:57 -08002755 // mix buffers...
2756 mAudioMixer->process(pts);
2757 // increase sleep time progressively when application underrun condition clears.
2758 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2759 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2760 // such that we would underrun the audio HAL.
2761 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2762 sleepTimeShift--;
2763 }
2764 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002765 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002766 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002767}
2768
2769void AudioFlinger::MixerThread::threadLoop_sleepTime()
2770{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002771 // If no tracks are ready, sleep once for the duration of an output
2772 // buffer size, then write 0s to the output
2773 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002774 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002775 sleepTime = activeSleepTime >> sleepTimeShift;
2776 if (sleepTime < kMinThreadSleepTimeUs) {
2777 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002779 // reduce sleep time in case of consecutive application underruns to avoid
2780 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2781 // duration we would end up writing less data than needed by the audio HAL if
2782 // the condition persists.
2783 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2784 sleepTimeShift++;
2785 }
2786 } else {
2787 sleepTime = idleSleepTime;
2788 }
2789 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002790 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002791 memset (mMixBuffer, 0, mixBufferSize);
2792 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002793 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002794 }
2795 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796}
2797
2798// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002799AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002800 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801{
2802
Glenn Kasten29c23c32012-01-26 13:37:52 -08002803 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002805 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 size_t mixedTracks = 0;
2807 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002808 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002809 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002810 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811
2812 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002813 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814
Eric Laurent571d49c2010-08-11 05:20:11 -07002815 if (masterMute) {
2816 masterVolume = 0;
2817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002819 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002821 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002822 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 masterVolume = (float)((v + (1 << 23)) >> 24);
2824 chain.clear();
2825 }
2826
Glenn Kasten288ed212012-04-25 17:52:27 -07002827 // prepare a new state to push
2828 FastMixerStateQueue *sq = NULL;
2829 FastMixerState *state = NULL;
2830 bool didModify = false;
2831 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2832 if (mFastMixer != NULL) {
2833 sq = mFastMixer->sq();
2834 state = sq->begin();
2835 }
2836
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002838 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839 if (t == 0) continue;
2840
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002841 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002843
Glenn Kasten288ed212012-04-25 17:52:27 -07002844 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002845 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002846
2847 // It's theoretically possible (though unlikely) for a fast track to be created
2848 // and then removed within the same normal mix cycle. This is not a problem, as
2849 // the track never becomes active so it's fast mixer slot is never touched.
2850 // The converse, of removing an (active) track and then creating a new track
2851 // at the identical fast mixer slot within the same normal mix cycle,
2852 // is impossible because the slot isn't marked available until the end of each cycle.
2853 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002854 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2855 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002856 FastTrack *fastTrack = &state->mFastTracks[j];
2857
2858 // Determine whether the track is currently in underrun condition,
2859 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002860 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2861 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002862 uint32_t recentFull = (underruns.mBitFields.mFull -
2863 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2864 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2865 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2866 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2867 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2868 uint32_t recentUnderruns = recentPartial + recentEmpty;
2869 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002870 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002871 // or stopped which can occur when flush() is called while active
2872 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002873 track->mUnderrunCount += recentUnderruns;
2874 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002875
Glenn Kastend08f48c2012-05-01 18:14:02 -07002876 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002877 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002878 bool isActive = true;
2879 switch (track->mState) {
2880 case TrackBase::STOPPING_1:
2881 // track stays active in STOPPING_1 state until first underrun
2882 if (recentUnderruns > 0) {
2883 track->mState = TrackBase::STOPPING_2;
2884 }
2885 break;
2886 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002887 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002888 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002889 break;
2890 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002891 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002892 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002893 break;
2894 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002895 if (recentFull > 0 || recentPartial > 0) {
2896 // track has provided at least some frames recently: reset retry count
2897 track->mRetryCount = kMaxTrackRetries;
2898 }
2899 if (recentUnderruns == 0) {
2900 // no recent underruns: stay active
2901 break;
2902 }
2903 // there has recently been an underrun of some kind
2904 if (track->sharedBuffer() == 0) {
2905 // were any of the recent underruns "empty" (no frames available)?
2906 if (recentEmpty == 0) {
2907 // no, then ignore the partial underruns as they are allowed indefinitely
2908 break;
2909 }
2910 // there has recently been an "empty" underrun: decrement the retry counter
2911 if (--(track->mRetryCount) > 0) {
2912 break;
2913 }
2914 // indicate to client process that the track was disabled because of underrun;
2915 // it will then automatically call start() when data is available
2916 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2917 // remove from active list, but state remains ACTIVE [confusing but true]
2918 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002919 break;
2920 }
2921 // fall through
2922 case TrackBase::STOPPING_2:
2923 case TrackBase::PAUSED:
2924 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002925 case TrackBase::STOPPED:
2926 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002927 // Check for presentation complete if track is inactive
2928 // We have consumed all the buffers of this track.
2929 // This would be incomplete if we auto-paused on underrun
2930 {
2931 size_t audioHALFrames =
2932 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2933 size_t framesWritten =
2934 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2935 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2936 // track stays in active list until presentation is complete
2937 break;
2938 }
2939 }
2940 if (track->isStopping_2()) {
2941 track->mState = TrackBase::STOPPED;
2942 }
2943 if (track->isStopped()) {
2944 // Can't reset directly, as fast mixer is still polling this track
2945 // track->reset();
2946 // So instead mark this track as needing to be reset after push with ack
2947 resetMask |= 1 << i;
2948 }
2949 isActive = false;
2950 break;
2951 case TrackBase::IDLE:
2952 default:
2953 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002954 }
2955
2956 if (isActive) {
2957 // was it previously inactive?
2958 if (!(state->mTrackMask & (1 << j))) {
2959 ExtendedAudioBufferProvider *eabp = track;
2960 VolumeProvider *vp = track;
2961 fastTrack->mBufferProvider = eabp;
2962 fastTrack->mVolumeProvider = vp;
2963 fastTrack->mSampleRate = track->mSampleRate;
2964 fastTrack->mChannelMask = track->mChannelMask;
2965 fastTrack->mGeneration++;
2966 state->mTrackMask |= 1 << j;
2967 didModify = true;
2968 // no acknowledgement required for newly active tracks
2969 }
2970 // cache the combined master volume and stream type volume for fast mixer; this
2971 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2972 track->mCachedVolume = track->isMuted() ?
2973 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2974 ++fastTracks;
2975 } else {
2976 // was it previously active?
2977 if (state->mTrackMask & (1 << j)) {
2978 fastTrack->mBufferProvider = NULL;
2979 fastTrack->mGeneration++;
2980 state->mTrackMask &= ~(1 << j);
2981 didModify = true;
2982 // If any fast tracks were removed, we must wait for acknowledgement
2983 // because we're about to decrement the last sp<> on those tracks.
2984 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002985 } else {
2986 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002987 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002988 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002989 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07002990 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002991 }
2992 continue;
2993 }
2994
2995 { // local variable scope to avoid goto warning
2996
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 audio_track_cblk_t* cblk = track->cblk();
2998
2999 // The first time a track is added we wait
3000 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003001 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003002 // make sure that we have enough frames to mix one full buffer.
3003 // enforce this condition only once to enable draining the buffer in case the client
3004 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003005 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003006 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003007 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003008 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003009 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003010 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003011 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003012 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003013 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003014 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003015 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003016 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003017 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3018 // the minimum track buffer size is normally twice the number of frames necessary
3019 // to fill one buffer and the resampler should not leave more than one buffer worth
3020 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003021 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003022 }
3023 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003024 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025 !track->isPaused() && !track->isTerminated())
3026 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003027 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028
3029 mixedTracks++;
3030
3031 // track->mainBuffer() != mMixBuffer means there is an effect chain
3032 // connected to the track
3033 chain.clear();
3034 if (track->mainBuffer() != mMixBuffer) {
3035 chain = getEffectChain_l(track->sessionId());
3036 // Delegate volume control to effect in track effect chain if needed
3037 if (chain != 0) {
3038 tracksWithEffect++;
3039 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003040 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003041 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 }
3043 }
3044
3045
3046 int param = AudioMixer::VOLUME;
3047 if (track->mFillingUpStatus == Track::FS_FILLED) {
3048 // no ramp for the first volume setting
3049 track->mFillingUpStatus = Track::FS_ACTIVE;
3050 if (track->mState == TrackBase::RESUMING) {
3051 track->mState = TrackBase::ACTIVE;
3052 param = AudioMixer::RAMP_VOLUME;
3053 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003054 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 } else if (cblk->server != 0) {
3056 // If the track is stopped before the first frame was mixed,
3057 // do not apply ramp
3058 param = AudioMixer::RAMP_VOLUME;
3059 }
3060
3061 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003062 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003063 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003064 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003065 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 if (track->isPausing()) {
3067 track->setPaused();
3068 }
3069 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003070
Mathias Agopian65ab4712010-07-14 17:59:35 -07003071 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003072 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003074 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003075 vl = vlr & 0xFFFF;
3076 vr = vlr >> 16;
3077 // track volumes come from shared memory, so can't be trusted and must be clamped
3078 if (vl > MAX_GAIN_INT) {
3079 ALOGV("Track left volume out of range: %04X", vl);
3080 vl = MAX_GAIN_INT;
3081 }
3082 if (vr > MAX_GAIN_INT) {
3083 ALOGV("Track right volume out of range: %04X", vr);
3084 vr = MAX_GAIN_INT;
3085 }
3086 // now apply the master volume and stream type volume
3087 vl = (uint32_t)(v * vl) << 12;
3088 vr = (uint32_t)(v * vr) << 12;
3089 // assuming master volume and stream type volume each go up to 1.0,
3090 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091
Glenn Kasten05632a52012-01-03 14:22:33 -08003092 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3093 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003094 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003095 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003096 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003097 }
3098 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003100 // Delegate volume control to effect in track effect chain if needed
3101 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3102 // Do not ramp volume if volume is controlled by effect
3103 param = AudioMixer::VOLUME;
3104 track->mHasVolumeController = true;
3105 } else {
3106 // force no volume ramp when volume controller was just disabled or removed
3107 // from effect chain to avoid volume spike
3108 if (track->mHasVolumeController) {
3109 param = AudioMixer::VOLUME;
3110 }
3111 track->mHasVolumeController = false;
3112 }
3113
3114 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003115 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003116 vl = (vl + (1 << 11)) >> 12;
3117 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3118 vr = (vr + (1 << 11)) >> 12;
3119 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003120
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003121 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 -07003122
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003124 mAudioMixer->setBufferProvider(name, track);
3125 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003127 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3128 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3129 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003131 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 AudioMixer::TRACK,
3133 AudioMixer::FORMAT, (void *)track->format());
3134 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003135 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003137 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003139 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 AudioMixer::RESAMPLE,
3141 AudioMixer::SAMPLE_RATE,
3142 (void *)(cblk->sampleRate));
3143 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003144 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 AudioMixer::TRACK,
3146 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3147 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003148 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 AudioMixer::TRACK,
3150 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3151
3152 // reset retry count
3153 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003154
Eric Laurent27741442012-01-17 19:20:12 -08003155 // If one track is ready, set the mixer ready if:
3156 // - the mixer was not ready during previous round OR
3157 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003158 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003159 mixerStatus != MIXER_TRACKS_ENABLED) {
3160 mixerStatus = MIXER_TRACKS_READY;
3161 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003163 // clear effect chain input buffer if an active track underruns to avoid sending
3164 // previous audio buffer again to effects
3165 chain = getEffectChain_l(track->sessionId());
3166 if (chain != 0) {
3167 chain->clearInputBuffer();
3168 }
3169
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003170 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurent83faee02012-04-27 18:24:29 -07003171 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3172 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 // We have consumed all the buffers of this track.
3174 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003175 // TODO: use actual buffer filling status instead of latency when available from
3176 // audio HAL
3177 size_t audioHALFrames =
3178 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3179 size_t framesWritten =
3180 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3181 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003182 if (track->isStopped()) {
3183 track->reset();
3184 }
Eric Laurenta011e352012-03-29 15:51:43 -07003185 tracksToRemove->add(track);
3186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003188 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 // No buffers for this track. Give it a few chances to
3190 // fill a buffer, then remove it from active list.
3191 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003192 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003194 // indicate to client process that the track was disabled because of underrun;
3195 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003196 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003197 // If one track is not ready, mark the mixer also not ready if:
3198 // - the mixer was ready during previous round OR
3199 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003200 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003201 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202 mixerStatus = MIXER_TRACKS_ENABLED;
3203 }
3204 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003205 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 }
Glenn Kasten58912562012-04-03 10:45:00 -07003207
3208 } // local variable scope to avoid goto warning
3209track_is_ready: ;
3210
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 }
3212
Glenn Kasten288ed212012-04-25 17:52:27 -07003213 // Push the new FastMixer state if necessary
3214 if (didModify) {
3215 state->mFastTracksGen++;
3216 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3217 if (kUseFastMixer == FastMixer_Dynamic &&
3218 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3219 state->mCommand = FastMixerState::COLD_IDLE;
3220 state->mColdFutexAddr = &mFastMixerFutex;
3221 state->mColdGen++;
3222 mFastMixerFutex = 0;
3223 if (kUseFastMixer == FastMixer_Dynamic) {
3224 mNormalSink = mOutputSink;
3225 }
3226 // If we go into cold idle, need to wait for acknowledgement
3227 // so that fast mixer stops doing I/O.
3228 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3229 }
3230 sq->end();
3231 }
3232 if (sq != NULL) {
3233 sq->end(didModify);
3234 sq->push(block);
3235 }
3236
3237 // Now perform the deferred reset on fast tracks that have stopped
3238 while (resetMask != 0) {
3239 size_t i = __builtin_ctz(resetMask);
3240 ALOG_ASSERT(i < count);
3241 resetMask &= ~(1 << i);
3242 sp<Track> t = mActiveTracks[i].promote();
3243 if (t == 0) continue;
3244 Track* track = t.get();
3245 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3246 track->reset();
3247 }
Glenn Kasten58912562012-04-03 10:45:00 -07003248
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 // remove all the tracks that need to be...
3250 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003251 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 for (size_t i=0 ; i<count ; i++) {
3253 const sp<Track>& track = tracksToRemove->itemAt(i);
3254 mActiveTracks.remove(track);
3255 if (track->mainBuffer() != mMixBuffer) {
3256 chain = getEffectChain_l(track->sessionId());
3257 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003258 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003259 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 }
3261 }
3262 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003263 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 }
3265 }
3266 }
3267
3268 // mix buffer must be cleared if all tracks are connected to an
3269 // effect chain as in this case the mixer will not write to
3270 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003271 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3272 // FIXME as a performance optimization, should remember previous zero status
3273 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 }
3275
Glenn Kasten58912562012-04-03 10:45:00 -07003276 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003277 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003278 if (fastTracks > 0) {
3279 mixerStatus = MIXER_TRACKS_READY;
3280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 return mixerStatus;
3282}
3283
Glenn Kasten66fcab92012-02-24 14:59:21 -08003284/*
3285The derived values that are cached:
3286 - mixBufferSize from frame count * frame size
3287 - activeSleepTime from activeSleepTimeUs()
3288 - idleSleepTime from idleSleepTimeUs()
3289 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3290 - maxPeriod from frame count and sample rate (MIXER only)
3291
3292The parameters that affect these derived values are:
3293 - frame count
3294 - frame size
3295 - sample rate
3296 - device type: A2DP or not
3297 - device latency
3298 - format: PCM or not
3299 - active sleep time
3300 - idle sleep time
3301*/
3302
3303void AudioFlinger::PlaybackThread::cacheParameters_l()
3304{
Glenn Kasten58912562012-04-03 10:45:00 -07003305 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003306 activeSleepTime = activeSleepTimeUs();
3307 idleSleepTime = idleSleepTimeUs();
3308}
3309
Glenn Kastenfff6d712012-01-12 16:38:12 -08003310void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311{
Steve Block3856b092011-10-20 11:56:00 +01003312 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003313 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003315
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 size_t size = mTracks.size();
3317 for (size_t i = 0; i < size; i++) {
3318 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003319 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003320 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322 }
3323 }
3324}
3325
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003327int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003329 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330}
3331
3332// deleteTrackName_l() must be called with ThreadBase::mLock held
3333void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3334{
Steve Block3856b092011-10-20 11:56:00 +01003335 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 mAudioMixer->deleteTrackName(name);
3337}
3338
3339// checkForNewParameters_l() must be called with ThreadBase::mLock held
3340bool AudioFlinger::MixerThread::checkForNewParameters_l()
3341{
Glenn Kasten58912562012-04-03 10:45:00 -07003342 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3343 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 bool reconfig = false;
3345
3346 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003347
3348 if (mFastMixer != NULL) {
3349 FastMixerStateQueue *sq = mFastMixer->sq();
3350 FastMixerState *state = sq->begin();
3351 if (!(state->mCommand & FastMixerState::IDLE)) {
3352 previousCommand = state->mCommand;
3353 state->mCommand = FastMixerState::HOT_IDLE;
3354 sq->end();
3355 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3356 } else {
3357 sq->end(false /*didModify*/);
3358 }
3359 }
3360
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 status_t status = NO_ERROR;
3362 String8 keyValuePair = mNewParameters[0];
3363 AudioParameter param = AudioParameter(keyValuePair);
3364 int value;
3365
3366 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3367 reconfig = true;
3368 }
3369 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003370 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 status = BAD_VALUE;
3372 } else {
3373 reconfig = true;
3374 }
3375 }
3376 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003377 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 status = BAD_VALUE;
3379 } else {
3380 reconfig = true;
3381 }
3382 }
3383 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3384 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003385 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 // if frame count is changed after track creation
3387 if (!mTracks.isEmpty()) {
3388 status = INVALID_OPERATION;
3389 } else {
3390 reconfig = true;
3391 }
3392 }
3393 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003394#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003395 // when changing the audio output device, call addBatteryData to notify
3396 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003397 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003398 uint32_t params = 0;
3399 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003400 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003401 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3402 }
3403
3404 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003405 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003406 // check if any other device (except speaker) is on
3407 if (value & deviceWithoutSpeaker ) {
3408 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3409 }
3410
3411 if (params != 0) {
3412 addBatteryData(params);
3413 }
3414 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003415#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003416
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 // forward device change to effects that have requested to be
3418 // aware of attached audio device.
3419 mDevice = (uint32_t)value;
3420 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003421 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 }
3423 }
3424
3425 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003426 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003427 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003429 mOutput->stream->common.standby(&mOutput->stream->common);
3430 mStandby = true;
3431 mBytesWritten = 0;
3432 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003433 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 }
3435 if (status == NO_ERROR && reconfig) {
3436 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003437 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3438 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003440 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003442 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 if (name < 0) break;
3444 mTracks[i]->mName = name;
3445 // limit track sample rate to 2 x new output sample rate
3446 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3447 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3448 }
3449 }
3450 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3451 }
3452 }
3453
3454 mNewParameters.removeAt(0);
3455
3456 mParamStatus = status;
3457 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003458 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3459 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003460 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 }
Glenn Kasten58912562012-04-03 10:45:00 -07003462
3463 if (!(previousCommand & FastMixerState::IDLE)) {
3464 ALOG_ASSERT(mFastMixer != NULL);
3465 FastMixerStateQueue *sq = mFastMixer->sq();
3466 FastMixerState *state = sq->begin();
3467 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3468 state->mCommand = previousCommand;
3469 sq->end();
3470 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3471 }
3472
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 return reconfig;
3474}
3475
3476status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3477{
3478 const size_t SIZE = 256;
3479 char buffer[SIZE];
3480 String8 result;
3481
3482 PlaybackThread::dumpInternals(fd, args);
3483
3484 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3485 result.append(buffer);
3486 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003487
3488 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3489 FastMixerDumpState copy = mFastMixerDumpState;
3490 copy.dump(fd);
3491
Glenn Kasten39993082012-05-31 13:40:27 -07003492#ifdef STATE_QUEUE_DUMP
3493 // Similar for state queue
3494 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3495 observerCopy.dump(fd);
3496 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3497 mutatorCopy.dump(fd);
3498#endif
3499
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003500 // Write the tee output to a .wav file
3501 NBAIO_Source *teeSource = mTeeSource.get();
3502 if (teeSource != NULL) {
3503 char teePath[64];
3504 struct timeval tv;
3505 gettimeofday(&tv, NULL);
3506 struct tm tm;
3507 localtime_r(&tv.tv_sec, &tm);
3508 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3509 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3510 if (teeFd >= 0) {
3511 char wavHeader[44];
3512 memcpy(wavHeader,
3513 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3514 sizeof(wavHeader));
3515 NBAIO_Format format = teeSource->format();
3516 unsigned channelCount = Format_channelCount(format);
3517 ALOG_ASSERT(channelCount <= FCC_2);
3518 unsigned sampleRate = Format_sampleRate(format);
3519 wavHeader[22] = channelCount; // number of channels
3520 wavHeader[24] = sampleRate; // sample rate
3521 wavHeader[25] = sampleRate >> 8;
3522 wavHeader[32] = channelCount * 2; // block alignment
3523 write(teeFd, wavHeader, sizeof(wavHeader));
3524 size_t total = 0;
3525 bool firstRead = true;
3526 for (;;) {
3527#define TEE_SINK_READ 1024
3528 short buffer[TEE_SINK_READ * FCC_2];
3529 size_t count = TEE_SINK_READ;
3530 ssize_t actual = teeSource->read(buffer, count);
3531 bool wasFirstRead = firstRead;
3532 firstRead = false;
3533 if (actual <= 0) {
3534 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3535 continue;
3536 }
3537 break;
3538 }
3539 ALOG_ASSERT(actual <= count);
3540 write(teeFd, buffer, actual * channelCount * sizeof(short));
3541 total += actual;
3542 }
3543 lseek(teeFd, (off_t) 4, SEEK_SET);
3544 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3545 write(teeFd, &temp, sizeof(temp));
3546 lseek(teeFd, (off_t) 40, SEEK_SET);
3547 temp = total * channelCount * sizeof(short);
3548 write(teeFd, &temp, sizeof(temp));
3549 close(teeFd);
3550 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3551 } else {
3552 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3553 }
3554 }
3555
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 return NO_ERROR;
3557}
3558
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003559uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560{
Glenn Kasten58912562012-04-03 10:45:00 -07003561 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562}
3563
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003564uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003565{
Glenn Kasten58912562012-04-03 10:45:00 -07003566 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003567}
3568
Glenn Kasten66fcab92012-02-24 14:59:21 -08003569void AudioFlinger::MixerThread::cacheParameters_l()
3570{
3571 PlaybackThread::cacheParameters_l();
3572
3573 // FIXME: Relaxed timing because of a certain device that can't meet latency
3574 // Should be reduced to 2x after the vendor fixes the driver issue
3575 // increase threshold again due to low power audio mode. The way this warning
3576 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003577 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003578}
3579
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003581AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3582 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003583 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003584 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586}
3587
3588AudioFlinger::DirectOutputThread::~DirectOutputThread()
3589{
3590}
3591
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003592AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3593 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003594)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003596 sp<Track> trackToRemove;
3597
Glenn Kastenfec279f2012-03-08 07:47:15 -08003598 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599
Glenn Kasten952eeb22012-03-06 11:30:57 -08003600 // find out which tracks need to be processed
3601 if (mActiveTracks.size() != 0) {
3602 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003603 // The track died recently
3604 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605
Glenn Kasten952eeb22012-03-06 11:30:57 -08003606 Track* const track = t.get();
3607 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608
Glenn Kasten952eeb22012-03-06 11:30:57 -08003609 // The first time a track is added we wait
3610 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003611 uint32_t minFrames;
3612 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3613 minFrames = mNormalFrameCount;
3614 } else {
3615 minFrames = 1;
3616 }
3617 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003618 !track->isPaused() && !track->isTerminated())
3619 {
3620 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621
Glenn Kasten952eeb22012-03-06 11:30:57 -08003622 if (track->mFillingUpStatus == Track::FS_FILLED) {
3623 track->mFillingUpStatus = Track::FS_ACTIVE;
3624 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003625 if (track->mState == TrackBase::RESUMING) {
3626 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003627 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003628 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003629
Glenn Kasten952eeb22012-03-06 11:30:57 -08003630 // compute volume for this track
3631 float left, right;
3632 if (track->isMuted() || mMasterMute || track->isPausing() ||
3633 mStreamTypes[track->streamType()].mute) {
3634 left = right = 0;
3635 if (track->isPausing()) {
3636 track->setPaused();
3637 }
3638 } else {
3639 float typeVolume = mStreamTypes[track->streamType()].volume;
3640 float v = mMasterVolume * typeVolume;
3641 uint32_t vlr = cblk->getVolumeLR();
3642 float v_clamped = v * (vlr & 0xFFFF);
3643 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3644 left = v_clamped/MAX_GAIN;
3645 v_clamped = v * (vlr >> 16);
3646 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3647 right = v_clamped/MAX_GAIN;
3648 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649
Glenn Kasten952eeb22012-03-06 11:30:57 -08003650 if (left != mLeftVolFloat || right != mRightVolFloat) {
3651 mLeftVolFloat = left;
3652 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653
Glenn Kasten952eeb22012-03-06 11:30:57 -08003654 // Convert volumes from float to 8.24
3655 uint32_t vl = (uint32_t)(left * (1 << 24));
3656 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657
Glenn Kasten952eeb22012-03-06 11:30:57 -08003658 // Delegate volume control to effect in track effect chain if needed
3659 // only one effect chain can be present on DirectOutputThread, so if
3660 // there is one, the track is connected to it
3661 if (!mEffectChains.isEmpty()) {
3662 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003663 mEffectChains[0]->setVolume_l(&vl, &vr);
3664 left = (float)vl / (1 << 24);
3665 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003666 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003667 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003668 }
3669
3670 // reset retry count
3671 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003672 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003673 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003674 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003675 // clear effect chain input buffer if an active track underruns to avoid sending
3676 // previous audio buffer again to effects
3677 if (!mEffectChains.isEmpty()) {
3678 mEffectChains[0]->clearInputBuffer();
3679 }
3680
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003682 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3683 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003684 // We have consumed all the buffers of this track.
3685 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003686 // TODO: implement behavior for compressed audio
3687 size_t audioHALFrames =
3688 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3689 size_t framesWritten =
3690 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3691 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003692 if (track->isStopped()) {
3693 track->reset();
3694 }
Eric Laurenta011e352012-03-29 15:51:43 -07003695 trackToRemove = track;
3696 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003697 } else {
3698 // No buffers for this track. Give it a few chances to
3699 // fill a buffer, then remove it from active list.
3700 if (--(track->mRetryCount) <= 0) {
3701 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3702 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003703 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003704 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705 }
3706 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003707 }
3708 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003710 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003711 // remove all the tracks that need to be...
3712 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003713 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003714 mActiveTracks.remove(trackToRemove);
3715 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003716 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003717 trackToRemove->sessionId());
3718 mEffectChains[0]->decActiveTrackCnt();
3719 }
3720 if (trackToRemove->isTerminated()) {
3721 removeTrack_l(trackToRemove);
3722 }
3723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724
Glenn Kastenfec279f2012-03-08 07:47:15 -08003725 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003726}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727
Glenn Kasten000f0e32012-03-01 17:10:56 -08003728void AudioFlinger::DirectOutputThread::threadLoop_mix()
3729{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 AudioBufferProvider::Buffer buffer;
3731 size_t frameCount = mFrameCount;
3732 int8_t *curBuf = (int8_t *)mMixBuffer;
3733 // output audio to hardware
3734 while (frameCount) {
3735 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003736 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003737 if (CC_UNLIKELY(buffer.raw == NULL)) {
3738 memset(curBuf, 0, frameCount * mFrameSize);
3739 break;
3740 }
3741 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3742 frameCount -= buffer.frameCount;
3743 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003744 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 }
3746 sleepTime = 0;
3747 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003748 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003749
Glenn Kasten000f0e32012-03-01 17:10:56 -08003750}
3751
3752void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3753{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003754 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003755 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003756 sleepTime = activeSleepTime;
3757 } else {
3758 sleepTime = idleSleepTime;
3759 }
3760 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003761 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003762 sleepTime = 0;
3763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764}
3765
3766// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003767int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768{
3769 return 0;
3770}
3771
3772// deleteTrackName_l() must be called with ThreadBase::mLock held
3773void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3774{
3775}
3776
3777// checkForNewParameters_l() must be called with ThreadBase::mLock held
3778bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3779{
3780 bool reconfig = false;
3781
3782 while (!mNewParameters.isEmpty()) {
3783 status_t status = NO_ERROR;
3784 String8 keyValuePair = mNewParameters[0];
3785 AudioParameter param = AudioParameter(keyValuePair);
3786 int value;
3787
3788 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3789 // do not accept frame count changes if tracks are open as the track buffer
3790 // size depends on frame count and correct behavior would not be garantied
3791 // if frame count is changed after track creation
3792 if (!mTracks.isEmpty()) {
3793 status = INVALID_OPERATION;
3794 } else {
3795 reconfig = true;
3796 }
3797 }
3798 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003799 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003800 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003802 mOutput->stream->common.standby(&mOutput->stream->common);
3803 mStandby = true;
3804 mBytesWritten = 0;
3805 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003806 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 }
3808 if (status == NO_ERROR && reconfig) {
3809 readOutputParameters();
3810 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3811 }
3812 }
3813
3814 mNewParameters.removeAt(0);
3815
3816 mParamStatus = status;
3817 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003818 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3819 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003820 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821 }
3822 return reconfig;
3823}
3824
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003825uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826{
3827 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003828 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003829 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 } else {
3831 time = 10000;
3832 }
3833 return time;
3834}
3835
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003836uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837{
3838 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003839 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003840 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841 } else {
3842 time = 10000;
3843 }
3844 return time;
3845}
3846
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003847uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003848{
3849 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003850 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003851 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3852 } else {
3853 time = 10000;
3854 }
3855 return time;
3856}
3857
Glenn Kasten66fcab92012-02-24 14:59:21 -08003858void AudioFlinger::DirectOutputThread::cacheParameters_l()
3859{
3860 PlaybackThread::cacheParameters_l();
3861
3862 // use shorter standby delay as on normal output to release
3863 // hardware resources as soon as possible
3864 standbyDelay = microseconds(activeSleepTime*2);
3865}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003866
Mathias Agopian65ab4712010-07-14 17:59:35 -07003867// ----------------------------------------------------------------------------
3868
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003869AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003870 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003871 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3872 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003873{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874 addOutputTrack(mainThread);
3875}
3876
3877AudioFlinger::DuplicatingThread::~DuplicatingThread()
3878{
3879 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3880 mOutputTracks[i]->destroy();
3881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882}
3883
Glenn Kasten000f0e32012-03-01 17:10:56 -08003884void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003886 // mix buffers...
3887 if (outputsReady(outputTracks)) {
3888 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3889 } else {
3890 memset(mMixBuffer, 0, mixBufferSize);
3891 }
3892 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003893 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003894 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003895}
3896
3897void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3898{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003899 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003900 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003901 sleepTime = activeSleepTime;
3902 } else {
3903 sleepTime = idleSleepTime;
3904 }
3905 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003906 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3907 writeFrames = mNormalFrameCount;
3908 memset(mMixBuffer, 0, mixBufferSize);
3909 } else {
3910 // flush remaining overflow buffers in output tracks
3911 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003912 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003913 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003914 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003915}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916
Glenn Kasten000f0e32012-03-01 17:10:56 -08003917void AudioFlinger::DuplicatingThread::threadLoop_write()
3918{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003919 for (size_t i = 0; i < outputTracks.size(); i++) {
3920 outputTracks[i]->write(mMixBuffer, writeFrames);
3921 }
3922 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003923}
Glenn Kasten688a6402012-02-29 07:57:06 -08003924
Glenn Kasten000f0e32012-03-01 17:10:56 -08003925void AudioFlinger::DuplicatingThread::threadLoop_standby()
3926{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003927 // DuplicatingThread implements standby by stopping all tracks
3928 for (size_t i = 0; i < outputTracks.size(); i++) {
3929 outputTracks[i]->stop();
3930 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931}
3932
Glenn Kastenfa26a852012-03-06 11:28:04 -08003933void AudioFlinger::DuplicatingThread::saveOutputTracks()
3934{
3935 outputTracks = mOutputTracks;
3936}
3937
3938void AudioFlinger::DuplicatingThread::clearOutputTracks()
3939{
3940 outputTracks.clear();
3941}
3942
Mathias Agopian65ab4712010-07-14 17:59:35 -07003943void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3944{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003945 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003946 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003947 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003948 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003949 this,
3950 mSampleRate,
3951 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003952 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953 frameCount);
3954 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003955 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003957 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003958 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003959 }
3960}
3961
3962void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3963{
3964 Mutex::Autolock _l(mLock);
3965 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003966 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003967 mOutputTracks[i]->destroy();
3968 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003969 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003970 return;
3971 }
3972 }
Steve Block3856b092011-10-20 11:56:00 +01003973 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974}
3975
Glenn Kasten438b0362012-03-06 11:24:48 -08003976// caller must hold mLock
3977void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978{
3979 mWaitTimeMs = UINT_MAX;
3980 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3981 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003982 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3984 if (waitTimeMs < mWaitTimeMs) {
3985 mWaitTimeMs = waitTimeMs;
3986 }
3987 }
3988 }
3989}
3990
3991
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003992bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993{
3994 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003995 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003997 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998 return false;
3999 }
4000 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4001 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004002 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003 return false;
4004 }
4005 }
4006 return true;
4007}
4008
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004009uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010{
4011 return (mWaitTimeMs * 1000) / 2;
4012}
4013
Glenn Kasten66fcab92012-02-24 14:59:21 -08004014void AudioFlinger::DuplicatingThread::cacheParameters_l()
4015{
4016 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4017 updateWaitTime_l();
4018
4019 MixerThread::cacheParameters_l();
4020}
4021
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022// ----------------------------------------------------------------------------
4023
4024// TrackBase constructor must be called with AudioFlinger::mLock held
4025AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004026 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 const sp<Client>& client,
4028 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004029 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004030 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 const sp<IMemory>& sharedBuffer,
4033 int sessionId)
4034 : RefBase(),
4035 mThread(thread),
4036 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004037 mCblk(NULL),
4038 // mBuffer
4039 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040 mFrameCount(0),
4041 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004042 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004044 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004046 // mChannelCount
4047 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048{
Steve Block3856b092011-10-20 11:56:00 +01004049 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050
Steve Blockb8a80522011-12-20 16:23:08 +00004051 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004052 size_t size = sizeof(audio_track_cblk_t);
4053 uint8_t channelCount = popcount(channelMask);
4054 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4055 if (sharedBuffer == 0) {
4056 size += bufferSize;
4057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004059 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 mCblkMemory = client->heap()->allocate(size);
4061 if (mCblkMemory != 0) {
4062 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004063 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064 new(mCblk) audio_track_cblk_t();
4065 // clear all buffers
4066 mCblk->frameCount = frameCount;
4067 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004068// uncomment the following lines to quickly test 32-bit wraparound
4069// mCblk->user = 0xffff0000;
4070// mCblk->server = 0xffff0000;
4071// mCblk->userBase = 0xffff0000;
4072// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004073 mChannelCount = channelCount;
4074 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075 if (sharedBuffer == 0) {
4076 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4077 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4078 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004079 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080 mCblk->flags = CBLK_UNDERRUN_ON;
4081 } else {
4082 mBuffer = sharedBuffer->pointer();
4083 }
4084 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4085 }
4086 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004087 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088 client->heap()->dump("AudioTrack");
4089 return;
4090 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004091 } else {
4092 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004093 // construct the shared structure in-place.
4094 new(mCblk) audio_track_cblk_t();
4095 // clear all buffers
4096 mCblk->frameCount = frameCount;
4097 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004098// uncomment the following lines to quickly test 32-bit wraparound
4099// mCblk->user = 0xffff0000;
4100// mCblk->server = 0xffff0000;
4101// mCblk->userBase = 0xffff0000;
4102// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004103 mChannelCount = channelCount;
4104 mChannelMask = channelMask;
4105 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4106 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4107 // Force underrun condition to avoid false underrun callback until first data is
4108 // written to buffer (other flags are cleared)
4109 mCblk->flags = CBLK_UNDERRUN_ON;
4110 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004111 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112}
4113
4114AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4115{
Glenn Kastena0d68332012-01-27 16:47:15 -08004116 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004117 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004119 } else {
4120 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121 }
4122 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004123 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004124 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004125 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004127 // If the client's reference count drops to zero, the associated destructor
4128 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4129 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 mClient.clear();
4131 }
4132}
4133
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004134// AudioBufferProvider interface
4135// getNextBuffer() = 0;
4136// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4138{
Glenn Kastene0feee32011-12-13 11:53:26 -08004139 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004141 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004142 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 buffer->frameCount = 0;
4144}
4145
4146bool AudioFlinger::ThreadBase::TrackBase::step() {
4147 bool result;
4148 audio_track_cblk_t* cblk = this->cblk();
4149
4150 result = cblk->stepServer(mFrameCount);
4151 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004152 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004153 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154 }
4155 return result;
4156}
4157
4158void AudioFlinger::ThreadBase::TrackBase::reset() {
4159 audio_track_cblk_t* cblk = this->cblk();
4160
4161 cblk->user = 0;
4162 cblk->server = 0;
4163 cblk->userBase = 0;
4164 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004165 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004166 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167}
4168
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4170 return (int)mCblk->sampleRate;
4171}
4172
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4174 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004175 size_t frameSize = cblk->frameSize;
4176 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4177 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178
4179 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004180 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4181 "TrackBase::getBuffer buffer out of range:\n"
4182 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4183 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004185 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186
4187 return bufferStart;
4188}
4189
Eric Laurenta011e352012-03-29 15:51:43 -07004190status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4191{
4192 mSyncEvents.add(event);
4193 return NO_ERROR;
4194}
4195
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196// ----------------------------------------------------------------------------
4197
4198// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4199AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004200 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004202 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004204 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004205 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 int frameCount,
4207 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004208 int sessionId,
4209 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004210 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004211 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004212 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004213 // mRetryCount initialized later when needed
4214 mSharedBuffer(sharedBuffer),
4215 mStreamType(streamType),
4216 mName(-1), // see note below
4217 mMainBuffer(thread->mixBuffer()),
4218 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004219 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004220 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004221 mFlags(flags),
4222 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004223 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004224 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225{
4226 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4228 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004229 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004230 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4231 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
4232 if (mName < 0) {
4233 ALOGE("no more track names available");
4234 return;
4235 }
4236 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004237 if (flags & IAudioFlinger::TRACK_FAST) {
4238 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4239 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4240 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004241 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004242 // FIXME This is too eager. We allocate a fast track index before the
4243 // fast track becomes active. Since fast tracks are a scarce resource,
4244 // this means we are potentially denying other more important fast tracks from
4245 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004246 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004247 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004248 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004249 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004250 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004252 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004253}
4254
4255AudioFlinger::PlaybackThread::Track::~Track()
4256{
Steve Block3856b092011-10-20 11:56:00 +01004257 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258 sp<ThreadBase> thread = mThread.promote();
4259 if (thread != 0) {
4260 Mutex::Autolock _l(thread->mLock);
4261 mState = TERMINATED;
4262 }
4263}
4264
4265void AudioFlinger::PlaybackThread::Track::destroy()
4266{
4267 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4268 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004269 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270 // we must acquire a strong reference on this Track before locking mLock
4271 // here so that the destructor is called only when exiting this function.
4272 // On the other hand, as long as Track::destroy() is only called by
4273 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4274 // this Track with its member mTrack.
4275 sp<Track> keep(this);
4276 { // scope for mLock
4277 sp<ThreadBase> thread = mThread.promote();
4278 if (thread != 0) {
4279 if (!isOutputTrack()) {
4280 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004281 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004282
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004283#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004284 // to track the speaker usage
4285 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004286#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287 }
4288 AudioSystem::releaseOutput(thread->id());
4289 }
4290 Mutex::Autolock _l(thread->mLock);
4291 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4292 playbackThread->destroyTrack_l(this);
4293 }
4294 }
4295}
4296
Glenn Kasten288ed212012-04-25 17:52:27 -07004297/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4298{
Glenn Kastene213c862012-04-25 13:46:15 -07004299 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07004300 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004301}
4302
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4304{
Glenn Kasten83d86532012-01-17 14:39:34 -08004305 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004306 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004307 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004308 } else {
4309 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4310 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004311 track_state state = mState;
4312 char stateChar;
4313 switch (state) {
4314 case IDLE:
4315 stateChar = 'I';
4316 break;
4317 case TERMINATED:
4318 stateChar = 'T';
4319 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004320 case STOPPING_1:
4321 stateChar = 's';
4322 break;
4323 case STOPPING_2:
4324 stateChar = '5';
4325 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004326 case STOPPED:
4327 stateChar = 'S';
4328 break;
4329 case RESUMING:
4330 stateChar = 'R';
4331 break;
4332 case ACTIVE:
4333 stateChar = 'A';
4334 break;
4335 case PAUSING:
4336 stateChar = 'p';
4337 break;
4338 case PAUSED:
4339 stateChar = 'P';
4340 break;
Eric Laurent29864602012-05-08 18:57:51 -07004341 case FLUSHED:
4342 stateChar = 'F';
4343 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004344 default:
4345 stateChar = '?';
4346 break;
4347 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004348 char nowInUnderrun;
4349 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4350 case UNDERRUN_FULL:
4351 nowInUnderrun = ' ';
4352 break;
4353 case UNDERRUN_PARTIAL:
4354 nowInUnderrun = '<';
4355 break;
4356 case UNDERRUN_EMPTY:
4357 nowInUnderrun = '*';
4358 break;
4359 default:
4360 nowInUnderrun = '?';
4361 break;
4362 }
Glenn Kastene213c862012-04-25 13:46:15 -07004363 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4364 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004365 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 mStreamType,
4367 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004368 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 mSessionId,
4370 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004371 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004372 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373 mMute,
4374 mFillingUpStatus,
4375 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004376 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4377 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378 mCblk->server,
4379 mCblk->user,
4380 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004381 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004382 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004383 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004384 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385}
4386
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004387// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004388status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004389 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004391 audio_track_cblk_t* cblk = this->cblk();
4392 uint32_t framesReady;
4393 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004395 // Check if last stepServer failed, try to step now
4396 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004397 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4398 // Since the fast mixer is higher priority than client callback thread,
4399 // it does not result in priority inversion for client.
4400 // But a non-blocking solution would be preferable to avoid
4401 // fast mixer being unable to tryLock(), and
4402 // to avoid the extra context switches if the client wakes up,
4403 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004404 if (!step()) goto getNextBuffer_exit;
4405 ALOGV("stepServer recovered");
4406 mStepServerFailed = false;
4407 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004408
Glenn Kasten288ed212012-04-25 17:52:27 -07004409 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004410 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004412 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 uint32_t s = cblk->server;
4414 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4415
4416 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4417 if (framesReq > framesReady) {
4418 framesReq = framesReady;
4419 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004420 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 framesReq = bufferEnd - s;
4422 }
4423
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004424 buffer->raw = getBuffer(s, framesReq);
4425 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004427 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004429 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430
4431getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004432 buffer->raw = NULL;
4433 buffer->frameCount = 0;
4434 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4435 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436}
4437
Glenn Kasten288ed212012-04-25 17:52:27 -07004438// Note that framesReady() takes a mutex on the control block using tryLock().
4439// This could result in priority inversion if framesReady() is called by the normal mixer,
4440// as the normal mixer thread runs at lower
4441// priority than the client's callback thread: there is a short window within framesReady()
4442// during which the normal mixer could be preempted, and the client callback would block.
4443// Another problem can occur if framesReady() is called by the fast mixer:
4444// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4445// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4446size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004447 return mCblk->framesReady();
4448}
4449
Glenn Kasten288ed212012-04-25 17:52:27 -07004450// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004452 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453
John Grossman4ff14ba2012-02-08 16:37:41 -08004454 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4456 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004457 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 return true;
4459 }
4460 return false;
4461}
4462
Glenn Kasten3acbd052012-02-28 10:39:56 -08004463status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004464 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465{
4466 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004467 ALOGV("start(%d), calling pid %d session %d",
4468 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004469
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470 sp<ThreadBase> thread = mThread.promote();
4471 if (thread != 0) {
4472 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004473 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 // here the track could be either new, or restarted
4475 // in both cases "unstop" the track
4476 if (mState == PAUSED) {
4477 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004478 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 } else {
4480 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004481 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482 }
4483
4484 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4485 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004486 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004488
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004489#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004490 // to track the speaker usage
4491 if (status == NO_ERROR) {
4492 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4493 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004494#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 }
4496 if (status == NO_ERROR) {
4497 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4498 playbackThread->addTrack_l(this);
4499 } else {
4500 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004501 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 }
4503 } else {
4504 status = BAD_VALUE;
4505 }
4506 return status;
4507}
4508
4509void AudioFlinger::PlaybackThread::Track::stop()
4510{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004511 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 sp<ThreadBase> thread = mThread.promote();
4513 if (thread != 0) {
4514 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004515 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004516 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 // If the track is not active (PAUSED and buffers full), flush buffers
4518 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4519 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4520 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004521 mState = STOPPED;
4522 } else if (!isFastTrack()) {
4523 mState = STOPPED;
4524 } else {
4525 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4526 // and then to STOPPED and reset() when presentation is complete
4527 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004529 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 }
4531 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4532 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004533 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004534 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004535
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004536#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004537 // to track the speaker usage
4538 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004539#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 }
4541 }
4542}
4543
4544void AudioFlinger::PlaybackThread::Track::pause()
4545{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004546 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547 sp<ThreadBase> thread = mThread.promote();
4548 if (thread != 0) {
4549 Mutex::Autolock _l(thread->mLock);
4550 if (mState == ACTIVE || mState == RESUMING) {
4551 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004552 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 if (!isOutputTrack()) {
4554 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004555 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004557
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004558#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004559 // to track the speaker usage
4560 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004561#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 }
4563 }
4564 }
4565}
4566
4567void AudioFlinger::PlaybackThread::Track::flush()
4568{
Steve Block3856b092011-10-20 11:56:00 +01004569 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 sp<ThreadBase> thread = mThread.promote();
4571 if (thread != 0) {
4572 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004573 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4574 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 return;
4576 }
4577 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004578 // FLUSHED state
4579 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004580 // do not reset the track if it is still in the process of being stopped or paused.
4581 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004582 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004583 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004584 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4585 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4586 reset();
4587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588 }
4589}
4590
4591void AudioFlinger::PlaybackThread::Track::reset()
4592{
4593 // Do not reset twice to avoid discarding data written just after a flush and before
4594 // the audioflinger thread detects the track is stopped.
4595 if (!mResetDone) {
4596 TrackBase::reset();
4597 // Force underrun condition to avoid false underrun callback until first data is
4598 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004599 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4600 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 mFillingUpStatus = FS_FILLING;
4602 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004603 if (mState == FLUSHED) {
4604 mState = IDLE;
4605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 }
4607}
4608
4609void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4610{
4611 mMute = muted;
4612}
4613
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4615{
4616 status_t status = DEAD_OBJECT;
4617 sp<ThreadBase> thread = mThread.promote();
4618 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004619 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4620 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 }
4622 return status;
4623}
4624
4625void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4626{
4627 mAuxEffectId = EffectId;
4628 mAuxBuffer = buffer;
4629}
4630
Eric Laurenta011e352012-03-29 15:51:43 -07004631bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4632 size_t audioHalFrames)
4633{
4634 // a track is considered presented when the total number of frames written to audio HAL
4635 // corresponds to the number of frames written when presentationComplete() is called for the
4636 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4637 if (mPresentationCompleteFrames == 0) {
4638 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4639 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4640 mPresentationCompleteFrames, audioHalFrames);
4641 }
4642 if (framesWritten >= mPresentationCompleteFrames) {
4643 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4644 mSessionId, framesWritten);
4645 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004646 return true;
4647 }
4648 return false;
4649}
4650
4651void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4652{
4653 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4654 if (mSyncEvents[i]->type() == type) {
4655 mSyncEvents[i]->trigger();
4656 mSyncEvents.removeAt(i);
4657 i--;
4658 }
4659 }
4660}
4661
Glenn Kasten58912562012-04-03 10:45:00 -07004662// implement VolumeBufferProvider interface
4663
4664uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4665{
4666 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4667 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4668 uint32_t vlr = mCblk->getVolumeLR();
4669 uint32_t vl = vlr & 0xFFFF;
4670 uint32_t vr = vlr >> 16;
4671 // track volumes come from shared memory, so can't be trusted and must be clamped
4672 if (vl > MAX_GAIN_INT) {
4673 vl = MAX_GAIN_INT;
4674 }
4675 if (vr > MAX_GAIN_INT) {
4676 vr = MAX_GAIN_INT;
4677 }
4678 // now apply the cached master volume and stream type volume;
4679 // this is trusted but lacks any synchronization or barrier so may be stale
4680 float v = mCachedVolume;
4681 vl *= v;
4682 vr *= v;
4683 // re-combine into U4.16
4684 vlr = (vr << 16) | (vl & 0xFFFF);
4685 // FIXME look at mute, pause, and stop flags
4686 return vlr;
4687}
Eric Laurenta011e352012-03-29 15:51:43 -07004688
Eric Laurent29864602012-05-08 18:57:51 -07004689status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4690{
4691 if (mState == TERMINATED || mState == PAUSED ||
4692 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4693 (mState == STOPPED)))) {
4694 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4695 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4696 event->cancel();
4697 return INVALID_OPERATION;
4698 }
4699 TrackBase::setSyncEvent(event);
4700 return NO_ERROR;
4701}
4702
John Grossman4ff14ba2012-02-08 16:37:41 -08004703// timed audio tracks
4704
4705sp<AudioFlinger::PlaybackThread::TimedTrack>
4706AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004707 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004708 const sp<Client>& client,
4709 audio_stream_type_t streamType,
4710 uint32_t sampleRate,
4711 audio_format_t format,
4712 uint32_t channelMask,
4713 int frameCount,
4714 const sp<IMemory>& sharedBuffer,
4715 int sessionId) {
4716 if (!client->reserveTimedTrack())
4717 return NULL;
4718
Glenn Kastena0356762012-03-19 10:38:51 -07004719 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004720 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4721 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004722}
4723
4724AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004725 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004726 const sp<Client>& client,
4727 audio_stream_type_t streamType,
4728 uint32_t sampleRate,
4729 audio_format_t format,
4730 uint32_t channelMask,
4731 int frameCount,
4732 const sp<IMemory>& sharedBuffer,
4733 int sessionId)
4734 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004735 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004736 mQueueHeadInFlight(false),
4737 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004738 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004739 mTimedSilenceBuffer(NULL),
4740 mTimedSilenceBufferSize(0),
4741 mTimedAudioOutputOnTime(false),
4742 mMediaTimeTransformValid(false)
4743{
4744 LocalClock lc;
4745 mLocalTimeFreq = lc.getLocalFreq();
4746
4747 mLocalTimeToSampleTransform.a_zero = 0;
4748 mLocalTimeToSampleTransform.b_zero = 0;
4749 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4750 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4751 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4752 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004753
4754 mMediaTimeToSampleTransform.a_zero = 0;
4755 mMediaTimeToSampleTransform.b_zero = 0;
4756 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4757 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4758 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4759 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004760}
4761
4762AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4763 mClient->releaseTimedTrack();
4764 delete [] mTimedSilenceBuffer;
4765}
4766
4767status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4768 size_t size, sp<IMemory>* buffer) {
4769
4770 Mutex::Autolock _l(mTimedBufferQueueLock);
4771
4772 trimTimedBufferQueue_l();
4773
4774 // lazily initialize the shared memory heap for timed buffers
4775 if (mTimedMemoryDealer == NULL) {
4776 const int kTimedBufferHeapSize = 512 << 10;
4777
4778 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4779 "AudioFlingerTimed");
4780 if (mTimedMemoryDealer == NULL)
4781 return NO_MEMORY;
4782 }
4783
4784 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4785 if (newBuffer == NULL) {
4786 newBuffer = mTimedMemoryDealer->allocate(size);
4787 if (newBuffer == NULL)
4788 return NO_MEMORY;
4789 }
4790
4791 *buffer = newBuffer;
4792 return NO_ERROR;
4793}
4794
4795// caller must hold mTimedBufferQueueLock
4796void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4797 int64_t mediaTimeNow;
4798 {
4799 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4800 if (!mMediaTimeTransformValid)
4801 return;
4802
4803 int64_t targetTimeNow;
4804 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4805 ? mCCHelper.getCommonTime(&targetTimeNow)
4806 : mCCHelper.getLocalTime(&targetTimeNow);
4807
4808 if (OK != res)
4809 return;
4810
4811 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4812 &mediaTimeNow)) {
4813 return;
4814 }
4815 }
4816
John Grossman1c345192012-03-27 14:00:17 -07004817 size_t trimEnd;
4818 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004819 int64_t bufEnd;
4820
John Grossmanc95cfbb2012-04-12 11:53:11 -07004821 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4822 // We have a next buffer. Just use its PTS as the PTS of the frame
4823 // following the last frame in this buffer. If the stream is sparse
4824 // (ie, there are deliberate gaps left in the stream which should be
4825 // filled with silence by the TimedAudioTrack), then this can result
4826 // in one extra buffer being left un-trimmed when it could have
4827 // been. In general, this is not typical, and we would rather
4828 // optimized away the TS calculation below for the more common case
4829 // where PTSes are contiguous.
4830 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4831 } else {
4832 // We have no next buffer. Compute the PTS of the frame following
4833 // the last frame in this buffer by computing the duration of of
4834 // this frame in media time units and adding it to the PTS of the
4835 // buffer.
4836 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4837 / mCblk->frameSize;
4838
4839 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4840 &bufEnd)) {
4841 ALOGE("Failed to convert frame count of %lld to media time"
4842 " duration" " (scale factor %d/%u) in %s",
4843 frameCount,
4844 mMediaTimeToSampleTransform.a_to_b_numer,
4845 mMediaTimeToSampleTransform.a_to_b_denom,
4846 __PRETTY_FUNCTION__);
4847 break;
4848 }
4849 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004850 }
John Grossman9fbdee12012-03-26 17:51:46 -07004851
4852 if (bufEnd > mediaTimeNow)
4853 break;
4854
4855 // Is the buffer we want to use in the middle of a mix operation right
4856 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4857 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004858 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004859 mTrimQueueHeadOnRelease = true;
4860 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004861 }
4862
John Grossman9fbdee12012-03-26 17:51:46 -07004863 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004864 if (trimStart < trimEnd) {
4865 // Update the bookkeeping for framesReady()
4866 for (size_t i = trimStart; i < trimEnd; ++i) {
4867 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4868 }
4869
4870 // Now actually remove the buffers from the queue.
4871 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004872 }
4873}
4874
John Grossman1c345192012-03-27 14:00:17 -07004875void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4876 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004877 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4878 "%s called (reason \"%s\"), but timed buffer queue has no"
4879 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004880
4881 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4882 mTimedBufferQueue.removeAt(0);
4883}
4884
4885void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4886 const TimedBuffer& buf,
4887 const char* logTag) {
4888 uint32_t bufBytes = buf.buffer()->size();
4889 uint32_t consumedAlready = buf.position();
4890
Eric Laurentb388e532012-04-14 13:32:48 -07004891 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004892 "Bad bookkeeping while updating frames pending. Timed buffer is"
4893 " only %u bytes long, but claims to have consumed %u"
4894 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004895 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004896
4897 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004898 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4899 "Bad bookkeeping while updating frames pending. Should have at"
4900 " least %u queued frames, but we think we have only %u. (update"
4901 " reason: \"%s\")",
4902 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004903
4904 mFramesPendingInQueue -= bufFrames;
4905}
4906
John Grossman4ff14ba2012-02-08 16:37:41 -08004907status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4908 const sp<IMemory>& buffer, int64_t pts) {
4909
4910 {
4911 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4912 if (!mMediaTimeTransformValid)
4913 return INVALID_OPERATION;
4914 }
4915
4916 Mutex::Autolock _l(mTimedBufferQueueLock);
4917
John Grossman1c345192012-03-27 14:00:17 -07004918 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4919 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004920 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4921
4922 return NO_ERROR;
4923}
4924
4925status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4926 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4927
John Grossman1c345192012-03-27 14:00:17 -07004928 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4929 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4930 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004931
4932 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4933 target == TimedAudioTrack::COMMON_TIME)) {
4934 return BAD_VALUE;
4935 }
4936
4937 Mutex::Autolock lock(mMediaTimeTransformLock);
4938 mMediaTimeTransform = xform;
4939 mMediaTimeTransformTarget = target;
4940 mMediaTimeTransformValid = true;
4941
4942 return NO_ERROR;
4943}
4944
4945#define min(a, b) ((a) < (b) ? (a) : (b))
4946
4947// implementation of getNextBuffer for tracks whose buffers have timestamps
4948status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4949 AudioBufferProvider::Buffer* buffer, int64_t pts)
4950{
4951 if (pts == AudioBufferProvider::kInvalidPTS) {
4952 buffer->raw = 0;
4953 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004954 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004955 return INVALID_OPERATION;
4956 }
4957
John Grossman4ff14ba2012-02-08 16:37:41 -08004958 Mutex::Autolock _l(mTimedBufferQueueLock);
4959
John Grossman9fbdee12012-03-26 17:51:46 -07004960 ALOG_ASSERT(!mQueueHeadInFlight,
4961 "getNextBuffer called without releaseBuffer!");
4962
John Grossman4ff14ba2012-02-08 16:37:41 -08004963 while (true) {
4964
4965 // if we have no timed buffers, then fail
4966 if (mTimedBufferQueue.isEmpty()) {
4967 buffer->raw = 0;
4968 buffer->frameCount = 0;
4969 return NOT_ENOUGH_DATA;
4970 }
4971
4972 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4973
4974 // calculate the PTS of the head of the timed buffer queue expressed in
4975 // local time
4976 int64_t headLocalPTS;
4977 {
4978 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4979
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004980 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004981
4982 if (mMediaTimeTransform.a_to_b_denom == 0) {
4983 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004984 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004985 return NO_ERROR;
4986 }
4987
4988 int64_t transformedPTS;
4989 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4990 &transformedPTS)) {
4991 // the transform failed. this shouldn't happen, but if it does
4992 // then just drop this buffer
4993 ALOGW("timedGetNextBuffer transform failed");
4994 buffer->raw = 0;
4995 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004996 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004997 return NO_ERROR;
4998 }
4999
5000 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5001 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5002 &headLocalPTS)) {
5003 buffer->raw = 0;
5004 buffer->frameCount = 0;
5005 return INVALID_OPERATION;
5006 }
5007 } else {
5008 headLocalPTS = transformedPTS;
5009 }
5010 }
5011
5012 // adjust the head buffer's PTS to reflect the portion of the head buffer
5013 // that has already been consumed
5014 int64_t effectivePTS = headLocalPTS +
5015 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5016
5017 // Calculate the delta in samples between the head of the input buffer
5018 // queue and the start of the next output buffer that will be written.
5019 // If the transformation fails because of over or underflow, it means
5020 // that the sample's position in the output stream is so far out of
5021 // whack that it should just be dropped.
5022 int64_t sampleDelta;
5023 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5024 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005025 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5026 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005027 continue;
5028 }
5029 if (!mLocalTimeToSampleTransform.doForwardTransform(
5030 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005031 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005032 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005033 continue;
5034 }
5035
John Grossman1c345192012-03-27 14:00:17 -07005036 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5037 " sampleDelta=[%d.%08x]",
5038 head.pts(), head.position(), pts,
5039 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5040 + (sampleDelta >> 32)),
5041 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005042
5043 // if the delta between the ideal placement for the next input sample and
5044 // the current output position is within this threshold, then we will
5045 // concatenate the next input samples to the previous output
5046 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005047 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005048
5049 // if this is the first buffer of audio that we're emitting from this track
5050 // then it should be almost exactly on time.
5051 const int64_t kSampleStartupThreshold = 1LL << 32;
5052
5053 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005054 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005055 // the next input is close enough to being on time, so concatenate it
5056 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005057 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005058
John Grossman1c345192012-03-27 14:00:17 -07005059 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5060 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005061 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005062 }
5063
5064 // Looks like our output is not on time. Reset our on timed status.
5065 // Next time we mix samples from our input queue, then should be within
5066 // the StartupThreshold.
5067 mTimedAudioOutputOnTime = false;
5068 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005069 // the gap between the current output position and the proper start of
5070 // the next input sample is too big, so fill it with silence
5071 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5072
John Grossman9fbdee12012-03-26 17:51:46 -07005073 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005074 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5075 return NO_ERROR;
5076 } else {
5077 // the next input sample is late
5078 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5079 size_t onTimeSamplePosition =
5080 head.position() + lateFrames * mCblk->frameSize;
5081
5082 if (onTimeSamplePosition > head.buffer()->size()) {
5083 // all the remaining samples in the head are too late, so
5084 // drop it and move on
5085 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005086 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005087 continue;
5088 } else {
5089 // skip over the late samples
5090 head.setPosition(onTimeSamplePosition);
5091
5092 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005093 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005094
5095 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5096 return NO_ERROR;
5097 }
5098 }
5099 }
5100}
5101
5102// Yield samples from the timed buffer queue head up to the given output
5103// buffer's capacity.
5104//
5105// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005106void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005107 AudioBufferProvider::Buffer* buffer) {
5108
5109 const TimedBuffer& head = mTimedBufferQueue[0];
5110
5111 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5112 head.position());
5113
5114 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5115 mCblk->frameSize);
5116 size_t framesRequested = buffer->frameCount;
5117 buffer->frameCount = min(framesLeftInHead, framesRequested);
5118
John Grossman9fbdee12012-03-26 17:51:46 -07005119 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005120 mTimedAudioOutputOnTime = true;
5121}
5122
5123// Yield samples of silence up to the given output buffer's capacity
5124//
5125// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005126void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005127 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5128
5129 // lazily allocate a buffer filled with silence
5130 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5131 delete [] mTimedSilenceBuffer;
5132 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5133 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5134 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5135 }
5136
5137 buffer->raw = mTimedSilenceBuffer;
5138 size_t framesRequested = buffer->frameCount;
5139 buffer->frameCount = min(numFrames, framesRequested);
5140
5141 mTimedAudioOutputOnTime = false;
5142}
5143
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005144// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005145void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5146 AudioBufferProvider::Buffer* buffer) {
5147
5148 Mutex::Autolock _l(mTimedBufferQueueLock);
5149
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005150 // If the buffer which was just released is part of the buffer at the head
5151 // of the queue, be sure to update the amt of the buffer which has been
5152 // consumed. If the buffer being returned is not part of the head of the
5153 // queue, its either because the buffer is part of the silence buffer, or
5154 // because the head of the timed queue was trimmed after the mixer called
5155 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005156 if (buffer->raw == mTimedSilenceBuffer) {
5157 ALOG_ASSERT(!mQueueHeadInFlight,
5158 "Queue head in flight during release of silence buffer!");
5159 goto done;
5160 }
5161
5162 ALOG_ASSERT(mQueueHeadInFlight,
5163 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5164 " head in flight.");
5165
5166 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005167 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005168
5169 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005170 void* end = reinterpret_cast<void*>(
5171 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5172 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005173
John Grossman9fbdee12012-03-26 17:51:46 -07005174 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5175 "released buffer not within the head of the timed buffer"
5176 " queue; qHead = [%p, %p], released buffer = %p",
5177 start, end, buffer->raw);
5178
5179 head.setPosition(head.position() +
5180 (buffer->frameCount * mCblk->frameSize));
5181 mQueueHeadInFlight = false;
5182
John Grossman1c345192012-03-27 14:00:17 -07005183 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5184 "Bad bookkeeping during releaseBuffer! Should have at"
5185 " least %u queued frames, but we think we have only %u",
5186 buffer->frameCount, mFramesPendingInQueue);
5187
5188 mFramesPendingInQueue -= buffer->frameCount;
5189
John Grossman9fbdee12012-03-26 17:51:46 -07005190 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5191 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005192 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005193 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005194 }
John Grossman9fbdee12012-03-26 17:51:46 -07005195 } else {
5196 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5197 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005198 }
5199
John Grossman9fbdee12012-03-26 17:51:46 -07005200done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005201 buffer->raw = 0;
5202 buffer->frameCount = 0;
5203}
5204
Glenn Kasten288ed212012-04-25 17:52:27 -07005205size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005206 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005207 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005208}
5209
5210AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5211 : mPTS(0), mPosition(0) {}
5212
5213AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5214 const sp<IMemory>& buffer, int64_t pts)
5215 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5216
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217// ----------------------------------------------------------------------------
5218
5219// RecordTrack constructor must be called with AudioFlinger::mLock held
5220AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005221 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005222 const sp<Client>& client,
5223 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005224 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005225 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005226 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005227 int sessionId)
5228 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005229 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005230 mOverflow(false)
5231{
5232 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005233 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5234 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5235 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5236 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5237 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5238 } else {
5239 mCblk->frameSize = sizeof(int8_t);
5240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005241 }
5242}
5243
5244AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5245{
5246 sp<ThreadBase> thread = mThread.promote();
5247 if (thread != 0) {
5248 AudioSystem::releaseInput(thread->id());
5249 }
5250}
5251
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005252// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005253status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005254{
5255 audio_track_cblk_t* cblk = this->cblk();
5256 uint32_t framesAvail;
5257 uint32_t framesReq = buffer->frameCount;
5258
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005259 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005260 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005262 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005263 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264 }
5265
5266 framesAvail = cblk->framesAvailable_l();
5267
Glenn Kastenf6b16782011-12-15 09:51:17 -08005268 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005269 uint32_t s = cblk->server;
5270 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5271
5272 if (framesReq > framesAvail) {
5273 framesReq = framesAvail;
5274 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005275 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276 framesReq = bufferEnd - s;
5277 }
5278
5279 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005280 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005281
5282 buffer->frameCount = framesReq;
5283 return NO_ERROR;
5284 }
5285
5286getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005287 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288 buffer->frameCount = 0;
5289 return NOT_ENOUGH_DATA;
5290}
5291
Glenn Kasten3acbd052012-02-28 10:39:56 -08005292status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005293 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294{
5295 sp<ThreadBase> thread = mThread.promote();
5296 if (thread != 0) {
5297 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005298 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299 } else {
5300 return BAD_VALUE;
5301 }
5302}
5303
5304void AudioFlinger::RecordThread::RecordTrack::stop()
5305{
5306 sp<ThreadBase> thread = mThread.promote();
5307 if (thread != 0) {
5308 RecordThread *recordThread = (RecordThread *)thread.get();
5309 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005310 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005311 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005312 // read from buffer
5313 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005314 }
5315}
5316
5317void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5318{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005319 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005320 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005322 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323 mSessionId,
5324 mFrameCount,
5325 mState,
5326 mCblk->sampleRate,
5327 mCblk->server,
5328 mCblk->user);
5329}
5330
5331
5332// ----------------------------------------------------------------------------
5333
5334AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005335 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336 DuplicatingThread *sourceThread,
5337 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005338 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005339 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005341 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5342 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343 mActive(false), mSourceThread(sourceThread)
5344{
5345
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 if (mCblk != NULL) {
5347 mCblk->flags |= CBLK_DIRECTION_OUT;
5348 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005349 mOutBuffer.frameCount = 0;
5350 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005351 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005352 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5353 mCblk, mBuffer, mCblk->buffers,
5354 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005356 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 }
5358}
5359
5360AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5361{
5362 clearBufferQueue();
5363}
5364
Glenn Kasten3acbd052012-02-28 10:39:56 -08005365status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005366 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005368 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 if (status != NO_ERROR) {
5370 return status;
5371 }
5372
5373 mActive = true;
5374 mRetryCount = 127;
5375 return status;
5376}
5377
5378void AudioFlinger::PlaybackThread::OutputTrack::stop()
5379{
5380 Track::stop();
5381 clearBufferQueue();
5382 mOutBuffer.frameCount = 0;
5383 mActive = false;
5384}
5385
5386bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5387{
5388 Buffer *pInBuffer;
5389 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005390 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 bool outputBufferFull = false;
5392 inBuffer.frameCount = frames;
5393 inBuffer.i16 = data;
5394
5395 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5396
5397 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005398 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 sp<ThreadBase> thread = mThread.promote();
5400 if (thread != 0) {
5401 MixerThread *mixerThread = (MixerThread *)thread.get();
5402 if (mCblk->frameCount > frames){
5403 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5404 uint32_t startFrames = (mCblk->frameCount - frames);
5405 pInBuffer = new Buffer;
5406 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5407 pInBuffer->frameCount = startFrames;
5408 pInBuffer->i16 = pInBuffer->mBuffer;
5409 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5410 mBufferQueue.add(pInBuffer);
5411 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005412 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 }
5414 }
5415 }
5416 }
5417
5418 while (waitTimeLeftMs) {
5419 // First write pending buffers, then new data
5420 if (mBufferQueue.size()) {
5421 pInBuffer = mBufferQueue.itemAt(0);
5422 } else {
5423 pInBuffer = &inBuffer;
5424 }
5425
5426 if (pInBuffer->frameCount == 0) {
5427 break;
5428 }
5429
5430 if (mOutBuffer.frameCount == 0) {
5431 mOutBuffer.frameCount = pInBuffer->frameCount;
5432 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005433 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005434 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 outputBufferFull = true;
5436 break;
5437 }
5438 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5439 if (waitTimeLeftMs >= waitTimeMs) {
5440 waitTimeLeftMs -= waitTimeMs;
5441 } else {
5442 waitTimeLeftMs = 0;
5443 }
5444 }
5445
5446 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5447 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5448 mCblk->stepUser(outFrames);
5449 pInBuffer->frameCount -= outFrames;
5450 pInBuffer->i16 += outFrames * channelCount;
5451 mOutBuffer.frameCount -= outFrames;
5452 mOutBuffer.i16 += outFrames * channelCount;
5453
5454 if (pInBuffer->frameCount == 0) {
5455 if (mBufferQueue.size()) {
5456 mBufferQueue.removeAt(0);
5457 delete [] pInBuffer->mBuffer;
5458 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005459 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460 } else {
5461 break;
5462 }
5463 }
5464 }
5465
5466 // If we could not write all frames, allocate a buffer and queue it for next time.
5467 if (inBuffer.frameCount) {
5468 sp<ThreadBase> thread = mThread.promote();
5469 if (thread != 0 && !thread->standby()) {
5470 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5471 pInBuffer = new Buffer;
5472 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5473 pInBuffer->frameCount = inBuffer.frameCount;
5474 pInBuffer->i16 = pInBuffer->mBuffer;
5475 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5476 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005477 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005479 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 }
5481 }
5482 }
5483
5484 // Calling write() with a 0 length buffer, means that no more data will be written:
5485 // If no more buffers are pending, fill output track buffer to make sure it is started
5486 // by output mixer.
5487 if (frames == 0 && mBufferQueue.size() == 0) {
5488 if (mCblk->user < mCblk->frameCount) {
5489 frames = mCblk->frameCount - mCblk->user;
5490 pInBuffer = new Buffer;
5491 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5492 pInBuffer->frameCount = frames;
5493 pInBuffer->i16 = pInBuffer->mBuffer;
5494 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5495 mBufferQueue.add(pInBuffer);
5496 } else if (mActive) {
5497 stop();
5498 }
5499 }
5500
5501 return outputBufferFull;
5502}
5503
5504status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5505{
5506 int active;
5507 status_t result;
5508 audio_track_cblk_t* cblk = mCblk;
5509 uint32_t framesReq = buffer->frameCount;
5510
Steve Block3856b092011-10-20 11:56:00 +01005511// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512 buffer->frameCount = 0;
5513
5514 uint32_t framesAvail = cblk->framesAvailable();
5515
5516
5517 if (framesAvail == 0) {
5518 Mutex::Autolock _l(cblk->lock);
5519 goto start_loop_here;
5520 while (framesAvail == 0) {
5521 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005522 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005523 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005524 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 }
5526 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5527 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005528 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 }
5530 // read the server count again
5531 start_loop_here:
5532 framesAvail = cblk->framesAvailable_l();
5533 }
5534 }
5535
5536// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005537// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538// }
5539
5540 if (framesReq > framesAvail) {
5541 framesReq = framesAvail;
5542 }
5543
5544 uint32_t u = cblk->user;
5545 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5546
Marco Nelissena1472d92012-03-30 14:36:54 -07005547 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 framesReq = bufferEnd - u;
5549 }
5550
5551 buffer->frameCount = framesReq;
5552 buffer->raw = (void *)cblk->buffer(u);
5553 return NO_ERROR;
5554}
5555
5556
5557void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5558{
5559 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005560
5561 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005562 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 delete [] pBuffer->mBuffer;
5564 delete pBuffer;
5565 }
5566 mBufferQueue.clear();
5567}
5568
5569// ----------------------------------------------------------------------------
5570
5571AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5572 : RefBase(),
5573 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005574 // 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 -07005575 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005576 mPid(pid),
5577 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005578{
5579 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5580}
5581
5582// Client destructor must be called with AudioFlinger::mLock held
5583AudioFlinger::Client::~Client()
5584{
5585 mAudioFlinger->removeClient_l(mPid);
5586}
5587
Glenn Kasten435dbe62012-01-30 10:15:48 -08005588sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005589{
5590 return mMemoryDealer;
5591}
5592
John Grossman4ff14ba2012-02-08 16:37:41 -08005593// Reserve one of the limited slots for a timed audio track associated
5594// with this client
5595bool AudioFlinger::Client::reserveTimedTrack()
5596{
5597 const int kMaxTimedTracksPerClient = 4;
5598
5599 Mutex::Autolock _l(mTimedTrackLock);
5600
5601 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5602 ALOGW("can not create timed track - pid %d has exceeded the limit",
5603 mPid);
5604 return false;
5605 }
5606
5607 mTimedTrackCount++;
5608 return true;
5609}
5610
5611// Release a slot for a timed audio track
5612void AudioFlinger::Client::releaseTimedTrack()
5613{
5614 Mutex::Autolock _l(mTimedTrackLock);
5615 mTimedTrackCount--;
5616}
5617
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618// ----------------------------------------------------------------------------
5619
5620AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5621 const sp<IAudioFlingerClient>& client,
5622 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005623 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005624{
5625}
5626
5627AudioFlinger::NotificationClient::~NotificationClient()
5628{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629}
5630
5631void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5632{
5633 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005634 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635}
5636
5637// ----------------------------------------------------------------------------
5638
5639AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5640 : BnAudioTrack(),
5641 mTrack(track)
5642{
5643}
5644
5645AudioFlinger::TrackHandle::~TrackHandle() {
5646 // just stop the track on deletion, associated resources
5647 // will be freed from the main thread once all pending buffers have
5648 // been played. Unless it's not in the active track list, in which
5649 // case we free everything now...
5650 mTrack->destroy();
5651}
5652
Glenn Kasten90716c52012-01-26 13:40:12 -08005653sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5654 return mTrack->getCblk();
5655}
5656
Glenn Kasten3acbd052012-02-28 10:39:56 -08005657status_t AudioFlinger::TrackHandle::start() {
5658 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659}
5660
5661void AudioFlinger::TrackHandle::stop() {
5662 mTrack->stop();
5663}
5664
5665void AudioFlinger::TrackHandle::flush() {
5666 mTrack->flush();
5667}
5668
5669void AudioFlinger::TrackHandle::mute(bool e) {
5670 mTrack->mute(e);
5671}
5672
5673void AudioFlinger::TrackHandle::pause() {
5674 mTrack->pause();
5675}
5676
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5678{
5679 return mTrack->attachAuxEffect(EffectId);
5680}
5681
John Grossman4ff14ba2012-02-08 16:37:41 -08005682status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5683 sp<IMemory>* buffer) {
5684 if (!mTrack->isTimedTrack())
5685 return INVALID_OPERATION;
5686
5687 PlaybackThread::TimedTrack* tt =
5688 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5689 return tt->allocateTimedBuffer(size, buffer);
5690}
5691
5692status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5693 int64_t pts) {
5694 if (!mTrack->isTimedTrack())
5695 return INVALID_OPERATION;
5696
5697 PlaybackThread::TimedTrack* tt =
5698 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5699 return tt->queueTimedBuffer(buffer, pts);
5700}
5701
5702status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5703 const LinearTransform& xform, int target) {
5704
5705 if (!mTrack->isTimedTrack())
5706 return INVALID_OPERATION;
5707
5708 PlaybackThread::TimedTrack* tt =
5709 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5710 return tt->setMediaTimeTransform(
5711 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5712}
5713
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714status_t AudioFlinger::TrackHandle::onTransact(
5715 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5716{
5717 return BnAudioTrack::onTransact(code, data, reply, flags);
5718}
5719
5720// ----------------------------------------------------------------------------
5721
5722sp<IAudioRecord> AudioFlinger::openRecord(
5723 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005724 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005726 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005727 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005729 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 int *sessionId,
5731 status_t *status)
5732{
5733 sp<RecordThread::RecordTrack> recordTrack;
5734 sp<RecordHandle> recordHandle;
5735 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736 status_t lStatus;
5737 RecordThread *thread;
5738 size_t inFrameCount;
5739 int lSessionId;
5740
5741 // check calling permissions
5742 if (!recordingAllowed()) {
5743 lStatus = PERMISSION_DENIED;
5744 goto Exit;
5745 }
5746
5747 // add client to list
5748 { // scope for mLock
5749 Mutex::Autolock _l(mLock);
5750 thread = checkRecordThread_l(input);
5751 if (thread == NULL) {
5752 lStatus = BAD_VALUE;
5753 goto Exit;
5754 }
5755
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005756 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005757
5758 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005759 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 lSessionId = *sessionId;
5761 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005762 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763 if (sessionId != NULL) {
5764 *sessionId = lSessionId;
5765 }
5766 }
5767 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005768 recordTrack = thread->createRecordTrack_l(client,
5769 sampleRate,
5770 format,
5771 channelMask,
5772 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005773 lSessionId,
5774 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005776 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5778 // destructor is called by the TrackBase destructor with mLock held
5779 client.clear();
5780 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781 goto Exit;
5782 }
5783
5784 // return to handle to client
5785 recordHandle = new RecordHandle(recordTrack);
5786 lStatus = NO_ERROR;
5787
5788Exit:
5789 if (status) {
5790 *status = lStatus;
5791 }
5792 return recordHandle;
5793}
5794
5795// ----------------------------------------------------------------------------
5796
5797AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5798 : BnAudioRecord(),
5799 mRecordTrack(recordTrack)
5800{
5801}
5802
5803AudioFlinger::RecordHandle::~RecordHandle() {
5804 stop();
5805}
5806
Glenn Kasten90716c52012-01-26 13:40:12 -08005807sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5808 return mRecordTrack->getCblk();
5809}
5810
Glenn Kasten3acbd052012-02-28 10:39:56 -08005811status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005812 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005813 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814}
5815
5816void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005817 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818 mRecordTrack->stop();
5819}
5820
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821status_t AudioFlinger::RecordHandle::onTransact(
5822 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5823{
5824 return BnAudioRecord::onTransact(code, data, reply, flags);
5825}
5826
5827// ----------------------------------------------------------------------------
5828
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005829AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5830 AudioStreamIn *input,
5831 uint32_t sampleRate,
5832 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005833 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005834 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005835 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005836 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5837 // mRsmpInIndex and mInputBytes set by readInputParameters()
5838 mReqChannelCount(popcount(channels)),
5839 mReqSampleRate(sampleRate)
5840 // mBytesRead is only meaningful while active, and so is cleared in start()
5841 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842{
Glenn Kasten480b4682012-02-28 12:30:08 -08005843 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005844
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845 readInputParameters();
5846}
5847
5848
5849AudioFlinger::RecordThread::~RecordThread()
5850{
5851 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005852 delete mResampler;
5853 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854}
5855
5856void AudioFlinger::RecordThread::onFirstRef()
5857{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005858 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859}
5860
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005861status_t AudioFlinger::RecordThread::readyToRun()
5862{
5863 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005864 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005865 return status;
5866}
5867
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868bool AudioFlinger::RecordThread::threadLoop()
5869{
5870 AudioBufferProvider::Buffer buffer;
5871 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005872 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873
Eric Laurent44d98482010-09-30 16:12:31 -07005874 nsecs_t lastWarning = 0;
5875
Eric Laurentfeb0db62011-07-22 09:04:31 -07005876 acquireWakeLock();
5877
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 // start recording
5879 while (!exitPending()) {
5880
5881 processConfigEvents();
5882
5883 { // scope for mLock
5884 Mutex::Autolock _l(mLock);
5885 checkForNewParameters_l();
5886 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5887 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005888 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 mStandby = true;
5890 }
5891
5892 if (exitPending()) break;
5893
Eric Laurentfeb0db62011-07-22 09:04:31 -07005894 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005895 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005896 // go to sleep
5897 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005898 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005899 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900 continue;
5901 }
5902 if (mActiveTrack != 0) {
5903 if (mActiveTrack->mState == TrackBase::PAUSING) {
5904 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005905 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 mStandby = true;
5907 }
5908 mActiveTrack.clear();
5909 mStartStopCond.broadcast();
5910 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5911 if (mReqChannelCount != mActiveTrack->channelCount()) {
5912 mActiveTrack.clear();
5913 mStartStopCond.broadcast();
5914 } else if (mBytesRead != 0) {
5915 // record start succeeds only if first read from audio input
5916 // succeeds
5917 if (mBytesRead > 0) {
5918 mActiveTrack->mState = TrackBase::ACTIVE;
5919 } else {
5920 mActiveTrack.clear();
5921 }
5922 mStartStopCond.broadcast();
5923 }
5924 mStandby = false;
5925 }
5926 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005927 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 }
5929
5930 if (mActiveTrack != 0) {
5931 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5932 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005933 unlockEffectChains(effectChains);
5934 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935 continue;
5936 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005937 for (size_t i = 0; i < effectChains.size(); i ++) {
5938 effectChains[i]->process_l();
5939 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005940
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005942 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005944 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 // no resampling
5946 while (framesOut) {
5947 size_t framesIn = mFrameCount - mRsmpInIndex;
5948 if (framesIn) {
5949 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5950 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5951 if (framesIn > framesOut)
5952 framesIn = framesOut;
5953 mRsmpInIndex += framesIn;
5954 framesOut -= framesIn;
5955 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005956 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957 memcpy(dst, src, framesIn * mFrameSize);
5958 } else {
5959 int16_t *src16 = (int16_t *)src;
5960 int16_t *dst16 = (int16_t *)dst;
5961 if (mChannelCount == 1) {
5962 while (framesIn--) {
5963 *dst16++ = *src16;
5964 *dst16++ = *src16++;
5965 }
5966 } else {
5967 while (framesIn--) {
5968 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5969 src16 += 2;
5970 }
5971 }
5972 }
5973 }
5974 if (framesOut && mFrameCount == mRsmpInIndex) {
5975 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005976 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005977 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 framesOut = 0;
5979 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005980 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 mRsmpInIndex = 0;
5982 }
5983 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005984 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5986 // Force input into standby so that it tries to
5987 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005988 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005989 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 }
5991 mRsmpInIndex = mFrameCount;
5992 framesOut = 0;
5993 buffer.frameCount = 0;
5994 }
5995 }
5996 }
5997 } else {
5998 // resampling
5999
6000 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6001 // alter output frame count as if we were expecting stereo samples
6002 if (mChannelCount == 1 && mReqChannelCount == 1) {
6003 framesOut >>= 1;
6004 }
6005 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6006 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6007 // are 32 bit aligned which should be always true.
6008 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006009 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 // the resampler always outputs stereo samples: do post stereo to mono conversion
6011 int16_t *src = (int16_t *)mRsmpOutBuffer;
6012 int16_t *dst = buffer.i16;
6013 while (framesOut--) {
6014 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6015 src += 2;
6016 }
6017 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006018 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019 }
6020
6021 }
Eric Laurenta011e352012-03-29 15:51:43 -07006022 if (mFramestoDrop == 0) {
6023 mActiveTrack->releaseBuffer(&buffer);
6024 } else {
6025 if (mFramestoDrop > 0) {
6026 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006027 if (mFramestoDrop <= 0) {
6028 clearSyncStartEvent();
6029 }
6030 } else {
6031 mFramestoDrop += buffer.frameCount;
6032 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6033 mSyncStartEvent->isCancelled()) {
6034 ALOGW("Synced record %s, session %d, trigger session %d",
6035 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6036 mActiveTrack->sessionId(),
6037 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6038 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006039 }
6040 }
6041 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 mActiveTrack->overflow();
6043 }
6044 // client isn't retrieving buffers fast enough
6045 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006046 if (!mActiveTrack->setOverflow()) {
6047 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006048 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006049 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006050 lastWarning = now;
6051 }
6052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 // Release the processor for a while before asking for a new buffer.
6054 // This will give the application more chance to read from the buffer and
6055 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006056 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 }
6058 }
Eric Laurentec437d82011-07-26 20:54:46 -07006059 // enable changes in effect chain
6060 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006061 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006062 }
6063
6064 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006065 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066 }
6067 mActiveTrack.clear();
6068
6069 mStartStopCond.broadcast();
6070
Eric Laurentfeb0db62011-07-22 09:04:31 -07006071 releaseWakeLock();
6072
Steve Block3856b092011-10-20 11:56:00 +01006073 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 return false;
6075}
6076
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006077
6078sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6079 const sp<AudioFlinger::Client>& client,
6080 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006081 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006082 int channelMask,
6083 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006084 int sessionId,
6085 status_t *status)
6086{
6087 sp<RecordTrack> track;
6088 status_t lStatus;
6089
6090 lStatus = initCheck();
6091 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006092 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006093 goto Exit;
6094 }
6095
6096 { // scope for mLock
6097 Mutex::Autolock _l(mLock);
6098
6099 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006100 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006101
Glenn Kasten7378ca52012-01-20 13:44:40 -08006102 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006103 lStatus = NO_MEMORY;
6104 goto Exit;
6105 }
6106
6107 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006108 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6109 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006110 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006111 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6112 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006113 }
6114 lStatus = NO_ERROR;
6115
6116Exit:
6117 if (status) {
6118 *status = lStatus;
6119 }
6120 return track;
6121}
6122
Eric Laurenta011e352012-03-29 15:51:43 -07006123status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006124 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006125 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126{
Glenn Kasten58912562012-04-03 10:45:00 -07006127 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006128 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006130
6131 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006132 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006133 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6134 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6135 triggerSession,
6136 recordTrack->sessionId(),
6137 syncStartEventCallback,
6138 this);
Eric Laurent29864602012-05-08 18:57:51 -07006139 // Sync event can be cancelled by the trigger session if the track is not in a
6140 // compatible state in which case we start record immediately
6141 if (mSyncStartEvent->isCancelled()) {
6142 clearSyncStartEvent();
6143 } else {
6144 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6145 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6146 }
Eric Laurenta011e352012-03-29 15:51:43 -07006147 }
6148
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006150 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151 if (mActiveTrack != 0) {
6152 if (recordTrack != mActiveTrack.get()) {
6153 status = -EBUSY;
6154 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6155 mActiveTrack->mState = TrackBase::ACTIVE;
6156 }
6157 return status;
6158 }
6159
6160 recordTrack->mState = TrackBase::IDLE;
6161 mActiveTrack = recordTrack;
6162 mLock.unlock();
6163 status_t status = AudioSystem::startInput(mId);
6164 mLock.lock();
6165 if (status != NO_ERROR) {
6166 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006167 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 return status;
6169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 mRsmpInIndex = mFrameCount;
6171 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006172 if (mResampler != NULL) {
6173 mResampler->reset();
6174 }
6175 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006177 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 mWaitWorkCV.signal();
6179 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006180 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181 mActiveTrack.clear();
6182 status = INVALID_OPERATION;
6183 goto startError;
6184 }
6185 mStartStopCond.wait(mLock);
6186 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006187 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 status = BAD_VALUE;
6189 goto startError;
6190 }
Steve Block3856b092011-10-20 11:56:00 +01006191 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 return status;
6193 }
6194startError:
6195 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006196 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197 return status;
6198}
6199
Eric Laurenta011e352012-03-29 15:51:43 -07006200void AudioFlinger::RecordThread::clearSyncStartEvent()
6201{
6202 if (mSyncStartEvent != 0) {
6203 mSyncStartEvent->cancel();
6204 }
6205 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006206 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006207}
6208
6209void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6210{
6211 sp<SyncEvent> strongEvent = event.promote();
6212
6213 if (strongEvent != 0) {
6214 RecordThread *me = (RecordThread *)strongEvent->cookie();
6215 me->handleSyncStartEvent(strongEvent);
6216 }
6217}
6218
6219void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6220{
Eric Laurent29864602012-05-08 18:57:51 -07006221 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006222 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6223 // from audio HAL
6224 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006225 }
6226}
6227
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006229 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006230 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006232 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6234 mActiveTrack->mState = TrackBase::PAUSING;
6235 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006236 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237 return;
6238 }
6239 mStartStopCond.wait(mLock);
6240 // if we have been restarted, recordTrack == mActiveTrack.get() here
6241 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6242 mLock.unlock();
6243 AudioSystem::stopInput(mId);
6244 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006245 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 }
6247 }
6248 }
6249}
6250
Eric Laurenta011e352012-03-29 15:51:43 -07006251bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6252{
6253 return false;
6254}
6255
6256status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6257{
6258 if (!isValidSyncEvent(event)) {
6259 return BAD_VALUE;
6260 }
6261
6262 Mutex::Autolock _l(mLock);
6263
6264 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6265 mTrack->setSyncEvent(event);
6266 return NO_ERROR;
6267 }
6268 return NAME_NOT_FOUND;
6269}
6270
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6272{
6273 const size_t SIZE = 256;
6274 char buffer[SIZE];
6275 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276
6277 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6278 result.append(buffer);
6279
6280 if (mActiveTrack != 0) {
6281 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006282 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 mActiveTrack->dump(buffer, SIZE);
6284 result.append(buffer);
6285
6286 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6287 result.append(buffer);
6288 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6289 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006290 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 result.append(buffer);
6292 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6293 result.append(buffer);
6294 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6295 result.append(buffer);
6296
6297
6298 } else {
6299 result.append("No record client\n");
6300 }
6301 write(fd, result.string(), result.size());
6302
6303 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006304 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305
6306 return NO_ERROR;
6307}
6308
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006309// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006310status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311{
6312 size_t framesReq = buffer->frameCount;
6313 size_t framesReady = mFrameCount - mRsmpInIndex;
6314 int channelCount;
6315
6316 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006317 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006319 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006320 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6321 // Force input into standby so that it tries to
6322 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006323 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006324 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006325 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006326 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 buffer->frameCount = 0;
6328 return NOT_ENOUGH_DATA;
6329 }
6330 mRsmpInIndex = 0;
6331 framesReady = mFrameCount;
6332 }
6333
6334 if (framesReq > framesReady) {
6335 framesReq = framesReady;
6336 }
6337
6338 if (mChannelCount == 1 && mReqChannelCount == 2) {
6339 channelCount = 1;
6340 } else {
6341 channelCount = 2;
6342 }
6343 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6344 buffer->frameCount = framesReq;
6345 return NO_ERROR;
6346}
6347
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006348// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6350{
6351 mRsmpInIndex += buffer->frameCount;
6352 buffer->frameCount = 0;
6353}
6354
6355bool AudioFlinger::RecordThread::checkForNewParameters_l()
6356{
6357 bool reconfig = false;
6358
6359 while (!mNewParameters.isEmpty()) {
6360 status_t status = NO_ERROR;
6361 String8 keyValuePair = mNewParameters[0];
6362 AudioParameter param = AudioParameter(keyValuePair);
6363 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006364 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006365 int reqSamplingRate = mReqSampleRate;
6366 int reqChannelCount = mReqChannelCount;
6367
6368 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6369 reqSamplingRate = value;
6370 reconfig = true;
6371 }
6372 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006373 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 reconfig = true;
6375 }
6376 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006377 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 reconfig = true;
6379 }
6380 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6381 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006382 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 // if frame count is changed after track creation
6384 if (mActiveTrack != 0) {
6385 status = INVALID_OPERATION;
6386 } else {
6387 reconfig = true;
6388 }
6389 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006390 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6391 // forward device change to effects that have requested to be
6392 // aware of attached audio device.
6393 for (size_t i = 0; i < mEffectChains.size(); i++) {
6394 mEffectChains[i]->setDevice_l(value);
6395 }
6396 // store input device and output device but do not forward output device to audio HAL.
6397 // Note that status is ignored by the caller for output device
6398 // (see AudioFlinger::setParameters()
6399 if (value & AUDIO_DEVICE_OUT_ALL) {
6400 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6401 status = BAD_VALUE;
6402 } else {
6403 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006404 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6405 if (mTrack != NULL) {
6406 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006407 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006408 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6409 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6410 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006411 }
6412 mDevice |= (uint32_t)value;
6413 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006415 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006416 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006417 mInput->stream->common.standby(&mInput->stream->common);
6418 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6419 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420 }
6421 if (reconfig) {
6422 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006423 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006424 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006425 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006426 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6427 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006428 status = NO_ERROR;
6429 }
6430 if (status == NO_ERROR) {
6431 readInputParameters();
6432 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6433 }
6434 }
6435 }
6436
6437 mNewParameters.removeAt(0);
6438
6439 mParamStatus = status;
6440 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006441 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6442 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006443 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 }
6445 return reconfig;
6446}
6447
6448String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6449{
Dima Zavinfce7a472011-04-19 22:30:36 -07006450 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006451 String8 out_s8 = String8();
6452
6453 Mutex::Autolock _l(mLock);
6454 if (initCheck() != NO_ERROR) {
6455 return out_s8;
6456 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006457
Dima Zavin799a70e2011-04-18 16:57:27 -07006458 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006459 out_s8 = String8(s);
6460 free(s);
6461 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462}
6463
6464void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6465 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006466 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467
6468 switch (event) {
6469 case AudioSystem::INPUT_OPENED:
6470 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006471 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 desc.samplingRate = mSampleRate;
6473 desc.format = mFormat;
6474 desc.frameCount = mFrameCount;
6475 desc.latency = 0;
6476 param2 = &desc;
6477 break;
6478
6479 case AudioSystem::INPUT_CLOSED:
6480 default:
6481 break;
6482 }
6483 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6484}
6485
6486void AudioFlinger::RecordThread::readInputParameters()
6487{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006488 delete mRsmpInBuffer;
6489 // mRsmpInBuffer is always assigned a new[] below
6490 delete mRsmpOutBuffer;
6491 mRsmpOutBuffer = NULL;
6492 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006493 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494
Dima Zavin799a70e2011-04-18 16:57:27 -07006495 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006496 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6497 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006498 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006499 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006500 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006502 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6504
Glenn Kasten53d76db2012-03-08 12:32:47 -08006505 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506 {
6507 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006508 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6509 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 if (mChannelCount == 1 && mReqChannelCount == 2) {
6511 channelCount = 1;
6512 } else {
6513 channelCount = 2;
6514 }
6515 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6516 mResampler->setSampleRate(mSampleRate);
6517 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6518 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6519
6520 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6521 if (mChannelCount == 1 && mReqChannelCount == 1) {
6522 mFrameCount >>= 1;
6523 }
6524
6525 }
6526 mRsmpInIndex = mFrameCount;
6527}
6528
6529unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6530{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006531 Mutex::Autolock _l(mLock);
6532 if (initCheck() != NO_ERROR) {
6533 return 0;
6534 }
6535
Dima Zavin799a70e2011-04-18 16:57:27 -07006536 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537}
6538
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006539uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6540{
6541 Mutex::Autolock _l(mLock);
6542 uint32_t result = 0;
6543 if (getEffectChain_l(sessionId) != 0) {
6544 result = EFFECT_SESSION;
6545 }
6546
6547 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6548 result |= TRACK_SESSION;
6549 }
6550
6551 return result;
6552}
6553
Eric Laurent59bd0da2011-08-01 09:52:20 -07006554AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6555{
6556 Mutex::Autolock _l(mLock);
6557 return mTrack;
6558}
6559
Glenn Kastenaed850d2012-01-26 09:46:34 -08006560AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006561{
6562 Mutex::Autolock _l(mLock);
6563 return mInput;
6564}
6565
6566AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6567{
6568 Mutex::Autolock _l(mLock);
6569 AudioStreamIn *input = mInput;
6570 mInput = NULL;
6571 return input;
6572}
6573
6574// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006575audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006576{
6577 if (mInput == NULL) {
6578 return NULL;
6579 }
6580 return &mInput->stream->common;
6581}
6582
6583
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584// ----------------------------------------------------------------------------
6585
Eric Laurenta4c5a552012-03-29 10:12:40 -07006586audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6587{
6588 if (!settingsAllowed()) {
6589 return 0;
6590 }
6591 Mutex::Autolock _l(mLock);
6592 return loadHwModule_l(name);
6593}
6594
6595// loadHwModule_l() must be called with AudioFlinger::mLock held
6596audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6597{
6598 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6599 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6600 ALOGW("loadHwModule() module %s already loaded", name);
6601 return mAudioHwDevs.keyAt(i);
6602 }
6603 }
6604
Eric Laurenta4c5a552012-03-29 10:12:40 -07006605 audio_hw_device_t *dev;
6606
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006607 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006608 if (rc) {
6609 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6610 return 0;
6611 }
6612
6613 mHardwareStatus = AUDIO_HW_INIT;
6614 rc = dev->init_check(dev);
6615 mHardwareStatus = AUDIO_HW_IDLE;
6616 if (rc) {
6617 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6618 return 0;
6619 }
6620
6621 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6622 (NULL != dev->set_master_volume)) {
6623 AutoMutex lock(mHardwareLock);
6624 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6625 dev->set_master_volume(dev, mMasterVolume);
6626 mHardwareStatus = AUDIO_HW_IDLE;
6627 }
6628
6629 audio_module_handle_t handle = nextUniqueId();
6630 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6631
6632 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006633 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006634
6635 return handle;
6636
6637}
6638
6639audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6640 audio_devices_t *pDevices,
6641 uint32_t *pSamplingRate,
6642 audio_format_t *pFormat,
6643 audio_channel_mask_t *pChannelMask,
6644 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006645 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646{
6647 status_t status;
6648 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006649 struct audio_config config = {
6650 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6651 channel_mask: pChannelMask ? *pChannelMask : 0,
6652 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6653 };
6654 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006655 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006656
Eric Laurenta4c5a552012-03-29 10:12:40 -07006657 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6658 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006659 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006660 config.sample_rate,
6661 config.format,
6662 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006663 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664
6665 if (pDevices == NULL || *pDevices == 0) {
6666 return 0;
6667 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006668
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 Mutex::Autolock _l(mLock);
6670
Eric Laurenta4c5a552012-03-29 10:12:40 -07006671 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006672 if (outHwDev == NULL)
6673 return 0;
6674
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006675 audio_io_handle_t id = nextUniqueId();
6676
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006677 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006678
6679 status = outHwDev->open_output_stream(outHwDev,
6680 id,
6681 *pDevices,
6682 (audio_output_flags_t)flags,
6683 &config,
6684 &outStream);
6685
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006686 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006687 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006688 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006689 config.sample_rate,
6690 config.format,
6691 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006692 status);
6693
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006694 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006695 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006696
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006697 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006698 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6699 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006700 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006701 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702 } else {
6703 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006704 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006705 }
6706 mPlaybackThreads.add(id, thread);
6707
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006708 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6709 if (pFormat != NULL) *pFormat = config.format;
6710 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006711 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712
6713 // notify client processes of the new output creation
6714 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006715
6716 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006717 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006718 ALOGI("Using module %d has the primary audio interface", module);
6719 mPrimaryHardwareDev = outHwDev;
6720
6721 AutoMutex lock(mHardwareLock);
6722 mHardwareStatus = AUDIO_HW_SET_MODE;
6723 outHwDev->set_mode(outHwDev, mMode);
6724
6725 // Determine the level of master volume support the primary audio HAL has,
6726 // and set the initial master volume at the same time.
6727 float initialVolume = 1.0;
6728 mMasterVolumeSupportLvl = MVS_NONE;
6729
6730 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6731 if ((NULL != outHwDev->get_master_volume) &&
6732 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6733 mMasterVolumeSupportLvl = MVS_FULL;
6734 } else {
6735 mMasterVolumeSupportLvl = MVS_SETONLY;
6736 initialVolume = 1.0;
6737 }
6738
6739 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6740 if ((NULL == outHwDev->set_master_volume) ||
6741 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6742 mMasterVolumeSupportLvl = MVS_NONE;
6743 }
6744 // now that we have a primary device, initialize master volume on other devices
6745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6746 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6747
6748 if ((dev != mPrimaryHardwareDev) &&
6749 (NULL != dev->set_master_volume)) {
6750 dev->set_master_volume(dev, initialVolume);
6751 }
6752 }
6753 mHardwareStatus = AUDIO_HW_IDLE;
6754 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6755 ? initialVolume
6756 : 1.0;
6757 mMasterVolume = initialVolume;
6758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 return id;
6760 }
6761
6762 return 0;
6763}
6764
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006765audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6766 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767{
6768 Mutex::Autolock _l(mLock);
6769 MixerThread *thread1 = checkMixerThread_l(output1);
6770 MixerThread *thread2 = checkMixerThread_l(output2);
6771
6772 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006773 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 return 0;
6775 }
6776
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006777 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006778 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6779 thread->addOutputTrack(thread2);
6780 mPlaybackThreads.add(id, thread);
6781 // notify client processes of the new output creation
6782 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6783 return id;
6784}
6785
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006786status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787{
6788 // keep strong reference on the playback thread so that
6789 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006790 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006791 {
6792 Mutex::Autolock _l(mLock);
6793 thread = checkPlaybackThread_l(output);
6794 if (thread == NULL) {
6795 return BAD_VALUE;
6796 }
6797
Steve Block3856b092011-10-20 11:56:00 +01006798 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006800 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006802 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6804 dupThread->removeOutputTrack((MixerThread *)thread.get());
6805 }
6806 }
6807 }
Glenn Kastena1117922012-01-26 10:53:32 -08006808 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 mPlaybackThreads.removeItem(output);
6810 }
6811 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006812 // The thread entity (active unit of execution) is no longer running here,
6813 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006815 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006816 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006817 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006818 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006819 out->hwDev->close_output_stream(out->hwDev, out->stream);
6820 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821 }
6822 return NO_ERROR;
6823}
6824
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006825status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826{
6827 Mutex::Autolock _l(mLock);
6828 PlaybackThread *thread = checkPlaybackThread_l(output);
6829
6830 if (thread == NULL) {
6831 return BAD_VALUE;
6832 }
6833
Steve Block3856b092011-10-20 11:56:00 +01006834 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 thread->suspend();
6836
6837 return NO_ERROR;
6838}
6839
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006840status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841{
6842 Mutex::Autolock _l(mLock);
6843 PlaybackThread *thread = checkPlaybackThread_l(output);
6844
6845 if (thread == NULL) {
6846 return BAD_VALUE;
6847 }
6848
Steve Block3856b092011-10-20 11:56:00 +01006849 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850
6851 thread->restore();
6852
6853 return NO_ERROR;
6854}
6855
Eric Laurenta4c5a552012-03-29 10:12:40 -07006856audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6857 audio_devices_t *pDevices,
6858 uint32_t *pSamplingRate,
6859 audio_format_t *pFormat,
6860 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861{
6862 status_t status;
6863 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006864 struct audio_config config = {
6865 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6866 channel_mask: pChannelMask ? *pChannelMask : 0,
6867 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6868 };
6869 uint32_t reqSamplingRate = config.sample_rate;
6870 audio_format_t reqFormat = config.format;
6871 audio_channel_mask_t reqChannels = config.channel_mask;
6872 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006873 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006874
6875 if (pDevices == NULL || *pDevices == 0) {
6876 return 0;
6877 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006878
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 Mutex::Autolock _l(mLock);
6880
Eric Laurenta4c5a552012-03-29 10:12:40 -07006881 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006882 if (inHwDev == NULL)
6883 return 0;
6884
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006885 audio_io_handle_t id = nextUniqueId();
6886
6887 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006888 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006889 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006890 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006891 config.sample_rate,
6892 config.format,
6893 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 status);
6895
6896 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6897 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6898 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006899 if (status == BAD_VALUE &&
6900 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6901 (config.sample_rate <= 2 * reqSamplingRate) &&
6902 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006903 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006904 inStream = NULL;
6905 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 }
6907
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006908 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006909 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6910
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006911 // Start record thread
6912 // RecorThread require both input and output device indication to forward to audio
6913 // pre processing modules
6914 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6915 thread = new RecordThread(this,
6916 input,
6917 reqSamplingRate,
6918 reqChannels,
6919 id,
6920 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006922 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006923 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006924 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006925 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926
Dima Zavin799a70e2011-04-18 16:57:27 -07006927 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928
6929 // notify client processes of the new input creation
6930 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6931 return id;
6932 }
6933
6934 return 0;
6935}
6936
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006937status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938{
6939 // keep strong reference on the record thread so that
6940 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006941 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942 {
6943 Mutex::Autolock _l(mLock);
6944 thread = checkRecordThread_l(input);
6945 if (thread == NULL) {
6946 return BAD_VALUE;
6947 }
6948
Steve Block3856b092011-10-20 11:56:00 +01006949 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006950 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 mRecordThreads.removeItem(input);
6952 }
6953 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006954 // The thread entity (active unit of execution) is no longer running here,
6955 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006957 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006958 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006959 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006960 in->hwDev->close_input_stream(in->hwDev, in->stream);
6961 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962
6963 return NO_ERROR;
6964}
6965
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006966status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967{
6968 Mutex::Autolock _l(mLock);
6969 MixerThread *dstThread = checkMixerThread_l(output);
6970 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006971 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 return BAD_VALUE;
6973 }
6974
Steve Block3856b092011-10-20 11:56:00 +01006975 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6977
6978 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6979 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006980 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 MixerThread *srcThread = (MixerThread *)thread;
6982 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 }
Eric Laurentde070132010-07-13 04:45:46 -07006984 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985
6986 return NO_ERROR;
6987}
6988
6989
6990int AudioFlinger::newAudioSessionId()
6991{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006992 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993}
6994
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006995void AudioFlinger::acquireAudioSessionId(int audioSession)
6996{
6997 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006998 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006999 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007000 size_t num = mAudioSessionRefs.size();
7001 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007002 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007003 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7004 ref->mCnt++;
7005 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007006 return;
7007 }
7008 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007009 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7010 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007011}
7012
7013void AudioFlinger::releaseAudioSessionId(int audioSession)
7014{
7015 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007016 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007017 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007018 size_t num = mAudioSessionRefs.size();
7019 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007020 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007021 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7022 ref->mCnt--;
7023 ALOGV(" decremented refcount to %d", ref->mCnt);
7024 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007025 mAudioSessionRefs.removeAt(i);
7026 delete ref;
7027 purgeStaleEffects_l();
7028 }
7029 return;
7030 }
7031 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007032 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007033}
7034
7035void AudioFlinger::purgeStaleEffects_l() {
7036
Steve Block3856b092011-10-20 11:56:00 +01007037 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007038
7039 Vector< sp<EffectChain> > chains;
7040
7041 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7042 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7043 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7044 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007045 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7046 chains.push(ec);
7047 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007048 }
7049 }
7050 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7051 sp<RecordThread> t = mRecordThreads.valueAt(i);
7052 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7053 sp<EffectChain> ec = t->mEffectChains[j];
7054 chains.push(ec);
7055 }
7056 }
7057
7058 for (size_t i = 0; i < chains.size(); i++) {
7059 sp<EffectChain> ec = chains[i];
7060 int sessionid = ec->sessionId();
7061 sp<ThreadBase> t = ec->mThread.promote();
7062 if (t == 0) {
7063 continue;
7064 }
7065 size_t numsessionrefs = mAudioSessionRefs.size();
7066 bool found = false;
7067 for (size_t k = 0; k < numsessionrefs; k++) {
7068 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007069 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007070 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007071 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007072 found = true;
7073 break;
7074 }
7075 }
7076 if (!found) {
7077 // remove all effects from the chain
7078 while (ec->mEffects.size()) {
7079 sp<EffectModule> effect = ec->mEffects[0];
7080 effect->unPin();
7081 Mutex::Autolock _l (t->mLock);
7082 t->removeEffect_l(effect);
7083 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7084 sp<EffectHandle> handle = effect->mHandles[j].promote();
7085 if (handle != 0) {
7086 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007087 if (handle->mHasControl && handle->mEnabled) {
7088 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7089 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007090 }
7091 }
7092 AudioSystem::unregisterEffect(effect->id());
7093 }
7094 }
7095 }
7096 return;
7097}
7098
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007100AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101{
Glenn Kastena1117922012-01-26 10:53:32 -08007102 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103}
7104
7105// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007106AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107{
7108 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007109 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007110}
7111
7112// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007113AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114{
Glenn Kastena1117922012-01-26 10:53:32 -08007115 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007116}
7117
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007118uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007120 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121}
7122
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007123AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007124{
7125 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7126 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007127 AudioStreamOut *output = thread->getOutput();
7128 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007129 return thread;
7130 }
7131 }
7132 return NULL;
7133}
7134
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007135uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007136{
7137 PlaybackThread *thread = primaryPlaybackThread_l();
7138
7139 if (thread == NULL) {
7140 return 0;
7141 }
7142
7143 return thread->device();
7144}
7145
Eric Laurenta011e352012-03-29 15:51:43 -07007146sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7147 int triggerSession,
7148 int listenerSession,
7149 sync_event_callback_t callBack,
7150 void *cookie)
7151{
7152 Mutex::Autolock _l(mLock);
7153
7154 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7155 status_t playStatus = NAME_NOT_FOUND;
7156 status_t recStatus = NAME_NOT_FOUND;
7157 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7158 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7159 if (playStatus == NO_ERROR) {
7160 return event;
7161 }
7162 }
7163 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7164 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7165 if (recStatus == NO_ERROR) {
7166 return event;
7167 }
7168 }
7169 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7170 mPendingSyncEvents.add(event);
7171 } else {
7172 ALOGV("createSyncEvent() invalid event %d", event->type());
7173 event.clear();
7174 }
7175 return event;
7176}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007177
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178// ----------------------------------------------------------------------------
7179// Effect management
7180// ----------------------------------------------------------------------------
7181
7182
Glenn Kastenf587ba52012-01-26 16:25:10 -08007183status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184{
7185 Mutex::Autolock _l(mLock);
7186 return EffectQueryNumberEffects(numEffects);
7187}
7188
Glenn Kastenf587ba52012-01-26 16:25:10 -08007189status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190{
7191 Mutex::Autolock _l(mLock);
7192 return EffectQueryEffect(index, descriptor);
7193}
7194
Glenn Kasten5e92a782012-01-30 07:40:52 -08007195status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007196 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197{
7198 Mutex::Autolock _l(mLock);
7199 return EffectGetDescriptor(pUuid, descriptor);
7200}
7201
7202
Mathias Agopian65ab4712010-07-14 17:59:35 -07007203sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7204 effect_descriptor_t *pDesc,
7205 const sp<IEffectClient>& effectClient,
7206 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007207 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 int sessionId,
7209 status_t *status,
7210 int *id,
7211 int *enabled)
7212{
7213 status_t lStatus = NO_ERROR;
7214 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007215 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007217 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007218 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007219
7220 if (pDesc == NULL) {
7221 lStatus = BAD_VALUE;
7222 goto Exit;
7223 }
7224
Eric Laurent84e9a102010-09-23 16:10:16 -07007225 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007226 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007227 lStatus = PERMISSION_DENIED;
7228 goto Exit;
7229 }
7230
Dima Zavinfce7a472011-04-19 22:30:36 -07007231 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007232 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007233 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007234 lStatus = PERMISSION_DENIED;
7235 goto Exit;
7236 }
7237
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007238 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007239 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007240 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007241 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007242 lStatus = BAD_VALUE;
7243 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007244 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007245 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007246 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007247 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007248 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007249 }
7250 }
7251
Mathias Agopian65ab4712010-07-14 17:59:35 -07007252 {
7253 Mutex::Autolock _l(mLock);
7254
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255
7256 if (!EffectIsNullUuid(&pDesc->uuid)) {
7257 // if uuid is specified, request effect descriptor
7258 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7259 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007260 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261 goto Exit;
7262 }
7263 } else {
7264 // if uuid is not specified, look for an available implementation
7265 // of the required type in effect factory
7266 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007267 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007268 lStatus = BAD_VALUE;
7269 goto Exit;
7270 }
7271 uint32_t numEffects = 0;
7272 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007273 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274 bool found = false;
7275
7276 lStatus = EffectQueryNumberEffects(&numEffects);
7277 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007278 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279 goto Exit;
7280 }
7281 for (uint32_t i = 0; i < numEffects; i++) {
7282 lStatus = EffectQueryEffect(i, &desc);
7283 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007284 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285 continue;
7286 }
7287 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7288 // If matching type found save effect descriptor. If the session is
7289 // 0 and the effect is not auxiliary, continue enumeration in case
7290 // an auxiliary version of this effect type is available
7291 found = true;
7292 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007293 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007294 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7295 break;
7296 }
7297 }
7298 }
7299 if (!found) {
7300 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007301 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302 goto Exit;
7303 }
7304 // For same effect type, chose auxiliary version over insert version if
7305 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007306 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7308 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7309 }
7310 }
7311
7312 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007313 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7315 lStatus = INVALID_OPERATION;
7316 goto Exit;
7317 }
7318
Eric Laurent59255e42011-07-27 19:49:51 -07007319 // check recording permission for visualizer
7320 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7321 !recordingAllowed()) {
7322 lStatus = PERMISSION_DENIED;
7323 goto Exit;
7324 }
7325
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326 // return effect descriptor
7327 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7328
7329 // If output is not specified try to find a matching audio session ID in one of the
7330 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007331 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7332 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007333 // Note: io is never 0 when creating an effect on an input
7334 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007335 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7337 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007338 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007339 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007340 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007342 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007343 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7344 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7345 io = mRecordThreads.keyAt(i);
7346 break;
7347 }
7348 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007349 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007350 // If no output thread contains the requested session ID, default to
7351 // first output. The effect chain will be moved to the correct output
7352 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007353 if (io == 0 && mPlaybackThreads.size()) {
7354 io = mPlaybackThreads.keyAt(0);
7355 }
Steve Block3856b092011-10-20 11:56:00 +01007356 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007357 }
7358 ThreadBase *thread = checkRecordThread_l(io);
7359 if (thread == NULL) {
7360 thread = checkPlaybackThread_l(io);
7361 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007362 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007363 lStatus = BAD_VALUE;
7364 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007367
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007368 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007370 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007371 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7372 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373 if (handle != 0 && id != NULL) {
7374 *id = handle->id();
7375 }
7376 }
7377
7378Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007379 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 *status = lStatus;
7381 }
7382 return handle;
7383}
7384
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007385status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7386 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007387{
Steve Block3856b092011-10-20 11:56:00 +01007388 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007389 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007390 Mutex::Autolock _l(mLock);
7391 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007392 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007393 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007394 }
Eric Laurentde070132010-07-13 04:45:46 -07007395 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7396 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007397 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007398 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399 }
Eric Laurentde070132010-07-13 04:45:46 -07007400 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7401 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007402 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007403 return BAD_VALUE;
7404 }
7405
7406 Mutex::Autolock _dl(dstThread->mLock);
7407 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007408 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007409
Mathias Agopian65ab4712010-07-14 17:59:35 -07007410 return NO_ERROR;
7411}
7412
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007413// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007414status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007415 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007416 AudioFlinger::PlaybackThread *dstThread,
7417 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007418{
Steve Block3856b092011-10-20 11:56:00 +01007419 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007420 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007421
Eric Laurent59255e42011-07-27 19:49:51 -07007422 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007423 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007424 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007425 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007426 return INVALID_OPERATION;
7427 }
7428
Eric Laurent39e94f82010-07-28 01:32:47 -07007429 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007430 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007431 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007432 // removed.
7433 srcThread->removeEffectChain_l(chain);
7434
7435 // transfer all effects one by one so that new effect chain is created on new thread with
7436 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007437 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007438 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007439 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007440 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7441 while (effect != 0) {
7442 srcThread->removeEffect_l(effect);
7443 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007444 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7445 if (effect->state() == EffectModule::ACTIVE ||
7446 effect->state() == EffectModule::STOPPING) {
7447 effect->start();
7448 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007449 // if the move request is not received from audio policy manager, the effect must be
7450 // re-registered with the new strategy and output
7451 if (dstChain == 0) {
7452 dstChain = effect->chain().promote();
7453 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007454 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007455 srcThread->addEffect_l(effect);
7456 return NO_INIT;
7457 }
7458 strategy = dstChain->strategy();
7459 }
7460 if (reRegister) {
7461 AudioSystem::unregisterEffect(effect->id());
7462 AudioSystem::registerEffect(&effect->desc(),
7463 dstOutput,
7464 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007465 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007466 effect->id());
7467 }
Eric Laurentde070132010-07-13 04:45:46 -07007468 effect = chain->getEffectFromId_l(0);
7469 }
7470
7471 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007472}
7473
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007474
Mathias Agopian65ab4712010-07-14 17:59:35 -07007475// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007476sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007477 const sp<AudioFlinger::Client>& client,
7478 const sp<IEffectClient>& effectClient,
7479 int32_t priority,
7480 int sessionId,
7481 effect_descriptor_t *desc,
7482 int *enabled,
7483 status_t *status
7484 )
7485{
7486 sp<EffectModule> effect;
7487 sp<EffectHandle> handle;
7488 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007489 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007490 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491 bool effectCreated = false;
7492 bool effectRegistered = false;
7493
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007494 lStatus = initCheck();
7495 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007496 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007497 goto Exit;
7498 }
7499
7500 // Do not allow effects with session ID 0 on direct output or duplicating threads
7501 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007502 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007503 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007504 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505 lStatus = BAD_VALUE;
7506 goto Exit;
7507 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007508 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007509 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007510 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007511 desc->name, desc->flags, mType);
7512 lStatus = BAD_VALUE;
7513 goto Exit;
7514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515
Steve Block3856b092011-10-20 11:56:00 +01007516 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007517
7518 { // scope for mLock
7519 Mutex::Autolock _l(mLock);
7520
7521 // check for existing effect chain with the requested audio session
7522 chain = getEffectChain_l(sessionId);
7523 if (chain == 0) {
7524 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007525 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526 chain = new EffectChain(this, sessionId);
7527 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007528 chain->setStrategy(getStrategyForSession_l(sessionId));
7529 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007530 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007531 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007532 }
7533
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007534 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535
7536 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007537 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007539 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 if (lStatus != NO_ERROR) {
7541 goto Exit;
7542 }
7543 effectRegistered = true;
7544 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007545 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007546 lStatus = effect->status();
7547 if (lStatus != NO_ERROR) {
7548 goto Exit;
7549 }
Eric Laurentcab11242010-07-15 12:50:15 -07007550 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 if (lStatus != NO_ERROR) {
7552 goto Exit;
7553 }
7554 effectCreated = true;
7555
7556 effect->setDevice(mDevice);
7557 effect->setMode(mAudioFlinger->getMode());
7558 }
7559 // create effect handle and connect it to effect module
7560 handle = new EffectHandle(effect, client, effectClient, priority);
7561 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007562 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563 *enabled = (int)effect->isEnabled();
7564 }
7565 }
7566
7567Exit:
7568 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007569 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007570 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007571 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007572 }
7573 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007574 AudioSystem::unregisterEffect(effect->id());
7575 }
7576 if (chainCreated) {
7577 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578 }
7579 handle.clear();
7580 }
7581
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007582 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 *status = lStatus;
7584 }
7585 return handle;
7586}
7587
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007588sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7589{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007590 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007591 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007592}
7593
Eric Laurentde070132010-07-13 04:45:46 -07007594// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7595// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007596status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007597{
7598 // check for existing effect chain with the requested audio session
7599 int sessionId = effect->sessionId();
7600 sp<EffectChain> chain = getEffectChain_l(sessionId);
7601 bool chainCreated = false;
7602
7603 if (chain == 0) {
7604 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007605 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007606 chain = new EffectChain(this, sessionId);
7607 addEffectChain_l(chain);
7608 chain->setStrategy(getStrategyForSession_l(sessionId));
7609 chainCreated = true;
7610 }
Steve Block3856b092011-10-20 11:56:00 +01007611 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007612
7613 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007614 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007615 this, effect->desc().name, chain.get());
7616 return BAD_VALUE;
7617 }
7618
7619 status_t status = chain->addEffect_l(effect);
7620 if (status != NO_ERROR) {
7621 if (chainCreated) {
7622 removeEffectChain_l(chain);
7623 }
7624 return status;
7625 }
7626
7627 effect->setDevice(mDevice);
7628 effect->setMode(mAudioFlinger->getMode());
7629 return NO_ERROR;
7630}
7631
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007632void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007633
Steve Block3856b092011-10-20 11:56:00 +01007634 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007636 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7637 detachAuxEffect_l(effect->id());
7638 }
7639
7640 sp<EffectChain> chain = effect->chain().promote();
7641 if (chain != 0) {
7642 // remove effect chain if removing last effect
7643 if (chain->removeEffect_l(effect) == 0) {
7644 removeEffectChain_l(chain);
7645 }
7646 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007647 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007648 }
7649}
7650
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007651void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007652 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007653{
7654 effectChains = mEffectChains;
7655 for (size_t i = 0; i < mEffectChains.size(); i++) {
7656 mEffectChains[i]->lock();
7657 }
7658}
7659
7660void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007661 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007662{
7663 for (size_t i = 0; i < effectChains.size(); i++) {
7664 effectChains[i]->unlock();
7665 }
7666}
7667
7668sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7669{
7670 Mutex::Autolock _l(mLock);
7671 return getEffectChain_l(sessionId);
7672}
7673
7674sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7675{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007676 size_t size = mEffectChains.size();
7677 for (size_t i = 0; i < size; i++) {
7678 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007679 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007680 }
7681 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007682 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007683}
7684
Glenn Kastenf78aee72012-01-04 11:00:47 -08007685void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007686{
7687 Mutex::Autolock _l(mLock);
7688 size_t size = mEffectChains.size();
7689 for (size_t i = 0; i < size; i++) {
7690 mEffectChains[i]->setMode_l(mode);
7691 }
7692}
7693
7694void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007695 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007696 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007697
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007699 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700 // delete the effect module if removing last handle on it
7701 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007702 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007703 removeEffect_l(effect);
7704 AudioSystem::unregisterEffect(effect->id());
7705 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007706 }
7707}
7708
7709status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7710{
7711 int session = chain->sessionId();
7712 int16_t *buffer = mMixBuffer;
7713 bool ownsBuffer = false;
7714
Steve Block3856b092011-10-20 11:56:00 +01007715 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716 if (session > 0) {
7717 // Only one effect chain can be present in direct output thread and it uses
7718 // the mix buffer as input
7719 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007720 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007721 buffer = new int16_t[numSamples];
7722 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007723 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007724 ownsBuffer = true;
7725 }
7726
7727 // Attach all tracks with same session ID to this chain.
7728 for (size_t i = 0; i < mTracks.size(); ++i) {
7729 sp<Track> track = mTracks[i];
7730 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007731 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007732 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007733 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007734 }
7735 }
7736
7737 // indicate all active tracks in the chain
7738 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7739 sp<Track> track = mActiveTracks[i].promote();
7740 if (track == 0) continue;
7741 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007742 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007743 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 }
7745 }
7746 }
7747
7748 chain->setInBuffer(buffer, ownsBuffer);
7749 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007750 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007751 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007752 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7753 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007755 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7756 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007757 // Effect chain for other sessions are inserted at beginning of effect
7758 // chains list to be processed before output mix effects. Relative order between other
7759 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760 size_t size = mEffectChains.size();
7761 size_t i = 0;
7762 for (i = 0; i < size; i++) {
7763 if (mEffectChains[i]->sessionId() < session) break;
7764 }
7765 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007766 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007767
7768 return NO_ERROR;
7769}
7770
7771size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7772{
7773 int session = chain->sessionId();
7774
Steve Block3856b092011-10-20 11:56:00 +01007775 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776
7777 for (size_t i = 0; i < mEffectChains.size(); i++) {
7778 if (chain == mEffectChains[i]) {
7779 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007780 // detach all active tracks from the chain
7781 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7782 sp<Track> track = mActiveTracks[i].promote();
7783 if (track == 0) continue;
7784 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007785 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007786 chain.get(), session);
7787 chain->decActiveTrackCnt();
7788 }
7789 }
7790
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 // detach all tracks with same session ID from this chain
7792 for (size_t i = 0; i < mTracks.size(); ++i) {
7793 sp<Track> track = mTracks[i];
7794 if (session == track->sessionId()) {
7795 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007796 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 }
7798 }
Eric Laurentde070132010-07-13 04:45:46 -07007799 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800 }
7801 }
7802 return mEffectChains.size();
7803}
7804
Eric Laurentde070132010-07-13 04:45:46 -07007805status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7806 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007807{
7808 Mutex::Autolock _l(mLock);
7809 return attachAuxEffect_l(track, EffectId);
7810}
7811
Eric Laurentde070132010-07-13 04:45:46 -07007812status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7813 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814{
7815 status_t status = NO_ERROR;
7816
7817 if (EffectId == 0) {
7818 track->setAuxBuffer(0, NULL);
7819 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007820 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7821 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 if (effect != 0) {
7823 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7824 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7825 } else {
7826 status = INVALID_OPERATION;
7827 }
7828 } else {
7829 status = BAD_VALUE;
7830 }
7831 }
7832 return status;
7833}
7834
7835void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7836{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007837 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838 sp<Track> track = mTracks[i];
7839 if (track->auxEffectId() == effectId) {
7840 attachAuxEffect_l(track, 0);
7841 }
7842 }
7843}
7844
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007845status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7846{
7847 // only one chain per input thread
7848 if (mEffectChains.size() != 0) {
7849 return INVALID_OPERATION;
7850 }
Steve Block3856b092011-10-20 11:56:00 +01007851 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007852
7853 chain->setInBuffer(NULL);
7854 chain->setOutBuffer(NULL);
7855
Eric Laurent59255e42011-07-27 19:49:51 -07007856 checkSuspendOnAddEffectChain_l(chain);
7857
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007858 mEffectChains.add(chain);
7859
7860 return NO_ERROR;
7861}
7862
7863size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7864{
Steve Block3856b092011-10-20 11:56:00 +01007865 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007866 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007867 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7868 chain.get(), mEffectChains.size(), this);
7869 if (mEffectChains.size() == 1) {
7870 mEffectChains.removeAt(0);
7871 }
7872 return 0;
7873}
7874
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875// ----------------------------------------------------------------------------
7876// EffectModule implementation
7877// ----------------------------------------------------------------------------
7878
7879#undef LOG_TAG
7880#define LOG_TAG "AudioFlinger::EffectModule"
7881
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007882AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007883 const wp<AudioFlinger::EffectChain>& chain,
7884 effect_descriptor_t *desc,
7885 int id,
7886 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007887 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007888 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889{
Steve Block3856b092011-10-20 11:56:00 +01007890 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007892 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007893 return;
7894 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007895
7896 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7897
7898 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007899 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900
7901 if (mStatus != NO_ERROR) {
7902 return;
7903 }
7904 lStatus = init();
7905 if (lStatus < 0) {
7906 mStatus = lStatus;
7907 goto Error;
7908 }
7909
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007910 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7911 mPinned = true;
7912 }
Steve Block3856b092011-10-20 11:56:00 +01007913 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 return;
7915Error:
7916 EffectRelease(mEffectInterface);
7917 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007918 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919}
7920
7921AudioFlinger::EffectModule::~EffectModule()
7922{
Steve Block3856b092011-10-20 11:56:00 +01007923 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007924 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007925 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7926 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7927 sp<ThreadBase> thread = mThread.promote();
7928 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007929 audio_stream_t *stream = thread->stream();
7930 if (stream != NULL) {
7931 stream->remove_audio_effect(stream, mEffectInterface);
7932 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007933 }
7934 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 // release effect engine
7936 EffectRelease(mEffectInterface);
7937 }
7938}
7939
Glenn Kasten435dbe62012-01-30 10:15:48 -08007940status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007941{
7942 status_t status;
7943
7944 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007945 int priority = handle->priority();
7946 size_t size = mHandles.size();
7947 sp<EffectHandle> h;
7948 size_t i;
7949 for (i = 0; i < size; i++) {
7950 h = mHandles[i].promote();
7951 if (h == 0) continue;
7952 if (h->priority() <= priority) break;
7953 }
7954 // if inserted in first place, move effect control from previous owner to this handle
7955 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007956 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007957 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007958 enabled = h->enabled();
7959 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960 }
Eric Laurent59255e42011-07-27 19:49:51 -07007961 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962 status = NO_ERROR;
7963 } else {
7964 status = ALREADY_EXISTS;
7965 }
Steve Block3856b092011-10-20 11:56:00 +01007966 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967 mHandles.insertAt(handle, i);
7968 return status;
7969}
7970
7971size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7972{
7973 Mutex::Autolock _l(mLock);
7974 size_t size = mHandles.size();
7975 size_t i;
7976 for (i = 0; i < size; i++) {
7977 if (mHandles[i] == handle) break;
7978 }
7979 if (i == size) {
7980 return size;
7981 }
Steve Block3856b092011-10-20 11:56:00 +01007982 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007983
7984 bool enabled = false;
7985 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007986 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007987 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007988 enabled = hdl->enabled();
7989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990 mHandles.removeAt(i);
7991 size = mHandles.size();
7992 // if removed from first place, move effect control from this handle to next in line
7993 if (i == 0 && size != 0) {
7994 sp<EffectHandle> h = mHandles[0].promote();
7995 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007996 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997 }
7998 }
7999
Eric Laurentec437d82011-07-26 20:54:46 -07008000 // Prevent calls to process() and other functions on effect interface from now on.
8001 // The effect engine will be released by the destructor when the last strong reference on
8002 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008003 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008004 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008005 }
8006
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007 return size;
8008}
8009
Eric Laurent59255e42011-07-27 19:49:51 -07008010sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8011{
8012 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08008013 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008014}
8015
Glenn Kasten58123c32012-02-03 10:32:24 -08008016void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017{
Glenn Kasten90bebef2012-01-27 15:24:38 -08008018 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008019 // keep a strong reference on this EffectModule to avoid calling the
8020 // destructor before we exit
8021 sp<EffectModule> keep(this);
8022 {
8023 sp<ThreadBase> thread = mThread.promote();
8024 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008025 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026 }
8027 }
8028}
8029
8030void AudioFlinger::EffectModule::updateState() {
8031 Mutex::Autolock _l(mLock);
8032
8033 switch (mState) {
8034 case RESTART:
8035 reset_l();
8036 // FALL THROUGH
8037
8038 case STARTING:
8039 // clear auxiliary effect input buffer for next accumulation
8040 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8041 memset(mConfig.inputCfg.buffer.raw,
8042 0,
8043 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8044 }
8045 start_l();
8046 mState = ACTIVE;
8047 break;
8048 case STOPPING:
8049 stop_l();
8050 mDisableWaitCnt = mMaxDisableWaitCnt;
8051 mState = STOPPED;
8052 break;
8053 case STOPPED:
8054 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8055 // turn off sequence.
8056 if (--mDisableWaitCnt == 0) {
8057 reset_l();
8058 mState = IDLE;
8059 }
8060 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008061 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008062 break;
8063 }
8064}
8065
8066void AudioFlinger::EffectModule::process()
8067{
8068 Mutex::Autolock _l(mLock);
8069
Eric Laurentec437d82011-07-26 20:54:46 -07008070 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008071 mConfig.inputCfg.buffer.raw == NULL ||
8072 mConfig.outputCfg.buffer.raw == NULL) {
8073 return;
8074 }
8075
Eric Laurent8f45bd72010-08-31 13:50:07 -07008076 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008077 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8078 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008079 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008080 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008081 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082 }
8083
8084 // do the actual processing in the effect engine
8085 int ret = (*mEffectInterface)->process(mEffectInterface,
8086 &mConfig.inputCfg.buffer,
8087 &mConfig.outputCfg.buffer);
8088
8089 // force transition to IDLE state when engine is ready
8090 if (mState == STOPPED && ret == -ENODATA) {
8091 mDisableWaitCnt = 1;
8092 }
8093
8094 // clear auxiliary effect input buffer for next accumulation
8095 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008096 memset(mConfig.inputCfg.buffer.raw, 0,
8097 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098 }
8099 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008100 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8101 // If an insert effect is idle and input buffer is different from output buffer,
8102 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008103 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008104 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008105 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8106 int16_t *in = mConfig.inputCfg.buffer.s16;
8107 int16_t *out = mConfig.outputCfg.buffer.s16;
8108 for (size_t i = 0; i < frameCnt; i++) {
8109 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008111 }
8112 }
8113}
8114
8115void AudioFlinger::EffectModule::reset_l()
8116{
8117 if (mEffectInterface == NULL) {
8118 return;
8119 }
8120 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8121}
8122
8123status_t AudioFlinger::EffectModule::configure()
8124{
8125 uint32_t channels;
8126 if (mEffectInterface == NULL) {
8127 return NO_INIT;
8128 }
8129
8130 sp<ThreadBase> thread = mThread.promote();
8131 if (thread == 0) {
8132 return DEAD_OBJECT;
8133 }
8134
8135 // TODO: handle configuration of effects replacing track process
8136 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008137 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008139 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140 }
8141
8142 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008143 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008144 } else {
8145 mConfig.inputCfg.channels = channels;
8146 }
8147 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008148 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8149 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008150 mConfig.inputCfg.samplingRate = thread->sampleRate();
8151 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8152 mConfig.inputCfg.bufferProvider.cookie = NULL;
8153 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8154 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8155 mConfig.outputCfg.bufferProvider.cookie = NULL;
8156 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8157 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8158 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8159 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008160 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008161 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162 // - in other sessions:
8163 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8164 // other effect: overwrites output buffer: input buffer == output buffer
8165 // Auxiliary effect:
8166 // accumulates in output buffer: input buffer != output buffer
8167 // Therefore: accumulate <=> input buffer != output buffer
8168 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8169 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8170 } else {
8171 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8172 }
8173 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8174 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8175 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8176 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8177
Steve Block3856b092011-10-20 11:56:00 +01008178 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008179 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8180
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008182 uint32_t size = sizeof(int);
8183 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008184 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008185 sizeof(effect_config_t),
8186 &mConfig,
8187 &size,
8188 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008189 if (status == 0) {
8190 status = cmdStatus;
8191 }
8192
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008193 if (status == 0 &&
8194 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8195 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8196 effect_param_t *p = (effect_param_t *)buf32;
8197
8198 p->psize = sizeof(uint32_t);
8199 p->vsize = sizeof(uint32_t);
8200 size = sizeof(int);
8201 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8202
8203 uint32_t latency = 0;
8204 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8205 if (pbt != NULL) {
8206 latency = pbt->latency_l();
8207 }
8208
8209 *((int32_t *)p->data + 1)= latency;
8210 (*mEffectInterface)->command(mEffectInterface,
8211 EFFECT_CMD_SET_PARAM,
8212 sizeof(effect_param_t) + 8,
8213 &buf32,
8214 &size,
8215 &cmdStatus);
8216 }
8217
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8219 (1000 * mConfig.outputCfg.buffer.frameCount);
8220
8221 return status;
8222}
8223
8224status_t AudioFlinger::EffectModule::init()
8225{
8226 Mutex::Autolock _l(mLock);
8227 if (mEffectInterface == NULL) {
8228 return NO_INIT;
8229 }
8230 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008231 uint32_t size = sizeof(status_t);
8232 status_t status = (*mEffectInterface)->command(mEffectInterface,
8233 EFFECT_CMD_INIT,
8234 0,
8235 NULL,
8236 &size,
8237 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008238 if (status == 0) {
8239 status = cmdStatus;
8240 }
8241 return status;
8242}
8243
Eric Laurentec35a142011-10-05 17:42:25 -07008244status_t AudioFlinger::EffectModule::start()
8245{
8246 Mutex::Autolock _l(mLock);
8247 return start_l();
8248}
8249
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250status_t AudioFlinger::EffectModule::start_l()
8251{
8252 if (mEffectInterface == NULL) {
8253 return NO_INIT;
8254 }
8255 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008256 uint32_t size = sizeof(status_t);
8257 status_t status = (*mEffectInterface)->command(mEffectInterface,
8258 EFFECT_CMD_ENABLE,
8259 0,
8260 NULL,
8261 &size,
8262 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008263 if (status == 0) {
8264 status = cmdStatus;
8265 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008266 if (status == 0 &&
8267 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8268 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8269 sp<ThreadBase> thread = mThread.promote();
8270 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008271 audio_stream_t *stream = thread->stream();
8272 if (stream != NULL) {
8273 stream->add_audio_effect(stream, mEffectInterface);
8274 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008275 }
8276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008277 return status;
8278}
8279
Eric Laurentec437d82011-07-26 20:54:46 -07008280status_t AudioFlinger::EffectModule::stop()
8281{
8282 Mutex::Autolock _l(mLock);
8283 return stop_l();
8284}
8285
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286status_t AudioFlinger::EffectModule::stop_l()
8287{
8288 if (mEffectInterface == NULL) {
8289 return NO_INIT;
8290 }
8291 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008292 uint32_t size = sizeof(status_t);
8293 status_t status = (*mEffectInterface)->command(mEffectInterface,
8294 EFFECT_CMD_DISABLE,
8295 0,
8296 NULL,
8297 &size,
8298 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008299 if (status == 0) {
8300 status = cmdStatus;
8301 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008302 if (status == 0 &&
8303 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8304 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8305 sp<ThreadBase> thread = mThread.promote();
8306 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008307 audio_stream_t *stream = thread->stream();
8308 if (stream != NULL) {
8309 stream->remove_audio_effect(stream, mEffectInterface);
8310 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008311 }
8312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313 return status;
8314}
8315
Eric Laurent25f43952010-07-28 05:40:18 -07008316status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8317 uint32_t cmdSize,
8318 void *pCmdData,
8319 uint32_t *replySize,
8320 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008321{
8322 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008323// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008324
Eric Laurentec437d82011-07-26 20:54:46 -07008325 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008326 return NO_INIT;
8327 }
Eric Laurent25f43952010-07-28 05:40:18 -07008328 status_t status = (*mEffectInterface)->command(mEffectInterface,
8329 cmdCode,
8330 cmdSize,
8331 pCmdData,
8332 replySize,
8333 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008334 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008335 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 for (size_t i = 1; i < mHandles.size(); i++) {
8337 sp<EffectHandle> h = mHandles[i].promote();
8338 if (h != 0) {
8339 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8340 }
8341 }
8342 }
8343 return status;
8344}
8345
8346status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8347{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008348
Mathias Agopian65ab4712010-07-14 17:59:35 -07008349 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008350 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008351
8352 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008353 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8354 if (enabled && status != NO_ERROR) {
8355 return status;
8356 }
8357
Mathias Agopian65ab4712010-07-14 17:59:35 -07008358 switch (mState) {
8359 // going from disabled to enabled
8360 case IDLE:
8361 mState = STARTING;
8362 break;
8363 case STOPPED:
8364 mState = RESTART;
8365 break;
8366 case STOPPING:
8367 mState = ACTIVE;
8368 break;
8369
8370 // going from enabled to disabled
8371 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008372 mState = STOPPED;
8373 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008374 case STARTING:
8375 mState = IDLE;
8376 break;
8377 case ACTIVE:
8378 mState = STOPPING;
8379 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008380 case DESTROYED:
8381 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 }
8383 for (size_t i = 1; i < mHandles.size(); i++) {
8384 sp<EffectHandle> h = mHandles[i].promote();
8385 if (h != 0) {
8386 h->setEnabled(enabled);
8387 }
8388 }
8389 }
8390 return NO_ERROR;
8391}
8392
Glenn Kastenc59c0042012-02-02 14:06:11 -08008393bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394{
8395 switch (mState) {
8396 case RESTART:
8397 case STARTING:
8398 case ACTIVE:
8399 return true;
8400 case IDLE:
8401 case STOPPING:
8402 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008403 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404 default:
8405 return false;
8406 }
8407}
8408
Glenn Kastenc59c0042012-02-02 14:06:11 -08008409bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008410{
8411 switch (mState) {
8412 case RESTART:
8413 case ACTIVE:
8414 case STOPPING:
8415 case STOPPED:
8416 return true;
8417 case IDLE:
8418 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008419 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008420 default:
8421 return false;
8422 }
8423}
8424
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8426{
8427 Mutex::Autolock _l(mLock);
8428 status_t status = NO_ERROR;
8429
8430 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8431 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008432 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008433 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8434 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008435 status_t cmdStatus;
8436 uint32_t volume[2];
8437 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008438 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008439 volume[0] = *left;
8440 volume[1] = *right;
8441 if (controller) {
8442 pVolume = volume;
8443 }
Eric Laurent25f43952010-07-28 05:40:18 -07008444 status = (*mEffectInterface)->command(mEffectInterface,
8445 EFFECT_CMD_SET_VOLUME,
8446 size,
8447 volume,
8448 &size,
8449 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008450 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8451 *left = volume[0];
8452 *right = volume[1];
8453 }
8454 }
8455 return status;
8456}
8457
8458status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8459{
8460 Mutex::Autolock _l(mLock);
8461 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008462 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8463 // audio pre processing modules on RecordThread can receive both output and
8464 // input device indication in the same call
8465 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8466 if (dev) {
8467 status_t cmdStatus;
8468 uint32_t size = sizeof(status_t);
8469
8470 status = (*mEffectInterface)->command(mEffectInterface,
8471 EFFECT_CMD_SET_DEVICE,
8472 sizeof(uint32_t),
8473 &dev,
8474 &size,
8475 &cmdStatus);
8476 if (status == NO_ERROR) {
8477 status = cmdStatus;
8478 }
8479 }
8480 dev = device & AUDIO_DEVICE_IN_ALL;
8481 if (dev) {
8482 status_t cmdStatus;
8483 uint32_t size = sizeof(status_t);
8484
8485 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8486 EFFECT_CMD_SET_INPUT_DEVICE,
8487 sizeof(uint32_t),
8488 &dev,
8489 &size,
8490 &cmdStatus);
8491 if (status2 == NO_ERROR) {
8492 status2 = cmdStatus;
8493 }
8494 if (status == NO_ERROR) {
8495 status = status2;
8496 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497 }
8498 }
8499 return status;
8500}
8501
Glenn Kastenf78aee72012-01-04 11:00:47 -08008502status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503{
8504 Mutex::Autolock _l(mLock);
8505 status_t status = NO_ERROR;
8506 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008507 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008508 uint32_t size = sizeof(status_t);
8509 status = (*mEffectInterface)->command(mEffectInterface,
8510 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008511 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008512 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008513 &size,
8514 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008515 if (status == NO_ERROR) {
8516 status = cmdStatus;
8517 }
8518 }
8519 return status;
8520}
8521
Eric Laurent59255e42011-07-27 19:49:51 -07008522void AudioFlinger::EffectModule::setSuspended(bool suspended)
8523{
8524 Mutex::Autolock _l(mLock);
8525 mSuspended = suspended;
8526}
Glenn Kastena3a85482012-01-04 11:01:11 -08008527
8528bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008529{
8530 Mutex::Autolock _l(mLock);
8531 return mSuspended;
8532}
8533
Mathias Agopian65ab4712010-07-14 17:59:35 -07008534status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8535{
8536 const size_t SIZE = 256;
8537 char buffer[SIZE];
8538 String8 result;
8539
8540 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8541 result.append(buffer);
8542
8543 bool locked = tryLock(mLock);
8544 // failed to lock - AudioFlinger is probably deadlocked
8545 if (!locked) {
8546 result.append("\t\tCould not lock Fx mutex:\n");
8547 }
8548
8549 result.append("\t\tSession Status State Engine:\n");
8550 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8551 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8552 result.append(buffer);
8553
8554 result.append("\t\tDescriptor:\n");
8555 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8556 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8557 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8558 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8559 result.append(buffer);
8560 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8561 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8562 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8563 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8564 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008565 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008566 mDescriptor.apiVersion,
8567 mDescriptor.flags);
8568 result.append(buffer);
8569 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8570 mDescriptor.name);
8571 result.append(buffer);
8572 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8573 mDescriptor.implementor);
8574 result.append(buffer);
8575
8576 result.append("\t\t- Input configuration:\n");
8577 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8578 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8579 (uint32_t)mConfig.inputCfg.buffer.raw,
8580 mConfig.inputCfg.buffer.frameCount,
8581 mConfig.inputCfg.samplingRate,
8582 mConfig.inputCfg.channels,
8583 mConfig.inputCfg.format);
8584 result.append(buffer);
8585
8586 result.append("\t\t- Output configuration:\n");
8587 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8588 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8589 (uint32_t)mConfig.outputCfg.buffer.raw,
8590 mConfig.outputCfg.buffer.frameCount,
8591 mConfig.outputCfg.samplingRate,
8592 mConfig.outputCfg.channels,
8593 mConfig.outputCfg.format);
8594 result.append(buffer);
8595
8596 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8597 result.append(buffer);
8598 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8599 for (size_t i = 0; i < mHandles.size(); ++i) {
8600 sp<EffectHandle> handle = mHandles[i].promote();
8601 if (handle != 0) {
8602 handle->dump(buffer, SIZE);
8603 result.append(buffer);
8604 }
8605 }
8606
8607 result.append("\n");
8608
8609 write(fd, result.string(), result.length());
8610
8611 if (locked) {
8612 mLock.unlock();
8613 }
8614
8615 return NO_ERROR;
8616}
8617
8618// ----------------------------------------------------------------------------
8619// EffectHandle implementation
8620// ----------------------------------------------------------------------------
8621
8622#undef LOG_TAG
8623#define LOG_TAG "AudioFlinger::EffectHandle"
8624
8625AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8626 const sp<AudioFlinger::Client>& client,
8627 const sp<IEffectClient>& effectClient,
8628 int32_t priority)
8629 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008630 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008631 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008632{
Steve Block3856b092011-10-20 11:56:00 +01008633 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008634
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008635 if (client == 0) {
8636 return;
8637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008638 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8639 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8640 if (mCblkMemory != 0) {
8641 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8642
Glenn Kastena0d68332012-01-27 16:47:15 -08008643 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008644 new(mCblk) effect_param_cblk_t();
8645 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008646 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008647 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008648 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008649 return;
8650 }
8651}
8652
8653AudioFlinger::EffectHandle::~EffectHandle()
8654{
Steve Block3856b092011-10-20 11:56:00 +01008655 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008656 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008657 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008658}
8659
8660status_t AudioFlinger::EffectHandle::enable()
8661{
Steve Block3856b092011-10-20 11:56:00 +01008662 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008663 if (!mHasControl) return INVALID_OPERATION;
8664 if (mEffect == 0) return DEAD_OBJECT;
8665
Eric Laurentdb7c0792011-08-10 10:37:50 -07008666 if (mEnabled) {
8667 return NO_ERROR;
8668 }
8669
Eric Laurent59255e42011-07-27 19:49:51 -07008670 mEnabled = true;
8671
8672 sp<ThreadBase> thread = mEffect->thread().promote();
8673 if (thread != 0) {
8674 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8675 }
8676
8677 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8678 if (mEffect->suspended()) {
8679 return NO_ERROR;
8680 }
8681
Eric Laurentdb7c0792011-08-10 10:37:50 -07008682 status_t status = mEffect->setEnabled(true);
8683 if (status != NO_ERROR) {
8684 if (thread != 0) {
8685 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8686 }
8687 mEnabled = false;
8688 }
8689 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690}
8691
8692status_t AudioFlinger::EffectHandle::disable()
8693{
Steve Block3856b092011-10-20 11:56:00 +01008694 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008695 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008696 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008697
Eric Laurentdb7c0792011-08-10 10:37:50 -07008698 if (!mEnabled) {
8699 return NO_ERROR;
8700 }
Eric Laurent59255e42011-07-27 19:49:51 -07008701 mEnabled = false;
8702
8703 if (mEffect->suspended()) {
8704 return NO_ERROR;
8705 }
8706
8707 status_t status = mEffect->setEnabled(false);
8708
8709 sp<ThreadBase> thread = mEffect->thread().promote();
8710 if (thread != 0) {
8711 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8712 }
8713
8714 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008715}
8716
8717void AudioFlinger::EffectHandle::disconnect()
8718{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008719 disconnect(true);
8720}
8721
Glenn Kasten58123c32012-02-03 10:32:24 -08008722void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008723{
Glenn Kasten58123c32012-02-03 10:32:24 -08008724 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 if (mEffect == 0) {
8726 return;
8727 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008728 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008729
Eric Laurenta85a74a2011-10-19 11:44:54 -07008730 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008731 sp<ThreadBase> thread = mEffect->thread().promote();
8732 if (thread != 0) {
8733 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8734 }
Eric Laurent59255e42011-07-27 19:49:51 -07008735 }
8736
Mathias Agopian65ab4712010-07-14 17:59:35 -07008737 // release sp on module => module destructor can be called now
8738 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008739 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008740 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008741 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008742 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8743 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008744 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008745 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8747 mClient.clear();
8748 }
8749}
8750
Eric Laurent25f43952010-07-28 05:40:18 -07008751status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8752 uint32_t cmdSize,
8753 void *pCmdData,
8754 uint32_t *replySize,
8755 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756{
Steve Block3856b092011-10-20 11:56:00 +01008757// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008758// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008759
8760 // only get parameter command is permitted for applications not controlling the effect
8761 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8762 return INVALID_OPERATION;
8763 }
8764 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008765 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008766
8767 // handle commands that are not forwarded transparently to effect engine
8768 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8769 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8770 // no risk to block the whole media server process or mixer threads is we are stuck here
8771 Mutex::Autolock _l(mCblk->lock);
8772 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8773 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8774 mCblk->serverIndex = 0;
8775 mCblk->clientIndex = 0;
8776 return BAD_VALUE;
8777 }
8778 status_t status = NO_ERROR;
8779 while (mCblk->serverIndex < mCblk->clientIndex) {
8780 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008781 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008782 int *p = (int *)(mBuffer + mCblk->serverIndex);
8783 int size = *p++;
8784 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008785 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008786 break;
8787 }
8788 effect_param_t *param = (effect_param_t *)p;
8789 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008790 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008791 mCblk->serverIndex += size;
8792 continue;
8793 }
Eric Laurent25f43952010-07-28 05:40:18 -07008794 uint32_t psize = sizeof(effect_param_t) +
8795 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8796 param->vsize;
8797 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8798 psize,
8799 p,
8800 &rsize,
8801 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008802 // stop at first error encountered
8803 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008804 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008805 *(int *)pReplyData = reply;
8806 break;
8807 } else if (reply != NO_ERROR) {
8808 *(int *)pReplyData = reply;
8809 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810 }
8811 mCblk->serverIndex += size;
8812 }
8813 mCblk->serverIndex = 0;
8814 mCblk->clientIndex = 0;
8815 return status;
8816 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008817 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818 return enable();
8819 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008820 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821 return disable();
8822 }
8823
8824 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8825}
8826
Eric Laurent59255e42011-07-27 19:49:51 -07008827void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008828{
Steve Block3856b092011-10-20 11:56:00 +01008829 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008830
8831 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008832 mEnabled = enabled;
8833
Mathias Agopian65ab4712010-07-14 17:59:35 -07008834 if (signal && mEffectClient != 0) {
8835 mEffectClient->controlStatusChanged(hasControl);
8836 }
8837}
8838
Eric Laurent25f43952010-07-28 05:40:18 -07008839void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8840 uint32_t cmdSize,
8841 void *pCmdData,
8842 uint32_t replySize,
8843 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008844{
8845 if (mEffectClient != 0) {
8846 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8847 }
8848}
8849
8850
8851
8852void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8853{
8854 if (mEffectClient != 0) {
8855 mEffectClient->enableStatusChanged(enabled);
8856 }
8857}
8858
8859status_t AudioFlinger::EffectHandle::onTransact(
8860 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8861{
8862 return BnEffect::onTransact(code, data, reply, flags);
8863}
8864
8865
8866void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8867{
Glenn Kastena0d68332012-01-27 16:47:15 -08008868 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008869
8870 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008871 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008872 mPriority,
8873 mHasControl,
8874 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008875 mCblk ? mCblk->clientIndex : 0,
8876 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877 );
8878
8879 if (locked) {
8880 mCblk->lock.unlock();
8881 }
8882}
8883
8884#undef LOG_TAG
8885#define LOG_TAG "AudioFlinger::EffectChain"
8886
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008887AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008888 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008889 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008890 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8891 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892{
Dima Zavinfce7a472011-04-19 22:30:36 -07008893 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008894 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008895 return;
8896 }
8897 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8898 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008899}
8900
8901AudioFlinger::EffectChain::~EffectChain()
8902{
8903 if (mOwnInBuffer) {
8904 delete mInBuffer;
8905 }
8906
8907}
8908
Eric Laurent59255e42011-07-27 19:49:51 -07008909// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008910sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008911{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912 size_t size = mEffects.size();
8913
8914 for (size_t i = 0; i < size; i++) {
8915 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008916 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008917 }
8918 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008919 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008920}
8921
Eric Laurent59255e42011-07-27 19:49:51 -07008922// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008923sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008924{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008925 size_t size = mEffects.size();
8926
8927 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008928 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8929 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008930 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931 }
8932 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008933 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008934}
8935
Eric Laurent59255e42011-07-27 19:49:51 -07008936// getEffectFromType_l() must be called with ThreadBase::mLock held
8937sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8938 const effect_uuid_t *type)
8939{
Eric Laurent59255e42011-07-27 19:49:51 -07008940 size_t size = mEffects.size();
8941
8942 for (size_t i = 0; i < size; i++) {
8943 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008944 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008945 }
8946 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008947 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008948}
8949
Eric Laurent91b14c42012-05-30 12:30:29 -07008950void AudioFlinger::EffectChain::clearInputBuffer()
8951{
8952 Mutex::Autolock _l(mLock);
8953 sp<ThreadBase> thread = mThread.promote();
8954 if (thread == 0) {
8955 ALOGW("clearInputBuffer(): cannot promote mixer thread");
8956 return;
8957 }
8958 clearInputBuffer_l(thread);
8959}
8960
8961// Must be called with EffectChain::mLock locked
8962void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
8963{
8964 size_t numSamples = thread->frameCount() * thread->channelCount();
8965 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8966
8967}
8968
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969// Must be called with EffectChain::mLock locked
8970void AudioFlinger::EffectChain::process_l()
8971{
Eric Laurentdac69112010-09-28 14:09:57 -07008972 sp<ThreadBase> thread = mThread.promote();
8973 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008974 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008975 return;
8976 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008977 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8978 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008979 // always process effects unless no more tracks are on the session and the effect tail
8980 // has been rendered
8981 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008982 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008983 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008984
Eric Laurent544fe9b2011-11-11 15:42:52 -08008985 if (!tracksOnSession && mTailBufferCount == 0) {
8986 doProcess = false;
8987 }
8988
8989 if (activeTrackCnt() == 0) {
8990 // if no track is active and the effect tail has not been rendered,
8991 // the input buffer must be cleared here as the mixer process will not do it
8992 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07008993 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008994 if (mTailBufferCount > 0) {
8995 mTailBufferCount--;
8996 }
8997 }
8998 }
Eric Laurentdac69112010-09-28 14:09:57 -07008999 }
9000
Mathias Agopian65ab4712010-07-14 17:59:35 -07009001 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009002 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009003 for (size_t i = 0; i < size; i++) {
9004 mEffects[i]->process();
9005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009006 }
9007 for (size_t i = 0; i < size; i++) {
9008 mEffects[i]->updateState();
9009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009010}
9011
Eric Laurentcab11242010-07-15 12:50:15 -07009012// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009013status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014{
9015 effect_descriptor_t desc = effect->desc();
9016 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9017
9018 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009019 effect->setChain(this);
9020 sp<ThreadBase> thread = mThread.promote();
9021 if (thread == 0) {
9022 return NO_INIT;
9023 }
9024 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025
9026 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9027 // Auxiliary effects are inserted at the beginning of mEffects vector as
9028 // they are processed first and accumulated in chain input buffer
9029 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009030
Mathias Agopian65ab4712010-07-14 17:59:35 -07009031 // the input buffer for auxiliary effect contains mono samples in
9032 // 32 bit format. This is to avoid saturation in AudoMixer
9033 // accumulation stage. Saturation is done in EffectModule::process() before
9034 // calling the process in effect engine
9035 size_t numSamples = thread->frameCount();
9036 int32_t *buffer = new int32_t[numSamples];
9037 memset(buffer, 0, numSamples * sizeof(int32_t));
9038 effect->setInBuffer((int16_t *)buffer);
9039 // auxiliary effects output samples to chain input buffer for further processing
9040 // by insert effects
9041 effect->setOutBuffer(mInBuffer);
9042 } else {
9043 // Insert effects are inserted at the end of mEffects vector as they are processed
9044 // after track and auxiliary effects.
9045 // Insert effect order as a function of indicated preference:
9046 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9047 // another effect is present
9048 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9049 // last effect claiming first position
9050 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9051 // first effect claiming last position
9052 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9053 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9054 // already present
9055
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009056 size_t size = mEffects.size();
9057 size_t idx_insert = size;
9058 ssize_t idx_insert_first = -1;
9059 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009060
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009061 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 effect_descriptor_t d = mEffects[i]->desc();
9063 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9064 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9065 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9066 // check invalid effect chaining combinations
9067 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9068 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009069 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009070 return INVALID_OPERATION;
9071 }
9072 // remember position of first insert effect and by default
9073 // select this as insert position for new effect
9074 if (idx_insert == size) {
9075 idx_insert = i;
9076 }
9077 // remember position of last insert effect claiming
9078 // first position
9079 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9080 idx_insert_first = i;
9081 }
9082 // remember position of first insert effect claiming
9083 // last position
9084 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9085 idx_insert_last == -1) {
9086 idx_insert_last = i;
9087 }
9088 }
9089 }
9090
9091 // modify idx_insert from first position if needed
9092 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9093 if (idx_insert_last != -1) {
9094 idx_insert = idx_insert_last;
9095 } else {
9096 idx_insert = size;
9097 }
9098 } else {
9099 if (idx_insert_first != -1) {
9100 idx_insert = idx_insert_first + 1;
9101 }
9102 }
9103
9104 // always read samples from chain input buffer
9105 effect->setInBuffer(mInBuffer);
9106
9107 // if last effect in the chain, output samples to chain
9108 // output buffer, otherwise to chain input buffer
9109 if (idx_insert == size) {
9110 if (idx_insert != 0) {
9111 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9112 mEffects[idx_insert-1]->configure();
9113 }
9114 effect->setOutBuffer(mOutBuffer);
9115 } else {
9116 effect->setOutBuffer(mInBuffer);
9117 }
9118 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009119
Steve Block3856b092011-10-20 11:56:00 +01009120 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009121 }
9122 effect->configure();
9123 return NO_ERROR;
9124}
9125
Eric Laurentcab11242010-07-15 12:50:15 -07009126// removeEffect_l() must be called with PlaybackThread::mLock held
9127size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128{
9129 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009130 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009131 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9132
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009133 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009134 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009135 // calling stop here will remove pre-processing effect from the audio HAL.
9136 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9137 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009138 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9139 mEffects[i]->state() == EffectModule::STOPPING) {
9140 mEffects[i]->stop();
9141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009142 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9143 delete[] effect->inBuffer();
9144 } else {
9145 if (i == size - 1 && i != 0) {
9146 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9147 mEffects[i - 1]->configure();
9148 }
9149 }
9150 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009151 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009152 break;
9153 }
9154 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009155
9156 return mEffects.size();
9157}
9158
Eric Laurentcab11242010-07-15 12:50:15 -07009159// setDevice_l() must be called with PlaybackThread::mLock held
9160void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009161{
9162 size_t size = mEffects.size();
9163 for (size_t i = 0; i < size; i++) {
9164 mEffects[i]->setDevice(device);
9165 }
9166}
9167
Eric Laurentcab11242010-07-15 12:50:15 -07009168// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009169void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009170{
9171 size_t size = mEffects.size();
9172 for (size_t i = 0; i < size; i++) {
9173 mEffects[i]->setMode(mode);
9174 }
9175}
9176
Eric Laurentcab11242010-07-15 12:50:15 -07009177// setVolume_l() must be called with PlaybackThread::mLock held
9178bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009179{
9180 uint32_t newLeft = *left;
9181 uint32_t newRight = *right;
9182 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009183 int ctrlIdx = -1;
9184 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009185
Eric Laurentcab11242010-07-15 12:50:15 -07009186 // first update volume controller
9187 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009188 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009189 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9190 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009191 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009192 break;
9193 }
9194 }
9195
9196 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009197 if (hasControl) {
9198 *left = mNewLeftVolume;
9199 *right = mNewRightVolume;
9200 }
9201 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009202 }
9203
9204 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009205 mLeftVolume = newLeft;
9206 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009207
9208 // second get volume update from volume controller
9209 if (ctrlIdx >= 0) {
9210 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009211 mNewLeftVolume = newLeft;
9212 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213 }
9214 // then indicate volume to all other effects in chain.
9215 // Pass altered volume to effects before volume controller
9216 // and requested volume to effects after controller
9217 uint32_t lVol = newLeft;
9218 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009219
Mathias Agopian65ab4712010-07-14 17:59:35 -07009220 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009221 if ((int)i == ctrlIdx) continue;
9222 // this also works for ctrlIdx == -1 when there is no volume controller
9223 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224 lVol = *left;
9225 rVol = *right;
9226 }
9227 mEffects[i]->setVolume(&lVol, &rVol, false);
9228 }
9229 *left = newLeft;
9230 *right = newRight;
9231
9232 return hasControl;
9233}
9234
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9236{
9237 const size_t SIZE = 256;
9238 char buffer[SIZE];
9239 String8 result;
9240
9241 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9242 result.append(buffer);
9243
9244 bool locked = tryLock(mLock);
9245 // failed to lock - AudioFlinger is probably deadlocked
9246 if (!locked) {
9247 result.append("\tCould not lock mutex:\n");
9248 }
9249
Eric Laurentcab11242010-07-15 12:50:15 -07009250 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9251 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252 mEffects.size(),
9253 (uint32_t)mInBuffer,
9254 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255 mActiveTrackCnt);
9256 result.append(buffer);
9257 write(fd, result.string(), result.size());
9258
9259 for (size_t i = 0; i < mEffects.size(); ++i) {
9260 sp<EffectModule> effect = mEffects[i];
9261 if (effect != 0) {
9262 effect->dump(fd, args);
9263 }
9264 }
9265
9266 if (locked) {
9267 mLock.unlock();
9268 }
9269
9270 return NO_ERROR;
9271}
9272
Eric Laurent59255e42011-07-27 19:49:51 -07009273// must be called with ThreadBase::mLock held
9274void AudioFlinger::EffectChain::setEffectSuspended_l(
9275 const effect_uuid_t *type, bool suspend)
9276{
9277 sp<SuspendedEffectDesc> desc;
9278 // use effect type UUID timelow as key as there is no real risk of identical
9279 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009280 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009281 if (suspend) {
9282 if (index >= 0) {
9283 desc = mSuspendedEffects.valueAt(index);
9284 } else {
9285 desc = new SuspendedEffectDesc();
9286 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9287 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009288 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009289 }
9290 if (desc->mRefCount++ == 0) {
9291 sp<EffectModule> effect = getEffectIfEnabled(type);
9292 if (effect != 0) {
9293 desc->mEffect = effect;
9294 effect->setSuspended(true);
9295 effect->setEnabled(false);
9296 }
9297 }
9298 } else {
9299 if (index < 0) {
9300 return;
9301 }
9302 desc = mSuspendedEffects.valueAt(index);
9303 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009304 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009305 desc->mRefCount = 1;
9306 }
9307 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009308 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009309 if (desc->mEffect != 0) {
9310 sp<EffectModule> effect = desc->mEffect.promote();
9311 if (effect != 0) {
9312 effect->setSuspended(false);
9313 sp<EffectHandle> handle = effect->controlHandle();
9314 if (handle != 0) {
9315 effect->setEnabled(handle->enabled());
9316 }
9317 }
9318 desc->mEffect.clear();
9319 }
9320 mSuspendedEffects.removeItemsAt(index);
9321 }
9322 }
9323}
9324
9325// must be called with ThreadBase::mLock held
9326void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9327{
9328 sp<SuspendedEffectDesc> desc;
9329
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009330 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009331 if (suspend) {
9332 if (index >= 0) {
9333 desc = mSuspendedEffects.valueAt(index);
9334 } else {
9335 desc = new SuspendedEffectDesc();
9336 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009337 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009338 }
9339 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009340 Vector< sp<EffectModule> > effects;
9341 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009342 for (size_t i = 0; i < effects.size(); i++) {
9343 setEffectSuspended_l(&effects[i]->desc().type, true);
9344 }
9345 }
9346 } else {
9347 if (index < 0) {
9348 return;
9349 }
9350 desc = mSuspendedEffects.valueAt(index);
9351 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009352 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009353 desc->mRefCount = 1;
9354 }
9355 if (--desc->mRefCount == 0) {
9356 Vector<const effect_uuid_t *> types;
9357 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9358 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9359 continue;
9360 }
9361 types.add(&mSuspendedEffects.valueAt(i)->mType);
9362 }
9363 for (size_t i = 0; i < types.size(); i++) {
9364 setEffectSuspended_l(types[i], false);
9365 }
Steve Block3856b092011-10-20 11:56:00 +01009366 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009367 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9368 }
9369 }
9370}
9371
Eric Laurent6bffdb82011-09-23 08:40:41 -07009372
9373// The volume effect is used for automated tests only
9374#ifndef OPENSL_ES_H_
9375static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9376 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9377const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9378#endif //OPENSL_ES_H_
9379
Eric Laurentdb7c0792011-08-10 10:37:50 -07009380bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9381{
9382 // auxiliary effects and visualizer are never suspended on output mix
9383 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9384 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009385 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9386 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009387 return false;
9388 }
9389 return true;
9390}
9391
Glenn Kastend0539712012-01-30 12:56:03 -08009392void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009393{
Glenn Kastend0539712012-01-30 12:56:03 -08009394 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009395 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009396 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9397 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009398 }
Eric Laurent59255e42011-07-27 19:49:51 -07009399 }
Eric Laurent59255e42011-07-27 19:49:51 -07009400}
9401
9402sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9403 const effect_uuid_t *type)
9404{
Glenn Kasten090f0192012-01-30 13:00:02 -08009405 sp<EffectModule> effect = getEffectFromType_l(type);
9406 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009407}
9408
9409void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9410 bool enabled)
9411{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009412 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009413 if (enabled) {
9414 if (index < 0) {
9415 // if the effect is not suspend check if all effects are suspended
9416 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9417 if (index < 0) {
9418 return;
9419 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009420 if (!isEffectEligibleForSuspend(effect->desc())) {
9421 return;
9422 }
Eric Laurent59255e42011-07-27 19:49:51 -07009423 setEffectSuspended_l(&effect->desc().type, enabled);
9424 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009425 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009426 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009427 return;
9428 }
Eric Laurent59255e42011-07-27 19:49:51 -07009429 }
Steve Block3856b092011-10-20 11:56:00 +01009430 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009431 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009432 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9433 // if effect is requested to suspended but was not yet enabled, supend it now.
9434 if (desc->mEffect == 0) {
9435 desc->mEffect = effect;
9436 effect->setEnabled(false);
9437 effect->setSuspended(true);
9438 }
9439 } else {
9440 if (index < 0) {
9441 return;
9442 }
Steve Block3856b092011-10-20 11:56:00 +01009443 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009444 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009445 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9446 desc->mEffect.clear();
9447 effect->setSuspended(false);
9448 }
9449}
9450
Mathias Agopian65ab4712010-07-14 17:59:35 -07009451#undef LOG_TAG
9452#define LOG_TAG "AudioFlinger"
9453
9454// ----------------------------------------------------------------------------
9455
9456status_t AudioFlinger::onTransact(
9457 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9458{
9459 return BnAudioFlinger::onTransact(code, data, reply, flags);
9460}
9461
Mathias Agopian65ab4712010-07-14 17:59:35 -07009462}; // namespace android