blob: 385e0b98fa50e6d1b9cc80576aab948da394027c [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <utils/String16.h>
35#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070036#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037
Dima Zavinfce7a472011-04-19 22:30:36 -070038#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <cutils/properties.h>
40
Dima Zavin64760242011-05-11 14:15:23 -070041#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070042#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
44#include "AudioMixer.h"
45#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080046#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Andy Hung6770c6f2015-04-07 13:43:36 -070048#include <media/AudioResamplerPublic.h>
49
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070051#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070052#include <audio_effects/effect_ns.h>
53#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054
Glenn Kasten3b21c502011-12-15 09:52:39 -080055#include <audio_utils/primitives.h>
56
Eric Laurentfeb0db62011-07-22 09:04:31 -070057#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080058
John Grossman4ff14ba2012-02-08 16:37:41 -080059#include <common_time/cc_helper.h>
Glenn Kasten58912562012-04-03 10:45:00 -070060
Glenn Kasten9e58b552013-01-18 15:09:48 -080061#include <media/IMediaLogService.h>
62
Glenn Kastenda6ef132013-01-10 12:31:01 -080063#include <media/nbaio/Pipe.h>
64#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070065#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080066#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070067#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080068
Mathias Agopian65ab4712010-07-14 17:59:35 -070069// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
John Grossman1c345192012-03-27 14:00:17 -070071// Note: the following macro is used for extremely verbose logging message. In
72// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
73// 0; but one side effect of this is to turn all LOGV's as well. Some messages
74// are so verbose that we want to suppress them even when we have ALOG_ASSERT
75// turned on. Do not uncomment the #def below unless you really know what you
76// are doing and want to see all of the extremely verbose messages.
77//#define VERY_VERY_VERBOSE_LOGGING
78#ifdef VERY_VERY_VERBOSE_LOGGING
79#define ALOGVV ALOGV
80#else
81#define ALOGVV(a...) do { } while(0)
82#endif
Eric Laurentde070132010-07-13 04:45:46 -070083
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Glenn Kastenec1d6b52011-12-12 09:04:45 -080086static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
87static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070088static const char kClientLockedString[] = "Client lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Glenn Kasten58912562012-04-03 10:45:00 -070090
John Grossman4ff14ba2012-02-08 16:37:41 -080091nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080092
Eric Laurent81784c32012-11-19 14:55:58 -080093uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070094
Glenn Kasten46909e72013-02-26 09:20:22 -080095#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -080096bool AudioFlinger::mTeeSinkInputEnabled = false;
97bool AudioFlinger::mTeeSinkOutputEnabled = false;
98bool AudioFlinger::mTeeSinkTrackEnabled = false;
99
100size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
101size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
102size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800103#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800104
Eric Laurent813e2a72013-08-31 12:59:48 -0700105// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
106// we define a minimum time during which a global effect is considered enabled.
107static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109// ----------------------------------------------------------------------------
110
Marco Nelissenb2208842014-02-07 14:00:50 -0800111const char *formatToString(audio_format_t format) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530112 switch (format & AUDIO_FORMAT_MAIN_MASK) {
113 case AUDIO_FORMAT_PCM:
114 switch (format) {
115 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
116 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
117 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
118 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
119 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
120 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
121 default:
122 break;
123 }
124 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800125 case AUDIO_FORMAT_MP3: return "mp3";
126 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
127 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
128 case AUDIO_FORMAT_AAC: return "aac";
129 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
130 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
131 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530132 case AUDIO_FORMAT_OPUS: return "opus";
133 case AUDIO_FORMAT_AC3: return "ac-3";
134 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Marco Nelissenb2208842014-02-07 14:00:50 -0800135 default:
136 break;
137 }
138 return "unknown";
139}
140
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700141static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700142{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700143 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700144 int rc;
145
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700146 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
147 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
148 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
149 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700150 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700151 }
152 rc = audio_hw_device_open(mod, dev);
153 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
154 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
155 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700156 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700157 }
Eric Laurent5806b352014-05-22 12:23:26 -0700158 if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700159 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
160 rc = BAD_VALUE;
161 goto out;
162 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700163 return 0;
164
165out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 *dev = NULL;
167 return rc;
168}
169
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170// ----------------------------------------------------------------------------
171
172AudioFlinger::AudioFlinger()
173 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800174 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800175 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700176 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mMasterMute(false),
179 mNextUniqueId(1),
180 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700181 mBtNrecIsOff(false),
182 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700183 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700184 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700185 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700186{
Glenn Kasten949a9262013-04-16 12:35:20 -0700187 getpid_cached = getpid();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800188 char value[PROPERTY_VALUE_MAX];
189 bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
190 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800191 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
192 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800193 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700194
Wei Jia3f273d12015-11-24 09:06:49 -0800195 // reset battery stats.
196 // if the audio service has crashed, battery stats could be left
197 // in bad state, reset the state upon service start.
198 BatteryNotifier::getInstance().noteResetAudio();
199
Glenn Kasten46909e72013-02-26 09:20:22 -0800200#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 (void) property_get("ro.debuggable", value, "0");
202 int debuggable = atoi(value);
203 int teeEnabled = 0;
204 if (debuggable) {
205 (void) property_get("af.tee", value, "0");
206 teeEnabled = atoi(value);
207 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800208 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700209 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800210 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700211 }
212 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800213 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700214 }
215 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800216 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700217 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700219}
220
221void AudioFlinger::onFirstRef()
222{
Dima Zavin799a70e2011-04-18 16:57:27 -0700223 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700224
Eric Laurent93575202011-01-18 18:39:02 -0800225 Mutex::Autolock _l(mLock);
226
Dima Zavin799a70e2011-04-18 16:57:27 -0700227 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 char val_str[PROPERTY_VALUE_MAX] = { 0 };
229 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
230 uint32_t int_val;
231 if (1 == sscanf(val_str, "%u", &int_val)) {
232 mStandbyTimeInNsecs = milliseconds(int_val);
233 ALOGI("Using %u mSec as standby time.", int_val);
234 } else {
235 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
236 ALOGI("Using default %u mSec as standby time.",
237 (uint32_t)(mStandbyTimeInNsecs / 1000000));
238 }
239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240
Eric Laurent1c333e22014-05-20 10:48:17 -0700241 mPatchPanel = new PatchPanel(this);
242
Eric Laurenta4c5a552012-03-29 10:12:40 -0700243 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244}
245
246AudioFlinger::~AudioFlinger()
247{
248 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700249 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700250 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251 }
252 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700253 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700254 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700256
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800257 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
258 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700259 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
260 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700262
263 // Tell media.log service about any old writers that still need to be unregistered
264 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
265 if (binder != 0) {
266 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
267 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
268 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
269 mUnregisteredWriters.pop();
270 mediaLogService->unregisterWriter(iMemory);
271 }
272 }
273
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274}
275
Eric Laurenta4c5a552012-03-29 10:12:40 -0700276static const char * const audio_interfaces[] = {
277 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278 AUDIO_HARDWARE_MODULE_ID_A2DP,
279 AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
Phil Burk062e67a2015-02-11 13:40:50 -0800283AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700284 audio_module_handle_t module,
285 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700286{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700287 // if module is 0, the request comes from an old policy manager and we should load
288 // well known modules
289 if (module == 0) {
290 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292 loadHwModule_l(audio_interfaces[i]);
293 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700294 // then try to find a module supporting the requested device.
295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
297 audio_hw_device_t *dev = audioHwDevice->hwDevice();
298 if ((dev->get_supported_devices != NULL) &&
299 (dev->get_supported_devices(dev) & devices) == devices)
300 return audioHwDevice;
301 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700302 } else {
303 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700304 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
305 if (audioHwDevice != NULL) {
306 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700307 }
308 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700309
Dima Zavin799a70e2011-04-18 16:57:27 -0700310 return NULL;
311}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312
Glenn Kasten0f11b512014-01-31 16:18:54 -0800313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314{
315 const size_t SIZE = 256;
316 char buffer[SIZE];
317 String8 result;
318
319 result.append("Clients:\n");
320 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800321 sp<Client> client = mClients.valueAt(i).promote();
322 if (client != 0) {
323 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
324 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 }
326 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327
Eric Laurentd1b28d42013-09-18 18:47:13 -0700328 result.append("Notification Clients:\n");
329 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
330 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
331 result.append(buffer);
332 }
333
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700334 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800335 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700336 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
337 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800338 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700339 result.append(buffer);
340 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700341 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342}
343
344
Glenn Kasten0f11b512014-01-31 16:18:54 -0800345void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700346{
347 const size_t SIZE = 256;
348 char buffer[SIZE];
349 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800350 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351
John Grossman4ff14ba2012-02-08 16:37:41 -0800352 snprintf(buffer, SIZE, "Hardware status: %d\n"
353 "Standby Time mSec: %u\n",
354 hardwareStatus,
355 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700356 result.append(buffer);
357 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700358}
359
Glenn Kasten0f11b512014-01-31 16:18:54 -0800360void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361{
362 const size_t SIZE = 256;
363 char buffer[SIZE];
364 String8 result;
365 snprintf(buffer, SIZE, "Permission Denial: "
366 "can't dump AudioFlinger from pid=%d, uid=%d\n",
367 IPCThreadState::self()->getCallingPid(),
368 IPCThreadState::self()->getCallingUid());
369 result.append(buffer);
370 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371}
372
Eric Laurent81784c32012-11-19 14:55:58 -0800373bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700374{
375 bool locked = false;
376 for (int i = 0; i < kDumpLockRetries; ++i) {
377 if (mutex.tryLock() == NO_ERROR) {
378 locked = true;
379 break;
380 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800381 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 }
383 return locked;
384}
385
386status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
387{
Glenn Kasten44deb052012-02-05 18:09:08 -0800388 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700389 dumpPermissionDenial(fd, args);
390 } else {
391 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800392 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393 if (!hardwareLocked) {
394 String8 result(kHardwareLockedString);
395 write(fd, result.string(), result.size());
396 } else {
397 mHardwareLock.unlock();
398 }
399
Eric Laurent81784c32012-11-19 14:55:58 -0800400 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401
402 // failed to lock - AudioFlinger is probably deadlocked
403 if (!locked) {
404 String8 result(kDeadlockedString);
405 write(fd, result.string(), result.size());
406 }
407
Eric Laurent021cf962014-05-13 10:18:14 -0700408 bool clientLocked = dumpTryLock(mClientLock);
409 if (!clientLocked) {
410 String8 result(kClientLockedString);
411 write(fd, result.string(), result.size());
412 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700413
414 EffectDumpEffects(fd);
415
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700417 if (clientLocked) {
418 mClientLock.unlock();
419 }
420
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 dumpInternals(fd, args);
422
423 // dump playback threads
424 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
425 mPlaybackThreads.valueAt(i)->dump(fd, args);
426 }
427
428 // dump record threads
429 for (size_t i = 0; i < mRecordThreads.size(); i++) {
430 mRecordThreads.valueAt(i)->dump(fd, args);
431 }
432
Eric Laurentaaa44472014-09-12 17:41:50 -0700433 // dump orphan effect chains
434 if (mOrphanEffectChains.size() != 0) {
435 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
436 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
437 mOrphanEffectChains.valueAt(i)->dump(fd, args);
438 }
439 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700440 // dump all hardware devs
441 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700442 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700443 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700445
Glenn Kasten46909e72013-02-26 09:20:22 -0800446#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700447 // dump the serially shared record tee sink
448 if (mRecordTeeSource != 0) {
449 dumpTee(fd, mRecordTeeSource);
450 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800451#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700452
Glenn Kastend65d73c2012-06-22 17:21:07 -0700453 if (locked) {
454 mLock.unlock();
455 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800456
457 // append a copy of media.log here by forwarding fd to it, but don't attempt
458 // to lookup the service if it's not running, as it will block for a second
459 if (mLogMemoryDealer != 0) {
460 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
461 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700462 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800463 Vector<String16> args;
464 binder->dump(fd, args);
465 }
466 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 }
468 return NO_ERROR;
469}
470
Eric Laurent021cf962014-05-13 10:18:14 -0700471sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800472{
Eric Laurent021cf962014-05-13 10:18:14 -0700473 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800474 // If pid is already in the mClients wp<> map, then use that entry
475 // (for which promote() is always != 0), otherwise create a new entry and Client.
476 sp<Client> client = mClients.valueFor(pid).promote();
477 if (client == 0) {
478 client = new Client(this, pid);
479 mClients.add(pid, client);
480 }
481
482 return client;
483}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484
Glenn Kasten9e58b552013-01-18 15:09:48 -0800485sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
486{
Glenn Kasten481fb672013-09-30 14:39:28 -0700487 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800488 if (mLogMemoryDealer == 0) {
489 return new NBLog::Writer();
490 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800491 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700492 // Similarly if we can't contact the media.log service, also return a dummy writer
493 if (binder == 0) {
494 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800495 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700496 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
497 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
498 // If allocation fails, consult the vector of previously unregistered writers
499 // and garbage-collect one or more them until an allocation succeeds
500 if (shared == 0) {
501 Mutex::Autolock _l(mUnregisteredWritersLock);
502 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
503 {
504 // Pick the oldest stale writer to garbage-collect
505 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
506 mUnregisteredWriters.removeAt(0);
507 mediaLogService->unregisterWriter(iMemory);
508 // Now the media.log remote reference to IMemory is gone. When our last local
509 // reference to IMemory also drops to zero at end of this block,
510 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
511 }
512 // Re-attempt the allocation
513 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
514 if (shared != 0) {
515 goto success;
516 }
517 }
518 // Even after garbage-collecting all old writers, there is still not enough memory,
519 // so return a dummy writer
520 return new NBLog::Writer();
521 }
522success:
523 mediaLogService->registerWriter(shared, size, name);
524 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800525}
526
527void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
528{
Glenn Kasten685ef092013-02-04 08:15:34 -0800529 if (writer == 0) {
530 return;
531 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800532 sp<IMemory> iMemory(writer->getIMemory());
533 if (iMemory == 0) {
534 return;
535 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700536 // Rather than removing the writer immediately, append it to a queue of old writers to
537 // be garbage-collected later. This allows us to continue to view old logs for a while.
538 Mutex::Autolock _l(mUnregisteredWritersLock);
539 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800540}
541
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542// IAudioFlinger interface
543
544
545sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800546 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800548 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700549 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800550 size_t *frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800551 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800553 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800554 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 int *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800556 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 status_t *status)
558{
559 sp<PlaybackThread::Track> track;
560 sp<TrackHandle> trackHandle;
561 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 status_t lStatus;
563 int lSessionId;
564
Glenn Kasten263709e2012-01-06 08:40:01 -0800565 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
566 // but if someone uses binder directly they could bypass that and cause us to crash
567 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000568 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569 lStatus = BAD_VALUE;
570 goto Exit;
571 }
572
Glenn Kasten53b5d092014-02-05 10:00:23 -0800573 // further sample rate checks are performed by createTrack_l() depending on the thread type
574 if (sampleRate == 0) {
575 ALOGE("createTrack() invalid sample rate %u", sampleRate);
576 lStatus = BAD_VALUE;
577 goto Exit;
578 }
579
580 // further channel mask checks are performed by createTrack_l() depending on the thread type
581 if (!audio_is_output_channel(channelMask)) {
582 ALOGE("createTrack() invalid channel mask %#x", channelMask);
583 lStatus = BAD_VALUE;
584 goto Exit;
585 }
586
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700587 // further format checks are performed by createTrack_l() depending on the thread type
588 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800589 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700590 lStatus = BAD_VALUE;
591 goto Exit;
592 }
593
Glenn Kasten663c2242013-09-24 11:52:37 -0700594 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
595 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
596 lStatus = BAD_VALUE;
597 goto Exit;
598 }
599
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 {
601 Mutex::Autolock _l(mLock);
602 PlaybackThread *thread = checkPlaybackThread_l(output);
603 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800604 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 lStatus = BAD_VALUE;
606 goto Exit;
607 }
608
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800609 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -0700610 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611
Glenn Kastene848bd92014-03-13 15:00:32 -0700612 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700613 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700614 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700615 // check if an effect chain with the same session ID is present on another
616 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700617 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700618 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
619 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700620 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700621 if (sessions & PlaybackThread::EFFECT_SESSION) {
622 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700623 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700624 }
Eric Laurentde070132010-07-13 04:45:46 -0700625 }
626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700628 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700629 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630 if (sessionId != NULL) {
631 *sessionId = lSessionId;
632 }
633 }
Steve Block3856b092011-10-20 11:56:00 +0100634 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635
636 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800637 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800638 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700639 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700640
641 // move effect chain to this output thread if an effect on same session was waiting
642 // for a track to be created
643 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700644 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700645 Mutex::Autolock _dl(thread->mLock);
646 Mutex::Autolock _sl(effectThread->mLock);
647 moveEffectChain_l(lSessionId, effectThread, thread, true);
648 }
Eric Laurenta011e352012-03-29 15:51:43 -0700649
650 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700651 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700652 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
653 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700654 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700655 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700656 } else {
657 mPendingSyncEvents[i]->cancel();
658 }
Eric Laurenta011e352012-03-29 15:51:43 -0700659 mPendingSyncEvents.removeAt(i);
660 i--;
661 }
662 }
663 }
Glenn Kastene198c362013-08-13 09:13:36 -0700664
Eric Laurentfa90e842014-10-17 18:12:31 -0700665 setAudioHwSyncForSession_l(thread, (audio_session_t)lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 }
Glenn Kastene198c362013-08-13 09:13:36 -0700667
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700668 if (lStatus != NO_ERROR) {
669 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700670 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700671 // Don't hold mClientLock when releasing the reference on the track as the
672 // destructor will acquire it.
673 {
674 Mutex::Autolock _cl(mClientLock);
675 client.clear();
676 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700678 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 }
680
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700681 // return handle to client
682 trackHandle = new TrackHandle(track);
683
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700685 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 return trackHandle;
687}
688
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800689uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690{
691 Mutex::Autolock _l(mLock);
692 PlaybackThread *thread = checkPlaybackThread_l(output);
693 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000694 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695 return 0;
696 }
697 return thread->sampleRate();
698}
699
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800700audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701{
702 Mutex::Autolock _l(mLock);
703 PlaybackThread *thread = checkPlaybackThread_l(output);
704 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000705 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800706 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 }
708 return thread->format();
709}
710
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800711size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712{
713 Mutex::Autolock _l(mLock);
714 PlaybackThread *thread = checkPlaybackThread_l(output);
715 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000716 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 return 0;
718 }
Glenn Kasten58912562012-04-03 10:45:00 -0700719 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
720 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 return thread->frameCount();
722}
723
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800724uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725{
726 Mutex::Autolock _l(mLock);
727 PlaybackThread *thread = checkPlaybackThread_l(output);
728 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800729 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 return 0;
731 }
732 return thread->latency();
733}
734
735status_t AudioFlinger::setMasterVolume(float value)
736{
Eric Laurenta1884f92011-08-23 08:25:03 -0700737 status_t ret = initCheck();
738 if (ret != NO_ERROR) {
739 return ret;
740 }
741
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742 // check calling permissions
743 if (!settingsAllowed()) {
744 return PERMISSION_DENIED;
745 }
746
Eric Laurenta4c5a552012-03-29 10:12:40 -0700747 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700748 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700749
John Grossmanee578c02012-07-23 17:05:46 -0700750 // Set master volume in the HALs which support it.
751 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
752 AutoMutex lock(mHardwareLock);
753 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800754
John Grossmanee578c02012-07-23 17:05:46 -0700755 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
756 if (dev->canSetMasterVolume()) {
757 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800758 }
John Grossmanee578c02012-07-23 17:05:46 -0700759 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700761
John Grossmanee578c02012-07-23 17:05:46 -0700762 // Now set the master volume in each playback thread. Playback threads
763 // assigned to HALs which do not have master volume support will apply
764 // master volume during the mix operation. Threads with HALs which do
765 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700766 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
767 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
768 continue;
769 }
John Grossmanee578c02012-07-23 17:05:46 -0700770 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772
773 return NO_ERROR;
774}
775
Glenn Kastenf78aee72012-01-04 11:00:47 -0800776status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777{
Eric Laurenta1884f92011-08-23 08:25:03 -0700778 status_t ret = initCheck();
779 if (ret != NO_ERROR) {
780 return ret;
781 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782
783 // check calling permissions
784 if (!settingsAllowed()) {
785 return PERMISSION_DENIED;
786 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800787 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000788 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789 return BAD_VALUE;
790 }
791
792 { // scope for the lock
793 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700794 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700796 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 mHardwareStatus = AUDIO_HW_IDLE;
798 }
799
800 if (NO_ERROR == ret) {
801 Mutex::Autolock _l(mLock);
802 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800803 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700804 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 }
806
807 return ret;
808}
809
810status_t AudioFlinger::setMicMute(bool state)
811{
Eric Laurenta1884f92011-08-23 08:25:03 -0700812 status_t ret = initCheck();
813 if (ret != NO_ERROR) {
814 return ret;
815 }
816
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 // check calling permissions
818 if (!settingsAllowed()) {
819 return PERMISSION_DENIED;
820 }
821
822 AutoMutex lock(mHardwareLock);
823 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700824 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
825 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
826 status_t result = dev->set_mic_mute(dev, state);
827 if (result != NO_ERROR) {
828 ret = result;
829 }
830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831 mHardwareStatus = AUDIO_HW_IDLE;
832 return ret;
833}
834
835bool AudioFlinger::getMicMute() const
836{
Eric Laurenta1884f92011-08-23 08:25:03 -0700837 status_t ret = initCheck();
838 if (ret != NO_ERROR) {
839 return false;
840 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800841 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700842 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800843 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800845 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
846 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
847 status_t result = dev->get_mic_mute(dev, &state);
848 if (result == NO_ERROR) {
849 mute = mute && state;
850 }
851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800853
854 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855}
856
857status_t AudioFlinger::setMasterMute(bool muted)
858{
John Grossmand8f178d2012-07-20 14:51:35 -0700859 status_t ret = initCheck();
860 if (ret != NO_ERROR) {
861 return ret;
862 }
863
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 // check calling permissions
865 if (!settingsAllowed()) {
866 return PERMISSION_DENIED;
867 }
868
John Grossmanee578c02012-07-23 17:05:46 -0700869 Mutex::Autolock _l(mLock);
870 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700871
John Grossmanee578c02012-07-23 17:05:46 -0700872 // Set master mute in the HALs which support it.
873 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
874 AutoMutex lock(mHardwareLock);
875 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700876
John Grossmanee578c02012-07-23 17:05:46 -0700877 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
878 if (dev->canSetMasterMute()) {
879 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700880 }
John Grossmanee578c02012-07-23 17:05:46 -0700881 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700882 }
883
John Grossmanee578c02012-07-23 17:05:46 -0700884 // Now set the master mute in each playback thread. Playback threads
885 // assigned to HALs which do not have master mute support will apply master
886 // mute during the mix operation. Threads with HALs which do support master
887 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700888 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
889 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
890 continue;
891 }
John Grossmanee578c02012-07-23 17:05:46 -0700892 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894
895 return NO_ERROR;
896}
897
898float AudioFlinger::masterVolume() const
899{
Glenn Kasten98067102011-12-13 11:47:54 -0800900 Mutex::Autolock _l(mLock);
901 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902}
903
904bool AudioFlinger::masterMute() const
905{
Glenn Kasten98067102011-12-13 11:47:54 -0800906 Mutex::Autolock _l(mLock);
907 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908}
909
John Grossman4ff14ba2012-02-08 16:37:41 -0800910float AudioFlinger::masterVolume_l() const
911{
John Grossman4ff14ba2012-02-08 16:37:41 -0800912 return mMasterVolume;
913}
914
John Grossmand8f178d2012-07-20 14:51:35 -0700915bool AudioFlinger::masterMute_l() const
916{
John Grossmanee578c02012-07-23 17:05:46 -0700917 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700918}
919
Eric Laurent223fd5c2014-11-11 13:43:36 -0800920status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
921{
922 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
923 ALOGW("setStreamVolume() invalid stream %d", stream);
924 return BAD_VALUE;
925 }
926 pid_t caller = IPCThreadState::self()->getCallingPid();
927 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
928 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
929 return PERMISSION_DENIED;
930 }
931
932 return NO_ERROR;
933}
934
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800935status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
936 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937{
938 // check calling permissions
939 if (!settingsAllowed()) {
940 return PERMISSION_DENIED;
941 }
942
Eric Laurent223fd5c2014-11-11 13:43:36 -0800943 status_t status = checkStreamType(stream);
944 if (status != NO_ERROR) {
945 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800947 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948
949 AutoMutex lock(mLock);
950 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700951 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952 thread = checkPlaybackThread_l(output);
953 if (thread == NULL) {
954 return BAD_VALUE;
955 }
956 }
957
958 mStreamTypes[stream].volume = value;
959
960 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800961 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700962 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 }
964 } else {
965 thread->setStreamVolume(stream, value);
966 }
967
968 return NO_ERROR;
969}
970
Glenn Kastenfff6d712012-01-12 16:38:12 -0800971status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972{
973 // check calling permissions
974 if (!settingsAllowed()) {
975 return PERMISSION_DENIED;
976 }
977
Eric Laurent223fd5c2014-11-11 13:43:36 -0800978 status_t status = checkStreamType(stream);
979 if (status != NO_ERROR) {
980 return status;
981 }
982 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
983
984 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000985 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986 return BAD_VALUE;
987 }
988
Eric Laurent93575202011-01-18 18:39:02 -0800989 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700991 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700992 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993
994 return NO_ERROR;
995}
996
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800997float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998{
Eric Laurent223fd5c2014-11-11 13:43:36 -0800999 status_t status = checkStreamType(stream);
1000 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 return 0.0f;
1002 }
1003
1004 AutoMutex lock(mLock);
1005 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001006 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 PlaybackThread *thread = checkPlaybackThread_l(output);
1008 if (thread == NULL) {
1009 return 0.0f;
1010 }
1011 volume = thread->streamVolume(stream);
1012 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001013 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014 }
1015
1016 return volume;
1017}
1018
Glenn Kastenfff6d712012-01-12 16:38:12 -08001019bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001021 status_t status = checkStreamType(stream);
1022 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 return true;
1024 }
1025
Glenn Kasten6637baa2012-01-09 09:40:36 -08001026 AutoMutex lock(mLock);
1027 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028}
1029
Eric Laurent054d9d32015-04-24 08:48:48 -07001030
1031void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1032{
1033 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1034 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1035 }
1036}
1037
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001038status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001040 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1041 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001042
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 // check calling permissions
1044 if (!settingsAllowed()) {
1045 return PERMISSION_DENIED;
1046 }
1047
Glenn Kasten142f5192014-03-25 17:44:59 -07001048 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1049 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001050 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001051 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001052 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001053 AutoMutex lock(mHardwareLock);
1054 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1055 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1056 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1057 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1058 final_result = result ?: final_result;
1059 }
1060 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001061 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001062 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1063 AudioParameter param = AudioParameter(keyValuePairs);
1064 String8 value;
1065 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001066 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1067 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001068 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1069 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001070 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001071 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1072 // collect all of the thread's session IDs
1073 KeyedVector<int, bool> ids = thread->sessionIds();
1074 // suspend effects associated with those session IDs
1075 for (size_t j = 0; j < ids.size(); ++j) {
1076 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001077 thread->setEffectSuspended(FX_IID_AEC,
1078 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001079 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001080 thread->setEffectSuspended(FX_IID_NS,
1081 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001082 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001083 }
1084 }
Eric Laurentbee53372011-08-29 12:42:48 -07001085 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001086 }
1087 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001088 String8 screenState;
1089 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1090 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001091 if (isOff != (AudioFlinger::mScreenState & 1)) {
1092 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001093 }
1094 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001095 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 }
1097
1098 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1099 // and the thread is exited once the lock is released
1100 sp<ThreadBase> thread;
1101 {
1102 Mutex::Autolock _l(mLock);
1103 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001104 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001106 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001107 // indicate output device change to all input threads for pre processing
1108 AudioParameter param = AudioParameter(keyValuePairs);
1109 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001110 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1111 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001112 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 }
1115 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001116 if (thread != 0) {
1117 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118 }
1119 return BAD_VALUE;
1120}
1121
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001122String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001124 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1125 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126
Eric Laurenta4c5a552012-03-29 10:12:40 -07001127 Mutex::Autolock _l(mLock);
1128
Glenn Kasten142f5192014-03-25 17:44:59 -07001129 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001130 String8 out_s8;
1131
Dima Zavin799a70e2011-04-18 16:57:27 -07001132 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001133 char *s;
1134 {
1135 AutoMutex lock(mHardwareLock);
1136 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001137 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001138 s = dev->get_parameters(dev, keys.string());
1139 mHardwareStatus = AUDIO_HW_IDLE;
1140 }
John Grossmanef7740b2012-02-09 11:28:36 -08001141 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001142 free(s);
1143 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001144 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 }
1146
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1148 if (playbackThread != NULL) {
1149 return playbackThread->getParameters(keys);
1150 }
1151 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1152 if (recordThread != NULL) {
1153 return recordThread->getParameters(keys);
1154 }
1155 return String8("");
1156}
1157
Glenn Kastendd8104c2012-07-02 12:42:44 -07001158size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1159 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160{
Eric Laurenta1884f92011-08-23 08:25:03 -07001161 status_t ret = initCheck();
1162 if (ret != NO_ERROR) {
1163 return 0;
1164 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001165 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
1166 return 0;
1167 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001168
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001169 AutoMutex lock(mHardwareLock);
1170 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001171 audio_config_t config, proposed;
1172 memset(&proposed, 0, sizeof(proposed));
1173 proposed.sample_rate = sampleRate;
1174 proposed.channel_mask = channelMask;
1175 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001176
John Grossmanee578c02012-07-23 17:05:46 -07001177 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001178 size_t frames;
1179 for (;;) {
1180 // Note: config is currently a const parameter for get_input_buffer_size()
1181 // but we use a copy from proposed in case config changes from the call.
1182 config = proposed;
1183 frames = dev->get_input_buffer_size(dev, &config);
1184 if (frames != 0) {
1185 break; // hal success, config is the result
1186 }
1187 // change one parameter of the configuration each iteration to a more "common" value
1188 // to see if the device will support it.
1189 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1190 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1191 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1192 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1193 } else {
1194 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1195 "format %#x, channelMask 0x%X",
1196 sampleRate, format, channelMask);
1197 break; // retries failed, break out of loop with frames == 0.
1198 }
1199 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001200 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001201 if (frames > 0 && config.sample_rate != sampleRate) {
1202 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1203 }
1204 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205}
1206
Glenn Kasten5f972c02014-01-13 09:59:31 -08001207uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 Mutex::Autolock _l(mLock);
1210
1211 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1212 if (recordThread != NULL) {
1213 return recordThread->getInputFramesLost();
1214 }
1215 return 0;
1216}
1217
1218status_t AudioFlinger::setVoiceVolume(float value)
1219{
Eric Laurenta1884f92011-08-23 08:25:03 -07001220 status_t ret = initCheck();
1221 if (ret != NO_ERROR) {
1222 return ret;
1223 }
1224
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 // check calling permissions
1226 if (!settingsAllowed()) {
1227 return PERMISSION_DENIED;
1228 }
1229
1230 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001231 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001232 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001233 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 mHardwareStatus = AUDIO_HW_IDLE;
1235
1236 return ret;
1237}
1238
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001239status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001240 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241{
1242 status_t status;
1243
1244 Mutex::Autolock _l(mLock);
1245
1246 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1247 if (playbackThread != NULL) {
1248 return playbackThread->getRenderPosition(halFrames, dspFrames);
1249 }
1250
1251 return BAD_VALUE;
1252}
1253
1254void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1255{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001257 if (client == 0) {
1258 return;
1259 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001260 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001261 {
1262 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001263 if (mNotificationClients.indexOfKey(pid) < 0) {
1264 sp<NotificationClient> notificationClient = new NotificationClient(this,
1265 client,
1266 pid);
1267 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268
Eric Laurent021cf962014-05-13 10:18:14 -07001269 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270
Marco Nelissen06b46062014-11-14 07:58:25 -08001271 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001272 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001273 }
1274 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275
Eric Laurent021cf962014-05-13 10:18:14 -07001276 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001277 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001278 // the config change is always sent from playback or record threads to avoid deadlock
1279 // with AudioSystem::gLock
1280 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1281 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001284 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1285 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 }
1287}
1288
1289void AudioFlinger::removeNotificationClient(pid_t pid)
1290{
1291 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001292 {
1293 Mutex::Autolock _cl(mClientLock);
1294 mNotificationClients.removeItem(pid);
1295 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001296
Steve Block3856b092011-10-20 11:56:00 +01001297 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001298 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001299 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001300 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001301 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001302 ALOGV(" pid %d @ %d", ref->mPid, i);
1303 if (ref->mPid == pid) {
1304 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001305 mAudioSessionRefs.removeAt(i);
1306 delete ref;
1307 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001308 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001309 } else {
1310 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001311 }
1312 }
1313 if (removed) {
1314 purgeStaleEffects_l();
1315 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001316}
1317
Eric Laurent73e26b62015-04-27 16:55:58 -07001318void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001319 const sp<AudioIoDescriptor>& ioDesc,
1320 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001321{
Eric Laurent021cf962014-05-13 10:18:14 -07001322 Mutex::Autolock _l(mClientLock);
1323 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001324 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001325 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1326 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328 }
1329}
1330
Eric Laurent021cf962014-05-13 10:18:14 -07001331// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001332void AudioFlinger::removeClient_l(pid_t pid)
1333{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001334 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001335 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336 mClients.removeItem(pid);
1337}
1338
Eric Laurent717e1282012-06-29 16:36:52 -07001339// getEffectThread_l() must be called with AudioFlinger::mLock held
1340sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1341{
1342 sp<PlaybackThread> thread;
1343
1344 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1345 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1346 ALOG_ASSERT(thread == 0);
1347 thread = mPlaybackThreads.valueAt(i);
1348 }
1349 }
1350
1351 return thread;
1352}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355
1356// ----------------------------------------------------------------------------
1357
1358AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1359 : RefBase(),
1360 mAudioFlinger(audioFlinger),
John Grossman4ff14ba2012-02-08 16:37:41 -08001361 mPid(pid),
1362 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363{
Eric Laurentda73b6c2015-08-20 16:18:53 -07001364 size_t heapSize = kClientSharedHeapSizeBytes;
1365 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1366 // invalidated tracks
1367 if (!audioFlinger->isLowRamDevice()) {
1368 heapSize *= kClientSharedHeapSizeMultiplier;
1369 }
1370 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371}
1372
Eric Laurent021cf962014-05-13 10:18:14 -07001373// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374AudioFlinger::Client::~Client()
1375{
1376 mAudioFlinger->removeClient_l(mPid);
1377}
1378
Glenn Kasten435dbe62012-01-30 10:15:48 -08001379sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380{
1381 return mMemoryDealer;
1382}
1383
John Grossman4ff14ba2012-02-08 16:37:41 -08001384// Reserve one of the limited slots for a timed audio track associated
1385// with this client
1386bool AudioFlinger::Client::reserveTimedTrack()
1387{
1388 const int kMaxTimedTracksPerClient = 4;
1389
1390 Mutex::Autolock _l(mTimedTrackLock);
1391
1392 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
1393 ALOGW("can not create timed track - pid %d has exceeded the limit",
1394 mPid);
1395 return false;
1396 }
1397
1398 mTimedTrackCount++;
1399 return true;
1400}
1401
1402// Release a slot for a timed audio track
1403void AudioFlinger::Client::releaseTimedTrack()
1404{
1405 Mutex::Autolock _l(mTimedTrackLock);
1406 mTimedTrackCount--;
1407}
1408
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409// ----------------------------------------------------------------------------
1410
1411AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1412 const sp<IAudioFlingerClient>& client,
1413 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001414 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415{
1416}
1417
1418AudioFlinger::NotificationClient::~NotificationClient()
1419{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420}
1421
Glenn Kasten0f11b512014-01-31 16:18:54 -08001422void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423{
1424 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001425 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426}
1427
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428
1429// ----------------------------------------------------------------------------
1430
Jeff Brown893a5642013-08-16 20:19:26 -07001431static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) {
1432 return audio_is_remote_submix_device(inDevice);
1433}
1434
Mathias Agopian65ab4712010-07-14 17:59:35 -07001435sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001436 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001438 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001439 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001440 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001441 size_t *frameCount,
Glenn Kasteneeca3262013-07-31 16:12:48 -07001442 IAudioFlinger::track_flags_t *flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001443 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001444 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445 int *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001446 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001447 sp<IMemory>& cblk,
1448 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449 status_t *status)
1450{
1451 sp<RecordThread::RecordTrack> recordTrack;
1452 sp<RecordHandle> recordHandle;
1453 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 int lSessionId;
1456
Glenn Kastend776ac62014-05-07 09:16:09 -07001457 cblk.clear();
1458 buffers.clear();
1459
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 // check calling permissions
Svet Ganovbe71aa22015-04-28 12:06:02 -07001461 if (!recordingAllowed(opPackageName)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001462 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463 lStatus = PERMISSION_DENIED;
1464 goto Exit;
1465 }
1466
Glenn Kasten53b5d092014-02-05 10:00:23 -08001467 // further sample rate checks are performed by createRecordTrack_l()
1468 if (sampleRate == 0) {
1469 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1470 lStatus = BAD_VALUE;
1471 goto Exit;
1472 }
1473
Andy Hung6770c6f2015-04-07 13:43:36 -07001474 // we don't yet support anything other than linear PCM
1475 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001476 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001477 lStatus = BAD_VALUE;
1478 goto Exit;
1479 }
1480
Glenn Kasten53b5d092014-02-05 10:00:23 -08001481 // further channel mask checks are performed by createRecordTrack_l()
1482 if (!audio_is_input_channel(channelMask)) {
1483 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1484 lStatus = BAD_VALUE;
1485 goto Exit;
1486 }
1487
Glenn Kasten05997e22014-03-13 15:08:33 -07001488 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001490 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001492 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 lStatus = BAD_VALUE;
1494 goto Exit;
1495 }
1496
Glenn Kasten8d6cc842012-02-03 11:06:53 -08001497 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001498 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001500 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 lSessionId = *sessionId;
1502 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001503 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001504 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 if (sessionId != NULL) {
1506 *sessionId = lSessionId;
1507 }
1508 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001509 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001510
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001511 // TODO: the uid should be passed in as a parameter to openRecord
Glenn Kasten1879fff2012-07-11 15:36:59 -07001512 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001513 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001514 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001515 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001516
1517 if (lStatus == NO_ERROR) {
1518 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1519 // session and move it to this thread.
1520 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)lSessionId);
1521 if (chain != 0) {
1522 Mutex::Autolock _l(thread->mLock);
1523 thread->addEffectChain_l(chain);
1524 }
1525 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 }
Glenn Kastene198c362013-08-13 09:13:36 -07001527
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001528 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001529 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001530 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001531 // Don't hold mClientLock when releasing the reference on the track as the
1532 // destructor will acquire it.
1533 {
1534 Mutex::Autolock _cl(mClientLock);
1535 client.clear();
1536 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 goto Exit;
1539 }
1540
Glenn Kastend776ac62014-05-07 09:16:09 -07001541 cblk = recordTrack->getCblk();
1542 buffers = recordTrack->getBuffers();
1543
Glenn Kasten2fc14732013-08-05 14:58:14 -07001544 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546
1547Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001548 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 return recordHandle;
1550}
1551
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001552
1553
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554// ----------------------------------------------------------------------------
1555
Eric Laurenta4c5a552012-03-29 10:12:40 -07001556audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1557{
Eric Laurent44622db2014-08-01 19:00:33 -07001558 if (name == NULL) {
1559 return 0;
1560 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001561 if (!settingsAllowed()) {
1562 return 0;
1563 }
1564 Mutex::Autolock _l(mLock);
1565 return loadHwModule_l(name);
1566}
1567
1568// loadHwModule_l() must be called with AudioFlinger::mLock held
1569audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1570{
1571 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1572 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1573 ALOGW("loadHwModule() module %s already loaded", name);
1574 return mAudioHwDevs.keyAt(i);
1575 }
1576 }
1577
Eric Laurenta4c5a552012-03-29 10:12:40 -07001578 audio_hw_device_t *dev;
1579
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001580 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001581 if (rc) {
1582 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1583 return 0;
1584 }
1585
1586 mHardwareStatus = AUDIO_HW_INIT;
1587 rc = dev->init_check(dev);
1588 mHardwareStatus = AUDIO_HW_IDLE;
1589 if (rc) {
1590 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1591 return 0;
1592 }
1593
John Grossmanee578c02012-07-23 17:05:46 -07001594 // Check and cache this HAL's level of support for master mute and master
1595 // volume. If this is the first HAL opened, and it supports the get
1596 // methods, use the initial values provided by the HAL as the current
1597 // master mute and volume settings.
1598
1599 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1600 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001601 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001602
1603 if (0 == mAudioHwDevs.size()) {
1604 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1605 if (NULL != dev->get_master_volume) {
1606 float mv;
1607 if (OK == dev->get_master_volume(dev, &mv)) {
1608 mMasterVolume = mv;
1609 }
1610 }
1611
1612 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1613 if (NULL != dev->get_master_mute) {
1614 bool mm;
1615 if (OK == dev->get_master_mute(dev, &mm)) {
1616 mMasterMute = mm;
1617 }
1618 }
1619 }
1620
Eric Laurenta4c5a552012-03-29 10:12:40 -07001621 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001622 if ((NULL != dev->set_master_volume) &&
1623 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1624 flags = static_cast<AudioHwDevice::Flags>(flags |
1625 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1626 }
1627
1628 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1629 if ((NULL != dev->set_master_mute) &&
1630 (OK == dev->set_master_mute(dev, mMasterMute))) {
1631 flags = static_cast<AudioHwDevice::Flags>(flags |
1632 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1633 }
1634
Eric Laurenta4c5a552012-03-29 10:12:40 -07001635 mHardwareStatus = AUDIO_HW_IDLE;
1636 }
1637
1638 audio_module_handle_t handle = nextUniqueId();
Eric Laurent83b88082014-06-20 18:31:16 -07001639 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001640
1641 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001642 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001643
1644 return handle;
1645
1646}
1647
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001648// ----------------------------------------------------------------------------
1649
Glenn Kasten3b16c762012-11-14 08:44:39 -08001650uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001651{
1652 Mutex::Autolock _l(mLock);
1653 PlaybackThread *thread = primaryPlaybackThread_l();
1654 return thread != NULL ? thread->sampleRate() : 0;
1655}
1656
Glenn Kastene33054e2012-11-14 12:54:39 -08001657size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001658{
1659 Mutex::Autolock _l(mLock);
1660 PlaybackThread *thread = primaryPlaybackThread_l();
1661 return thread != NULL ? thread->frameCountHAL() : 0;
1662}
1663
1664// ----------------------------------------------------------------------------
1665
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001666status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1667{
1668 uid_t uid = IPCThreadState::self()->getCallingUid();
1669 if (uid != AID_SYSTEM) {
1670 return PERMISSION_DENIED;
1671 }
1672 Mutex::Autolock _l(mLock);
1673 if (mIsDeviceTypeKnown) {
1674 return INVALID_OPERATION;
1675 }
1676 mIsLowRamDevice = isLowRamDevice;
1677 mIsDeviceTypeKnown = true;
1678 return NO_ERROR;
1679}
1680
Eric Laurent93c3d412014-08-01 14:48:35 -07001681audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1682{
1683 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001684
1685 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1686 if (index >= 0) {
1687 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1688 mHwAvSyncIds.valueAt(index), sessionId);
1689 return mHwAvSyncIds.valueAt(index);
1690 }
1691
1692 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1693 if (dev == NULL) {
1694 return AUDIO_HW_SYNC_INVALID;
1695 }
1696 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1697 AudioParameter param = AudioParameter(String8(reply));
1698 free(reply);
1699
1700 int value;
1701 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1702 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1703 return AUDIO_HW_SYNC_INVALID;
1704 }
1705
1706 // allow only one session for a given HW A/V sync ID.
1707 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1708 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1709 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1710 value, mHwAvSyncIds.keyAt(i));
1711 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001712 break;
1713 }
1714 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001715
1716 mHwAvSyncIds.add(sessionId, value);
1717
1718 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1719 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1720 uint32_t sessions = thread->hasAudioSession(sessionId);
1721 if (sessions & PlaybackThread::TRACK_SESSION) {
1722 AudioParameter param = AudioParameter();
1723 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1724 thread->setParameters(param.toString());
1725 break;
1726 }
1727 }
1728
1729 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1730 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001731}
1732
Eric Laurent72e3f392015-05-20 14:43:50 -07001733status_t AudioFlinger::systemReady()
1734{
1735 Mutex::Autolock _l(mLock);
1736 ALOGI("%s", __FUNCTION__);
1737 if (mSystemReady) {
1738 ALOGW("%s called twice", __FUNCTION__);
1739 return NO_ERROR;
1740 }
1741 mSystemReady = true;
1742 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1743 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1744 thread->systemReady();
1745 }
1746 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1747 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1748 thread->systemReady();
1749 }
1750 return NO_ERROR;
1751}
1752
Eric Laurentfa90e842014-10-17 18:12:31 -07001753// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1754void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1755{
1756 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1757 if (index >= 0) {
1758 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1759 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1760 AudioParameter param = AudioParameter();
1761 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1762 thread->setParameters(param.toString());
1763 }
1764}
1765
1766
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001767// ----------------------------------------------------------------------------
1768
Eric Laurent83b88082014-06-20 18:31:16 -07001769
1770sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001771 audio_io_handle_t *output,
1772 audio_config_t *config,
1773 audio_devices_t devices,
1774 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001775 audio_output_flags_t flags)
1776{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001777 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001778 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001779 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001780 }
1781
1782 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001783 if (*output == AUDIO_IO_HANDLE_NONE) {
1784 *output = nextUniqueId();
1785 }
Eric Laurent83b88082014-06-20 18:31:16 -07001786
1787 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1788
Eric Laurent83b88082014-06-20 18:31:16 -07001789 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001790 // This if statement allows overriding the audio policy settings
1791 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1792 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1793 // Check only for Normal Mixing mode
1794 if (kEnableExtendedPrecision) {
1795 // Specify format (uncomment one below to choose)
1796 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1797 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1798 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1799 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001800 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001801 }
1802 if (kEnableExtendedChannels) {
1803 // Specify channel mask (uncomment one below to choose)
1804 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1805 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1806 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1807 }
Eric Laurent83b88082014-06-20 18:31:16 -07001808 }
1809
Phil Burk062e67a2015-02-11 13:40:50 -08001810 AudioStreamOut *outputStream = NULL;
1811 status_t status = outHwDev->openOutputStream(
1812 &outputStream,
1813 *output,
1814 devices,
1815 flags,
1816 config,
1817 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001818
1819 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001820
Phil Burk062e67a2015-02-11 13:40:50 -08001821 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001822
1823 PlaybackThread *thread;
1824 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001825 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001826 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001827 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1828 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001829 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001830 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001831 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001832 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001833 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001834 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001835 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001836 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001837 return thread;
1838 }
1839
1840 return 0;
1841}
1842
Eric Laurentcf2c0212014-07-25 16:20:43 -07001843status_t AudioFlinger::openOutput(audio_module_handle_t module,
1844 audio_io_handle_t *output,
1845 audio_config_t *config,
1846 audio_devices_t *devices,
1847 const String8& address,
1848 uint32_t *latencyMs,
1849 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850{
Phil Burk062e67a2015-02-11 13:40:50 -08001851 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001852 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001853 (devices != NULL) ? *devices : 0,
1854 config->sample_rate,
1855 config->format,
1856 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001857 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858
Eric Laurentcf2c0212014-07-25 16:20:43 -07001859 if (*devices == AUDIO_DEVICE_NONE) {
1860 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001862
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 Mutex::Autolock _l(mLock);
1864
Eric Laurentcf2c0212014-07-25 16:20:43 -07001865 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001866 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001867 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868
1869 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001870 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001871
1872 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001873 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001874 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001875 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001876
1877 AutoMutex lock(mHardwareLock);
1878 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001879 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001880 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001881 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001882 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 }
1884
Eric Laurentcf2c0212014-07-25 16:20:43 -07001885 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886}
1887
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001888audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1889 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890{
1891 Mutex::Autolock _l(mLock);
1892 MixerThread *thread1 = checkMixerThread_l(output1);
1893 MixerThread *thread2 = checkMixerThread_l(output2);
1894
1895 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001896 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1897 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001898 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 }
1900
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001901 audio_io_handle_t id = nextUniqueId();
Eric Laurent72e3f392015-05-20 14:43:50 -07001902 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 thread->addOutputTrack(thread2);
1904 mPlaybackThreads.add(id, thread);
1905 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001906 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 return id;
1908}
1909
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001910status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911{
Glenn Kastend96c5722012-04-25 13:44:49 -07001912 return closeOutput_nonvirtual(output);
1913}
1914
1915status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1916{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 // keep strong reference on the playback thread so that
1918 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001919 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920 {
1921 Mutex::Autolock _l(mLock);
1922 thread = checkPlaybackThread_l(output);
1923 if (thread == NULL) {
1924 return BAD_VALUE;
1925 }
1926
Steve Block3856b092011-10-20 11:56:00 +01001927 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001929 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001931 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001932 DuplicatingThread *dupThread =
1933 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001935 }
1936 }
1937 }
1938
1939
1940 mPlaybackThreads.removeItem(output);
1941 // save all effects to the default thread
1942 if (mPlaybackThreads.size()) {
1943 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1944 if (dstThread != NULL) {
1945 // audioflinger lock is held here so the acquisition order of thread locks does not
1946 // matter
1947 Mutex::Autolock _dl(dstThread->mLock);
1948 Mutex::Autolock _sl(thread->mLock);
1949 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1950 for (size_t i = 0; i < effectChains.size(); i ++) {
1951 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 }
1953 }
1954 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001955 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1956 ioDesc->mIoHandle = output;
1957 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 }
1959 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08001960 // The thread entity (active unit of execution) is no longer running here,
1961 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962
Eric Laurentf6870ae2015-05-08 10:50:03 -07001963 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07001964 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 }
Eric Laurent83b88082014-06-20 18:31:16 -07001966
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 return NO_ERROR;
1968}
1969
Eric Laurent83b88082014-06-20 18:31:16 -07001970void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
1971{
1972 AudioStreamOut *out = thread->clearOutput();
1973 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1974 // from now on thread->mOutput is NULL
1975 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1976 delete out;
1977}
1978
1979void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
1980{
1981 mPlaybackThreads.removeItem(thread->mId);
1982 thread->exit();
1983 closeOutputFinish(thread);
1984}
1985
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001986status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987{
1988 Mutex::Autolock _l(mLock);
1989 PlaybackThread *thread = checkPlaybackThread_l(output);
1990
1991 if (thread == NULL) {
1992 return BAD_VALUE;
1993 }
1994
Steve Block3856b092011-10-20 11:56:00 +01001995 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996 thread->suspend();
1997
1998 return NO_ERROR;
1999}
2000
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002001status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002{
2003 Mutex::Autolock _l(mLock);
2004 PlaybackThread *thread = checkPlaybackThread_l(output);
2005
2006 if (thread == NULL) {
2007 return BAD_VALUE;
2008 }
2009
Steve Block3856b092011-10-20 11:56:00 +01002010 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011
2012 thread->restore();
2013
2014 return NO_ERROR;
2015}
2016
Eric Laurentcf2c0212014-07-25 16:20:43 -07002017status_t AudioFlinger::openInput(audio_module_handle_t module,
2018 audio_io_handle_t *input,
2019 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002020 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002021 const String8& address,
2022 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002023 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024{
Eric Laurent83b88082014-06-20 18:31:16 -07002025 Mutex::Autolock _l(mLock);
2026
Glenn Kastene7d66712015-03-05 13:46:52 -08002027 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002028 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002029 }
2030
Glenn Kastene7d66712015-03-05 13:46:52 -08002031 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002032
2033 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002034 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002035 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002036 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002038 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002039}
Dima Zavin799a70e2011-04-18 16:57:27 -07002040
Eric Laurent83b88082014-06-20 18:31:16 -07002041sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002042 audio_io_handle_t *input,
2043 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002044 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002045 const String8& address,
2046 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002047 audio_input_flags_t flags)
2048{
Glenn Kastene7d66712015-03-05 13:46:52 -08002049 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002050 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002051 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002052 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002053 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002054
Eric Laurentcf2c0212014-07-25 16:20:43 -07002055 if (*input == AUDIO_IO_HANDLE_NONE) {
2056 *input = nextUniqueId();
2057 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002058
Eric Laurentcf2c0212014-07-25 16:20:43 -07002059 audio_config_t halconfig = *config;
2060 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002061 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002062 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002063 &inStream, flags, address.string(), source);
2064 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002065 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002066 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002067 halconfig.sample_rate,
2068 halconfig.format,
2069 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002070 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002071 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002073 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002074 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002075 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002076 audio_is_linear_pcm(config->format) &&
2077 audio_is_linear_pcm(halconfig.format) &&
2078 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
Eric Laurentcf2c0212014-07-25 16:20:43 -07002079 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_2) &&
2080 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_2)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002081 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002082 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002083 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002084 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002085 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002086 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 }
2088
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002089 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002090
Glenn Kasten46909e72013-02-26 09:20:22 -08002091#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002092 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2093 // or (re-)create if current Pipe is idle and does not match the new format
2094 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002095 enum {
2096 TEE_SINK_NO, // don't copy input
2097 TEE_SINK_NEW, // copy input using a new pipe
2098 TEE_SINK_OLD, // copy input using an existing pipe
2099 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002100 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2101 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002102 if (!mTeeSinkInputEnabled) {
2103 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002104 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002105 kind = TEE_SINK_NO;
2106 } else if (mRecordTeeSink == 0) {
2107 kind = TEE_SINK_NEW;
2108 } else if (mRecordTeeSink->getStrongCount() != 1) {
2109 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002110 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002111 kind = TEE_SINK_OLD;
2112 } else {
2113 kind = TEE_SINK_NEW;
2114 }
2115 switch (kind) {
2116 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002117 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002118 size_t numCounterOffers = 0;
2119 const NBAIO_Format offers[1] = {format};
2120 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2121 ALOG_ASSERT(index == 0);
2122 PipeReader *pipeReader = new PipeReader(*pipe);
2123 numCounterOffers = 0;
2124 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2125 ALOG_ASSERT(index == 0);
2126 mRecordTeeSink = pipe;
2127 mRecordTeeSource = pipeReader;
2128 teeSink = pipe;
2129 }
2130 break;
2131 case TEE_SINK_OLD:
2132 teeSink = mRecordTeeSink;
2133 break;
2134 case TEE_SINK_NO:
2135 default:
2136 break;
2137 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002138#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002139
Eric Laurentcf2c0212014-07-25 16:20:43 -07002140 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002141
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002142 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002143 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002144 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002145 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002146 inputStream,
2147 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002148 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002149 devices,
2150 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002151#ifdef TEE_SINK
2152 , teeSink
2153#endif
2154 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002155 mRecordThreads.add(*input, thread);
2156 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002157 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 }
2159
Eric Laurentcf2c0212014-07-25 16:20:43 -07002160 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 return 0;
2162}
2163
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002164status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165{
Glenn Kastend96c5722012-04-25 13:44:49 -07002166 return closeInput_nonvirtual(input);
2167}
2168
2169status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2170{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 // keep strong reference on the record thread so that
2172 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002173 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 {
2175 Mutex::Autolock _l(mLock);
2176 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002177 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178 return BAD_VALUE;
2179 }
2180
Steve Block3856b092011-10-20 11:56:00 +01002181 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002182
2183 // If we still have effect chains, it means that a client still holds a handle
2184 // on at least one effect. We must either move the chain to an existing thread with the
2185 // same session ID or put it aside in case a new record thread is opened for a
2186 // new capture on the same session
2187 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002188 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002189 Mutex::Autolock _sl(thread->mLock);
2190 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002191 // Note: maximum one chain per record thread
2192 if (effectChains.size() != 0) {
2193 chain = effectChains[0];
2194 }
2195 }
2196 if (chain != 0) {
2197 // first check if a record thread is already opened with a client on the same session.
2198 // This should only happen in case of overlap between one thread tear down and the
2199 // creation of its replacement
2200 size_t i;
2201 for (i = 0; i < mRecordThreads.size(); i++) {
2202 sp<RecordThread> t = mRecordThreads.valueAt(i);
2203 if (t == thread) {
2204 continue;
2205 }
2206 if (t->hasAudioSession(chain->sessionId()) != 0) {
2207 Mutex::Autolock _l(t->mLock);
2208 ALOGV("closeInput() found thread %d for effect session %d",
2209 t->id(), chain->sessionId());
2210 t->addEffectChain_l(chain);
2211 break;
2212 }
2213 }
2214 // put the chain aside if we could not find a record thread with the same session id.
2215 if (i == mRecordThreads.size()) {
2216 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002217 }
2218 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002219 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2220 ioDesc->mIoHandle = input;
2221 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 mRecordThreads.removeItem(input);
2223 }
Eric Laurent83b88082014-06-20 18:31:16 -07002224 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2225 // we have a different lock for notification client
2226 closeInputFinish(thread);
2227 return NO_ERROR;
2228}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229
Eric Laurent83b88082014-06-20 18:31:16 -07002230void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2231{
2232 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002233 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002234 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002235 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002236 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002237 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002238}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239
Eric Laurent83b88082014-06-20 18:31:16 -07002240void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2241{
2242 mRecordThreads.removeItem(thread->mId);
2243 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244}
2245
Glenn Kastend2304db2014-02-03 07:40:31 -08002246status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247{
2248 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002249 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250
2251 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2252 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002253 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002254 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255
2256 return NO_ERROR;
2257}
2258
2259
Eric Laurentde3f8392014-07-27 18:38:22 -07002260audio_unique_id_t AudioFlinger::newAudioUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002262 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263}
2264
Marco Nelissend457c972014-02-11 08:47:07 -08002265void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002266{
2267 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002268 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002269 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2270 if (pid != -1 && (caller == getpid_cached)) {
2271 caller = pid;
2272 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002273
Eric Laurent021cf962014-05-13 10:18:14 -07002274 {
2275 Mutex::Autolock _cl(mClientLock);
2276 // Ignore requests received from processes not known as notification client. The request
2277 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2278 // called from a different pid leaving a stale session reference. Also we don't know how
2279 // to clear this reference if the client process dies.
2280 if (mNotificationClients.indexOfKey(caller) < 0) {
2281 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2282 return;
2283 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002284 }
2285
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002286 size_t num = mAudioSessionRefs.size();
2287 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002288 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002289 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2290 ref->mCnt++;
2291 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002292 return;
2293 }
2294 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002295 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2296 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002297}
2298
Marco Nelissend457c972014-02-11 08:47:07 -08002299void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002300{
2301 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002302 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002303 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2304 if (pid != -1 && (caller == getpid_cached)) {
2305 caller = pid;
2306 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002307 size_t num = mAudioSessionRefs.size();
2308 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002309 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002310 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2311 ref->mCnt--;
2312 ALOGV(" decremented refcount to %d", ref->mCnt);
2313 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002314 mAudioSessionRefs.removeAt(i);
2315 delete ref;
2316 purgeStaleEffects_l();
2317 }
2318 return;
2319 }
2320 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002321 // If the caller is mediaserver it is likely that the session being released was acquired
2322 // on behalf of a process not in notification clients and we ignore the warning.
2323 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002324}
2325
2326void AudioFlinger::purgeStaleEffects_l() {
2327
Steve Block3856b092011-10-20 11:56:00 +01002328 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002329
2330 Vector< sp<EffectChain> > chains;
2331
2332 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2333 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2334 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2335 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002336 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2337 chains.push(ec);
2338 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002339 }
2340 }
2341 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2342 sp<RecordThread> t = mRecordThreads.valueAt(i);
2343 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2344 sp<EffectChain> ec = t->mEffectChains[j];
2345 chains.push(ec);
2346 }
2347 }
2348
2349 for (size_t i = 0; i < chains.size(); i++) {
2350 sp<EffectChain> ec = chains[i];
2351 int sessionid = ec->sessionId();
2352 sp<ThreadBase> t = ec->mThread.promote();
2353 if (t == 0) {
2354 continue;
2355 }
2356 size_t numsessionrefs = mAudioSessionRefs.size();
2357 bool found = false;
2358 for (size_t k = 0; k < numsessionrefs; k++) {
2359 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002360 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002361 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002362 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002363 found = true;
2364 break;
2365 }
2366 }
2367 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002368 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002369 // remove all effects from the chain
2370 while (ec->mEffects.size()) {
2371 sp<EffectModule> effect = ec->mEffects[0];
2372 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002373 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002374 if (effect->purgeHandles()) {
2375 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002376 }
2377 AudioSystem::unregisterEffect(effect->id());
2378 }
2379 }
2380 }
2381 return;
2382}
2383
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002385AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386{
Glenn Kastena1117922012-01-26 10:53:32 -08002387 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388}
2389
2390// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002391AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392{
2393 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002394 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395}
2396
2397// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002398AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399{
Glenn Kastena1117922012-01-26 10:53:32 -08002400 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401}
2402
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002403uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404{
Glenn Kastenbcefec32014-01-17 12:09:05 -08002405 return (uint32_t) android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406}
2407
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002408AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002409{
2410 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2411 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002412 if(thread->isDuplicating()) {
2413 continue;
2414 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002415 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002416 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002417 return thread;
2418 }
2419 }
2420 return NULL;
2421}
2422
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002423audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002424{
2425 PlaybackThread *thread = primaryPlaybackThread_l();
2426
2427 if (thread == NULL) {
2428 return 0;
2429 }
2430
Eric Laurentf1c04f92012-08-28 14:26:53 -07002431 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002432}
2433
Eric Laurenta011e352012-03-29 15:51:43 -07002434sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
2435 int triggerSession,
2436 int listenerSession,
2437 sync_event_callback_t callBack,
Eric Laurent8ea16e42014-02-20 16:26:11 -08002438 wp<RefBase> cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002439{
2440 Mutex::Autolock _l(mLock);
2441
2442 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2443 status_t playStatus = NAME_NOT_FOUND;
2444 status_t recStatus = NAME_NOT_FOUND;
2445 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2446 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2447 if (playStatus == NO_ERROR) {
2448 return event;
2449 }
2450 }
2451 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2452 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2453 if (recStatus == NO_ERROR) {
2454 return event;
2455 }
2456 }
2457 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2458 mPendingSyncEvents.add(event);
2459 } else {
2460 ALOGV("createSyncEvent() invalid event %d", event->type());
2461 event.clear();
2462 }
2463 return event;
2464}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002465
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466// ----------------------------------------------------------------------------
2467// Effect management
2468// ----------------------------------------------------------------------------
2469
2470
Glenn Kastenf587ba52012-01-26 16:25:10 -08002471status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472{
2473 Mutex::Autolock _l(mLock);
2474 return EffectQueryNumberEffects(numEffects);
2475}
2476
Glenn Kastenf587ba52012-01-26 16:25:10 -08002477status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478{
2479 Mutex::Autolock _l(mLock);
2480 return EffectQueryEffect(index, descriptor);
2481}
2482
Glenn Kasten5e92a782012-01-30 07:40:52 -08002483status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002484 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485{
2486 Mutex::Autolock _l(mLock);
2487 return EffectGetDescriptor(pUuid, descriptor);
2488}
2489
2490
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002491sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 effect_descriptor_t *pDesc,
2493 const sp<IEffectClient>& effectClient,
2494 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002495 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 int sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002497 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 status_t *status,
2499 int *id,
2500 int *enabled)
2501{
2502 status_t lStatus = NO_ERROR;
2503 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002506 pid_t pid = IPCThreadState::self()->getCallingPid();
Glenn Kasten98ec94c2012-01-25 14:28:29 -08002507 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002508 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509
2510 if (pDesc == NULL) {
2511 lStatus = BAD_VALUE;
2512 goto Exit;
2513 }
2514
Eric Laurent84e9a102010-09-23 16:10:16 -07002515 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002516 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002517 lStatus = PERMISSION_DENIED;
2518 goto Exit;
2519 }
2520
Dima Zavinfce7a472011-04-19 22:30:36 -07002521 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002522 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002523 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002524 lStatus = PERMISSION_DENIED;
2525 goto Exit;
2526 }
2527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 if (!EffectIsNullUuid(&pDesc->uuid)) {
2530 // if uuid is specified, request effect descriptor
2531 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2532 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002533 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 goto Exit;
2535 }
2536 } else {
2537 // if uuid is not specified, look for an available implementation
2538 // of the required type in effect factory
2539 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002540 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 lStatus = BAD_VALUE;
2542 goto Exit;
2543 }
2544 uint32_t numEffects = 0;
2545 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002546 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 bool found = false;
2548
2549 lStatus = EffectQueryNumberEffects(&numEffects);
2550 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002551 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 goto Exit;
2553 }
2554 for (uint32_t i = 0; i < numEffects; i++) {
2555 lStatus = EffectQueryEffect(i, &desc);
2556 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002557 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 continue;
2559 }
2560 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2561 // If matching type found save effect descriptor. If the session is
2562 // 0 and the effect is not auxiliary, continue enumeration in case
2563 // an auxiliary version of this effect type is available
2564 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002565 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002566 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2568 break;
2569 }
2570 }
2571 }
2572 if (!found) {
2573 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002574 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575 goto Exit;
2576 }
2577 // For same effect type, chose auxiliary version over insert version if
2578 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002579 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002581 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 }
2583 }
2584
2585 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002586 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2588 lStatus = INVALID_OPERATION;
2589 goto Exit;
2590 }
2591
Eric Laurent59255e42011-07-27 19:49:51 -07002592 // check recording permission for visualizer
2593 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganovbe71aa22015-04-28 12:06:02 -07002594 !recordingAllowed(opPackageName)) {
Eric Laurent59255e42011-07-27 19:49:51 -07002595 lStatus = PERMISSION_DENIED;
2596 goto Exit;
2597 }
2598
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002600 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002601 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002602 // if the output returned by getOutputForEffect() is removed before we lock the
2603 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2604 // and we will exit safely
2605 io = AudioSystem::getOutputForEffect(&desc);
2606 ALOGV("createEffect got output %d", io);
2607 }
2608
2609 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610
2611 // If output is not specified try to find a matching audio session ID in one of the
2612 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002613 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2614 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002615 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002616 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002617 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2618 // output must be specified by AudioPolicyManager when using session
2619 // AUDIO_SESSION_OUTPUT_STAGE
2620 lStatus = BAD_VALUE;
2621 goto Exit;
2622 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002623 // look for the thread where the specified audio session is present
2624 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2625 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2626 io = mPlaybackThreads.keyAt(i);
2627 break;
2628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002630 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002631 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2632 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2633 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002634 break;
2635 }
2636 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002637 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002638 // If no output thread contains the requested session ID, default to
2639 // first output. The effect chain will be moved to the correct output
2640 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002641 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002642 io = mPlaybackThreads.keyAt(0);
2643 }
Steve Block3856b092011-10-20 11:56:00 +01002644 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002645 }
2646 ThreadBase *thread = checkRecordThread_l(io);
2647 if (thread == NULL) {
2648 thread = checkPlaybackThread_l(io);
2649 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002650 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002651 lStatus = BAD_VALUE;
2652 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002653 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002654 } else {
2655 // Check if one effect chain was awaiting for an effect to be created on this
2656 // session and used it instead of creating a new one.
2657 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)sessionId);
2658 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002659 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002660 thread->addEffectChain_l(chain);
2661 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002663
Eric Laurent021cf962014-05-13 10:18:14 -07002664 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002666 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002667 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2668 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669 if (handle != 0 && id != NULL) {
2670 *id = handle->id();
2671 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002672 if (handle == 0) {
2673 // remove local strong reference to Client with mClientLock held
2674 Mutex::Autolock _cl(mClientLock);
2675 client.clear();
2676 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 }
2678
2679Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002680 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 return handle;
2682}
2683
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002684status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2685 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002686{
Steve Block3856b092011-10-20 11:56:00 +01002687 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002688 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002689 Mutex::Autolock _l(mLock);
2690 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002691 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002692 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693 }
Eric Laurentde070132010-07-13 04:45:46 -07002694 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2695 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002696 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002697 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 }
Eric Laurentde070132010-07-13 04:45:46 -07002699 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2700 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002701 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002702 return BAD_VALUE;
2703 }
2704
2705 Mutex::Autolock _dl(dstThread->mLock);
2706 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002707 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708}
2709
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002710// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07002711status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002712 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002713 AudioFlinger::PlaybackThread *dstThread,
2714 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002715{
Steve Block3856b092011-10-20 11:56:00 +01002716 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002717 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002718
Eric Laurent59255e42011-07-27 19:49:51 -07002719 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002720 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002721 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002722 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002723 return INVALID_OPERATION;
2724 }
2725
Andy Hung9a592762014-07-21 21:56:01 -07002726 // Check whether the destination thread has a channel count of FCC_2, which is
2727 // currently required for (most) effects. Prevent moving the effect chain here rather
2728 // than disabling the addEffect_l() call in dstThread below.
Eric Laurentf6870ae2015-05-08 10:50:03 -07002729 if ((dstThread->type() == ThreadBase::MIXER || dstThread->isDuplicating()) &&
Eric Laurentb10352f2014-11-03 16:25:39 -08002730 dstThread->mChannelCount != FCC_2) {
Andy Hung9a592762014-07-21 21:56:01 -07002731 ALOGW("moveEffectChain_l() effect chain failed because"
2732 " destination thread %p channel count(%u) != %u",
2733 dstThread, dstThread->mChannelCount, FCC_2);
2734 return INVALID_OPERATION;
2735 }
2736
Eric Laurent39e94f82010-07-28 01:32:47 -07002737 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002738 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002739 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002740 // removed.
2741 srcThread->removeEffectChain_l(chain);
2742
2743 // transfer all effects one by one so that new effect chain is created on new thread with
2744 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002745 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002746 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002747 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002748 Vector< sp<EffectModule> > removed;
2749 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002750 while (effect != 0) {
2751 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002752 removed.add(effect);
2753 status = dstThread->addEffect_l(effect);
2754 if (status != NO_ERROR) {
2755 break;
2756 }
Eric Laurentec35a142011-10-05 17:42:25 -07002757 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2758 if (effect->state() == EffectModule::ACTIVE ||
2759 effect->state() == EffectModule::STOPPING) {
2760 effect->start();
2761 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002762 // if the move request is not received from audio policy manager, the effect must be
2763 // re-registered with the new strategy and output
2764 if (dstChain == 0) {
2765 dstChain = effect->chain().promote();
2766 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002767 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002768 status = NO_INIT;
2769 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002770 }
2771 strategy = dstChain->strategy();
2772 }
2773 if (reRegister) {
2774 AudioSystem::unregisterEffect(effect->id());
2775 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002776 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002777 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002778 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002779 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002780 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002781 }
Eric Laurentde070132010-07-13 04:45:46 -07002782 effect = chain->getEffectFromId_l(0);
2783 }
2784
Eric Laurent5baf2af2013-09-12 17:37:00 -07002785 if (status != NO_ERROR) {
2786 for (size_t i = 0; i < removed.size(); i++) {
2787 srcThread->addEffect_l(removed[i]);
2788 if (dstChain != 0 && reRegister) {
2789 AudioSystem::unregisterEffect(removed[i]->id());
2790 AudioSystem::registerEffect(&removed[i]->desc(),
2791 srcThread->id(),
2792 strategy,
2793 sessionId,
2794 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002795 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002796 }
2797 }
2798 }
2799
2800 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801}
2802
Eric Laurent5baf2af2013-09-12 17:37:00 -07002803bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002804{
2805 if (mGlobalEffectEnableTime != 0 &&
2806 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2807 return true;
2808 }
2809
2810 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2811 sp<EffectChain> ec =
2812 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002813 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002814 return true;
2815 }
2816 }
2817 return false;
2818}
2819
Eric Laurent5baf2af2013-09-12 17:37:00 -07002820void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002821{
2822 Mutex::Autolock _l(mLock);
2823
2824 mGlobalEffectEnableTime = systemTime();
2825
2826 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2827 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2828 if (t->mType == ThreadBase::OFFLOAD) {
2829 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2830 }
2831 }
2832
2833}
2834
Eric Laurentaaa44472014-09-12 17:41:50 -07002835status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2836{
2837 audio_session_t session = (audio_session_t)chain->sessionId();
2838 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2839 ALOGV("putOrphanEffectChain_l session %d index %d", session, index);
2840 if (index >= 0) {
2841 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2842 return ALREADY_EXISTS;
2843 }
2844 mOrphanEffectChains.add(session, chain);
2845 return NO_ERROR;
2846}
2847
2848sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2849{
2850 sp<EffectChain> chain;
2851 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2852 ALOGV("getOrphanEffectChain_l session %d index %d", session, index);
2853 if (index >= 0) {
2854 chain = mOrphanEffectChains.valueAt(index);
2855 mOrphanEffectChains.removeItemsAt(index);
2856 }
2857 return chain;
2858}
2859
2860bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2861{
2862 Mutex::Autolock _l(mLock);
2863 audio_session_t session = (audio_session_t)effect->sessionId();
2864 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2865 ALOGV("updateOrphanEffectChains session %d index %d", session, index);
2866 if (index >= 0) {
2867 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2868 if (chain->removeEffect_l(effect) == 0) {
2869 ALOGV("updateOrphanEffectChains removing effect chain at index %d", index);
2870 mOrphanEffectChains.removeItemsAt(index);
2871 }
2872 return true;
2873 }
2874 return false;
2875}
2876
2877
Glenn Kastenda6ef132013-01-10 12:31:01 -08002878struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002879#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
2880 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002881};
2882
2883int comparEntry(const void *p1, const void *p2)
2884{
Glenn Kasten2f55e762015-03-05 16:05:08 -08002885 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002886}
2887
Glenn Kasten46909e72013-02-26 09:20:22 -08002888#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002889void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890{
Eric Laurent81784c32012-11-19 14:55:58 -08002891 NBAIO_Source *teeSource = source.get();
2892 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002893 // .wav rotation
2894 // There is a benign race condition if 2 threads call this simultaneously.
2895 // They would both traverse the directory, but the result would simply be
2896 // failures at unlink() which are ignored. It's also unlikely since
2897 // normally dumpsys is only done by bugreport or from the command line.
2898 char teePath[32+256];
2899 strcpy(teePath, "/data/misc/media");
2900 size_t teePathLen = strlen(teePath);
2901 DIR *dir = opendir(teePath);
2902 teePath[teePathLen++] = '/';
2903 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002904#define TEE_MAX_SORT 20 // number of entries to sort
2905#define TEE_MAX_KEEP 10 // number of entries to keep
2906 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002907 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08002908 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002909 struct dirent de;
2910 struct dirent *result = NULL;
2911 int rc = readdir_r(dir, &de, &result);
2912 if (rc != 0) {
2913 ALOGW("readdir_r failed %d", rc);
2914 break;
2915 }
2916 if (result == NULL) {
2917 break;
2918 }
2919 if (result != &de) {
2920 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
2921 break;
2922 }
2923 // ignore non .wav file entries
2924 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002925 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08002926 strcmp(&de.d_name[nameLen - 4], ".wav")) {
2927 continue;
2928 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08002929 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002930 }
2931 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002932 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002933 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002934 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
2935 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002936 (void) unlink(teePath);
2937 }
2938 }
2939 } else {
2940 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07002941 dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08002942 }
2943 }
Eric Laurent81784c32012-11-19 14:55:58 -08002944 char teeTime[16];
2945 struct timeval tv;
2946 gettimeofday(&tv, NULL);
2947 struct tm tm;
2948 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002949 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
2950 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
2951 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
2952 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08002953 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07002954 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08002955 char wavHeader[44];
2956 memcpy(wavHeader,
2957 "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",
2958 sizeof(wavHeader));
2959 NBAIO_Format format = teeSource->format();
2960 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08002961 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07002962 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08002963 wavHeader[22] = channelCount; // number of channels
2964 wavHeader[24] = sampleRate; // sample rate
2965 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07002966 wavHeader[32] = frameSize; // block alignment
2967 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08002968 write(teeFd, wavHeader, sizeof(wavHeader));
2969 size_t total = 0;
2970 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07002971#define TEE_SINK_READ 1024 // frames per I/O operation
2972 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002973 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08002974 size_t count = TEE_SINK_READ;
2975 ssize_t actual = teeSource->read(buffer, count,
2976 AudioBufferProvider::kInvalidPTS);
2977 bool wasFirstRead = firstRead;
2978 firstRead = false;
2979 if (actual <= 0) {
2980 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2981 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07002982 }
Eric Laurent81784c32012-11-19 14:55:58 -08002983 break;
Eric Laurent59255e42011-07-27 19:49:51 -07002984 }
Eric Laurent81784c32012-11-19 14:55:58 -08002985 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07002986 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002987 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07002988 }
Glenn Kasten329f6512014-08-28 16:23:16 -07002989 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002990 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07002991 uint32_t temp = 44 + total * frameSize - 8;
2992 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08002993 write(teeFd, &temp, sizeof(temp));
2994 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07002995 temp = total * frameSize;
2996 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08002997 write(teeFd, &temp, sizeof(temp));
2998 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002999 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003000 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003001 }
Eric Laurent59255e42011-07-27 19:49:51 -07003002 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003003 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003004 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003005 }
Eric Laurent59255e42011-07-27 19:49:51 -07003006 }
3007 }
3008}
Glenn Kasten46909e72013-02-26 09:20:22 -08003009#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003010
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011// ----------------------------------------------------------------------------
3012
3013status_t AudioFlinger::onTransact(
3014 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3015{
3016 return BnAudioFlinger::onTransact(code, data, reply, flags);
3017}
3018
Glenn Kasten63238ef2015-03-02 15:50:29 -08003019} // namespace android