blob: 53a4ce9e0c919d1ecd4a52e51e3e2a462cd7f94f [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>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
42
Steven Morelandf0c02ce2018-02-23 14:53:55 -080043#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <cutils/properties.h>
45
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Mathias Agopian65ab4712010-07-14 17:59:35 -070048#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070049#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Andy Hung6770c6f2015-04-07 13:43:36 -070051#include <media/AudioResamplerPublic.h>
52
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_visualizer.h>
54#include <system/audio_effects/effect_ns.h>
55#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Eric Laurentfeb0db62011-07-22 09:04:31 -070059#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080060
Glenn Kasten9e58b552013-01-18 15:09:48 -080061#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070062#include <media/MemoryLeakTrackUtil.h>
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>
Andy Hungab7ef302018-05-15 19:35:29 -070067#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
rago3bd1c872016-09-26 12:58:14 -070070//#define BUFLOG_NDEBUG 0
71#include <BufLog.h>
72
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080073#include "TypedLogger.h"
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
John Grossman1c345192012-03-27 14:00:17 -070077// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
Eric Laurentde070132010-07-13 04:45:46 -070089
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Glenn Kastenec1d6b52011-12-12 09:04:45 -080092static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
93static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070094static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070095static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070096
Glenn Kasten58912562012-04-03 10:45:00 -070097
John Grossman4ff14ba2012-02-08 16:37:41 -080098nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700101
Eric Laurent813e2a72013-08-31 12:59:48 -0700102// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
103// we define a minimum time during which a global effect is considered enabled.
104static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
105
Eric Laurentfc235202016-12-20 18:48:17 -0800106Mutex gLock;
107wp<AudioFlinger> gAudioFlinger;
108
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700109// Keep a strong reference to media.log service around forever.
110// The service is within our parent process so it can never die in a way that we could observe.
111// These two variables are const after initialization.
112static sp<IBinder> sMediaLogServiceAsBinder;
113static sp<IMediaLogService> sMediaLogService;
114
115static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
116
117static void sMediaLogInit()
118{
119 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
120 if (sMediaLogServiceAsBinder != 0) {
121 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
122 }
123}
124
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125// ----------------------------------------------------------------------------
126
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700127std::string formatToString(audio_format_t format) {
128 std::string result;
129 FormatConverter::toString(format, result);
130 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800131}
132
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133// ----------------------------------------------------------------------------
134
135AudioFlinger::AudioFlinger()
136 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800137 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800138 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800139 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700140 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800141 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800142 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700143 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800144 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700145 mBtNrecIsOff(false),
146 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700147 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800148 mTotalMemory(0),
149 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700150 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700151 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700152 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700153{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700154 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
155 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
156 // zero ID has a special meaning, so unavailable
157 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
158 }
159
Glenn Kastenae0cff12016-02-24 13:57:49 -0800160 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800161 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800162 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
163 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700164 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800165 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700166
Wei Jia3f273d12015-11-24 09:06:49 -0800167 // reset battery stats.
168 // if the audio service has crashed, battery stats could be left
169 // in bad state, reset the state upon service start.
170 BatteryNotifier::getInstance().noteResetAudio();
171
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700172 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700173 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
174
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800175 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700176}
177
178void AudioFlinger::onFirstRef()
179{
Eric Laurent93575202011-01-18 18:39:02 -0800180 Mutex::Autolock _l(mLock);
181
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800183 char val_str[PROPERTY_VALUE_MAX] = { 0 };
184 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
185 uint32_t int_val;
186 if (1 == sscanf(val_str, "%u", &int_val)) {
187 mStandbyTimeInNsecs = milliseconds(int_val);
188 ALOGI("Using %u mSec as standby time.", int_val);
189 } else {
190 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
191 ALOGI("Using default %u mSec as standby time.",
192 (uint32_t)(mStandbyTimeInNsecs / 1000000));
193 }
194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700195
Eric Laurenta4c5a552012-03-29 10:12:40 -0700196 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800197
198 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700199}
200
201AudioFlinger::~AudioFlinger()
202{
203 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700204 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700205 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700206 }
207 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700208 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700209 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700211
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800212 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
213 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700214 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700216
217 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700218 if (sMediaLogService != 0) {
219 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
220 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
221 mUnregisteredWriters.pop();
222 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700223 }
224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225}
226
Eric Laurentfc235202016-12-20 18:48:17 -0800227//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800228__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800229status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
230 const audio_attributes_t *attr,
231 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700232 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800233 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800234 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800235 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700236 sp<MmapStreamInterface>& interface,
237 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800238{
239 sp<AudioFlinger> af;
240 {
241 Mutex::Autolock _l(gLock);
242 af = gAudioFlinger.promote();
243 }
244 status_t ret = NO_INIT;
245 if (af != 0) {
246 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800247 direction, attr, config, client, deviceId,
248 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800249 }
250 return ret;
251}
252
Eric Laurent6acd1d42017-01-04 14:23:29 -0800253status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
254 const audio_attributes_t *attr,
255 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700256 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800257 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800258 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800259 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700260 sp<MmapStreamInterface>& interface,
261 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800262{
263 status_t ret = initCheck();
264 if (ret != NO_ERROR) {
265 return ret;
266 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800267 audio_session_t actualSessionId = *sessionId;
268 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
269 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
270 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800271 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700272 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800273 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
274 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
275 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
276 fullConfig.sample_rate = config->sample_rate;
277 fullConfig.channel_mask = config->channel_mask;
278 fullConfig.format = config->format;
279 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800280 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200281 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800282 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800283 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
284 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700285 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800286 } else {
287 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800288 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800289 client.clientPid,
290 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800291 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800292 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700293 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800294 }
295 if (ret != NO_ERROR) {
296 return ret;
297 }
298
299 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
300 // audio policy manager and we can retrieve it
301 sp<MmapThread> thread = mMmapThreads.valueFor(io);
302 if (thread != 0) {
303 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800304 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700305 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800306 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800307 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700308 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800309 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700310 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800311 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700312 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800313 ret = NO_INIT;
314 }
315
316 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
317
Eric Laurentfc235202016-12-20 18:48:17 -0800318 return ret;
319}
320
Eric Laurenta4c5a552012-03-29 10:12:40 -0700321static const char * const audio_interfaces[] = {
322 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
323 AUDIO_HARDWARE_MODULE_ID_A2DP,
324 AUDIO_HARDWARE_MODULE_ID_USB,
325};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700326
Phil Burk062e67a2015-02-11 13:40:50 -0800327AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700328 audio_module_handle_t module,
329 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700330{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700331 // if module is 0, the request comes from an old policy manager and we should load
332 // well known modules
333 if (module == 0) {
334 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700335 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700336 loadHwModule_l(audio_interfaces[i]);
337 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700338 // then try to find a module supporting the requested device.
339 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
340 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700341 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
342 uint32_t supportedDevices;
343 if (dev->getSupportedDevices(&supportedDevices) == OK &&
344 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700345 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700346 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700347 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700348 } else {
349 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700350 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
351 if (audioHwDevice != NULL) {
352 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700353 }
354 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355
Dima Zavin799a70e2011-04-18 16:57:27 -0700356 return NULL;
357}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700358
Glenn Kasten0f11b512014-01-31 16:18:54 -0800359void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360{
361 const size_t SIZE = 256;
362 char buffer[SIZE];
363 String8 result;
364
365 result.append("Clients:\n");
366 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800367 sp<Client> client = mClients.valueAt(i).promote();
368 if (client != 0) {
369 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
370 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700373
Eric Laurentd1b28d42013-09-18 18:47:13 -0700374 result.append("Notification Clients:\n");
375 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
376 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
377 result.append(buffer);
378 }
379
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700380 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800381 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700382 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
383 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800384 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700385 result.append(buffer);
386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388}
389
390
Glenn Kasten0f11b512014-01-31 16:18:54 -0800391void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392{
393 const size_t SIZE = 256;
394 char buffer[SIZE];
395 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800396 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397
John Grossman4ff14ba2012-02-08 16:37:41 -0800398 snprintf(buffer, SIZE, "Hardware status: %d\n"
399 "Standby Time mSec: %u\n",
400 hardwareStatus,
401 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402 result.append(buffer);
403 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404}
405
Glenn Kasten0f11b512014-01-31 16:18:54 -0800406void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407{
408 const size_t SIZE = 256;
409 char buffer[SIZE];
410 String8 result;
411 snprintf(buffer, SIZE, "Permission Denial: "
412 "can't dump AudioFlinger from pid=%d, uid=%d\n",
413 IPCThreadState::self()->getCallingPid(),
414 IPCThreadState::self()->getCallingUid());
415 result.append(buffer);
416 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417}
418
Eric Laurent81784c32012-11-19 14:55:58 -0800419bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420{
421 bool locked = false;
422 for (int i = 0; i < kDumpLockRetries; ++i) {
423 if (mutex.tryLock() == NO_ERROR) {
424 locked = true;
425 break;
426 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800427 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428 }
429 return locked;
430}
431
432status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
433{
Glenn Kasten44deb052012-02-05 18:09:08 -0800434 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 dumpPermissionDenial(fd, args);
436 } else {
437 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800438 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 if (!hardwareLocked) {
440 String8 result(kHardwareLockedString);
441 write(fd, result.string(), result.size());
442 } else {
443 mHardwareLock.unlock();
444 }
445
Eric Laurent81784c32012-11-19 14:55:58 -0800446 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447
448 // failed to lock - AudioFlinger is probably deadlocked
449 if (!locked) {
450 String8 result(kDeadlockedString);
451 write(fd, result.string(), result.size());
452 }
453
Eric Laurent021cf962014-05-13 10:18:14 -0700454 bool clientLocked = dumpTryLock(mClientLock);
455 if (!clientLocked) {
456 String8 result(kClientLockedString);
457 write(fd, result.string(), result.size());
458 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700459
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700460 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700461 mEffectsFactoryHal->dumpEffects(fd);
462 } else {
463 String8 result(kNoEffectsFactory);
464 write(fd, result.string(), result.size());
465 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700466
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700468 if (clientLocked) {
469 mClientLock.unlock();
470 }
471
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 dumpInternals(fd, args);
473
474 // dump playback threads
475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
476 mPlaybackThreads.valueAt(i)->dump(fd, args);
477 }
478
479 // dump record threads
480 for (size_t i = 0; i < mRecordThreads.size(); i++) {
481 mRecordThreads.valueAt(i)->dump(fd, args);
482 }
483
Eric Laurent6acd1d42017-01-04 14:23:29 -0800484 // dump mmap threads
485 for (size_t i = 0; i < mMmapThreads.size(); i++) {
486 mMmapThreads.valueAt(i)->dump(fd, args);
487 }
488
Eric Laurentaaa44472014-09-12 17:41:50 -0700489 // dump orphan effect chains
490 if (mOrphanEffectChains.size() != 0) {
491 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
492 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
493 mOrphanEffectChains.valueAt(i)->dump(fd, args);
494 }
495 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700496 // dump all hardware devs
497 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700498 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
499 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700501
Mikhail Naganov201369b2018-05-16 16:52:32 -0700502 mPatchPanel.dump(fd);
503
rago3bd1c872016-09-26 12:58:14 -0700504 BUFLOG_RESET;
505
Glenn Kastend65d73c2012-06-22 17:21:07 -0700506 if (locked) {
507 mLock.unlock();
508 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800509
Andy Hung8946a282018-04-19 20:04:56 -0700510#ifdef TEE_SINK
511 // NBAIO_Tee dump is safe to call outside of AF lock.
512 NBAIO_Tee::dumpAll(fd, "_DUMP");
513#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800514 // append a copy of media.log here by forwarding fd to it, but don't attempt
515 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700516 if (sMediaLogServiceAsBinder != 0) {
517 dprintf(fd, "\nmedia.log:\n");
518 Vector<String16> args;
519 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800520 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700521
522 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700523 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700524 bool unreachableMemory = false;
525 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700526 if (arg == String16("-m")) {
527 dumpMem = true;
528 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700529 unreachableMemory = true;
530 }
531 }
532
Andy Hung07b745e2016-05-23 16:21:07 -0700533 if (dumpMem) {
534 dprintf(fd, "\nDumping memory:\n");
535 std::string s = dumpMemoryAddresses(100 /* limit */);
536 write(fd, s.c_str(), s.size());
537 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700538 if (unreachableMemory) {
539 dprintf(fd, "\nDumping unreachable memory:\n");
540 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700541 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700542 write(fd, s.c_str(), s.size());
543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 }
545 return NO_ERROR;
546}
547
Eric Laurent021cf962014-05-13 10:18:14 -0700548sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800549{
Eric Laurent021cf962014-05-13 10:18:14 -0700550 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800551 // If pid is already in the mClients wp<> map, then use that entry
552 // (for which promote() is always != 0), otherwise create a new entry and Client.
553 sp<Client> client = mClients.valueFor(pid).promote();
554 if (client == 0) {
555 client = new Client(this, pid);
556 mClients.add(pid, client);
557 }
558
559 return client;
560}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561
Glenn Kasten9e58b552013-01-18 15:09:48 -0800562sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
563{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700564 // If there is no memory allocated for logs, return a dummy writer that does nothing.
565 // Similarly if we can't contact the media.log service, also return a dummy writer.
566 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800567 return new NBLog::Writer();
568 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700569 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
570 // If allocation fails, consult the vector of previously unregistered writers
571 // and garbage-collect one or more them until an allocation succeeds
572 if (shared == 0) {
573 Mutex::Autolock _l(mUnregisteredWritersLock);
574 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
575 {
576 // Pick the oldest stale writer to garbage-collect
577 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
578 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700579 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700580 // Now the media.log remote reference to IMemory is gone. When our last local
581 // reference to IMemory also drops to zero at end of this block,
582 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
583 }
584 // Re-attempt the allocation
585 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
586 if (shared != 0) {
587 goto success;
588 }
589 }
590 // Even after garbage-collecting all old writers, there is still not enough memory,
591 // so return a dummy writer
592 return new NBLog::Writer();
593 }
594success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800595 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
596 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
597 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700598 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800599 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800600}
601
602void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
603{
Glenn Kasten685ef092013-02-04 08:15:34 -0800604 if (writer == 0) {
605 return;
606 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800607 sp<IMemory> iMemory(writer->getIMemory());
608 if (iMemory == 0) {
609 return;
610 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700611 // Rather than removing the writer immediately, append it to a queue of old writers to
612 // be garbage-collected later. This allows us to continue to view old logs for a while.
613 Mutex::Autolock _l(mUnregisteredWritersLock);
614 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800615}
616
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617// IAudioFlinger interface
618
Eric Laurent21da6472017-11-09 16:29:26 -0800619sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
620 CreateTrackOutput& output,
621 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622{
623 sp<PlaybackThread::Track> track;
624 sp<TrackHandle> trackHandle;
625 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800627 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800628 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
Eric Laurent21da6472017-11-09 16:29:26 -0800630 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700631 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800632 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700633 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800634 ALOGW_IF(clientUid != callingUid,
635 "%s uid %d tried to pass itself off as %d",
636 __FUNCTION__, callingUid, clientUid);
637 clientUid = callingUid;
638 updatePid = true;
639 }
640 pid_t clientPid = input.clientInfo.clientPid;
641 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700642 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800643 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700644 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800645 __func__, callingUid, callingPid, clientPid);
646 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700647 }
648
Eric Laurent21da6472017-11-09 16:29:26 -0800649 audio_session_t sessionId = input.sessionId;
650 if (sessionId == AUDIO_SESSION_ALLOCATE) {
651 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800652 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
653 lStatus = BAD_VALUE;
654 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800655 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800656
Eric Laurent21da6472017-11-09 16:29:26 -0800657 output.sessionId = sessionId;
658 output.outputId = AUDIO_IO_HANDLE_NONE;
659 output.selectedDeviceId = input.selectedDeviceId;
660
661 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200662 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800663 &output.selectedDeviceId, &portId);
664
665 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
666 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
667 goto Exit;
668 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800669 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
670 // but if someone uses binder directly they could bypass that and cause us to crash
671 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000672 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673 lStatus = BAD_VALUE;
674 goto Exit;
675 }
676
Glenn Kasten53b5d092014-02-05 10:00:23 -0800677 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800678 if (!audio_is_output_channel(input.config.channel_mask)) {
679 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800680 lStatus = BAD_VALUE;
681 goto Exit;
682 }
683
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700684 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800685 if (!audio_is_valid_format(input.config.format)) {
686 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700687 lStatus = BAD_VALUE;
688 goto Exit;
689 }
690
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691 {
692 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800693 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800695 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 lStatus = BAD_VALUE;
697 goto Exit;
698 }
699
Eric Laurent21da6472017-11-09 16:29:26 -0800700 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701
Glenn Kastene848bd92014-03-13 15:00:32 -0700702 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800703 // check if an effect chain with the same session ID is present on another
704 // output thread and move it here.
705 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
706 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
707 if (mPlaybackThreads.keyAt(i) != output.outputId) {
708 uint32_t sessions = t->hasAudioSession(sessionId);
709 if (sessions & ThreadBase::EFFECT_SESSION) {
710 effectThread = t.get();
711 break;
Eric Laurentde070132010-07-13 04:45:46 -0700712 }
713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714 }
Eric Laurent21da6472017-11-09 16:29:26 -0800715 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716
Eric Laurent21da6472017-11-09 16:29:26 -0800717 output.sampleRate = input.config.sample_rate;
718 output.frameCount = input.frameCount;
719 output.notificationFrameCount = input.notificationFrameCount;
720 output.flags = input.flags;
721
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700722 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
723 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800724 &output.frameCount, &output.notificationFrameCount,
725 input.notificationsPerBuffer, input.speed,
726 input.sharedBuffer, sessionId, &output.flags,
727 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800728 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700729 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700730
Eric Laurent21da6472017-11-09 16:29:26 -0800731 output.afFrameCount = thread->frameCount();
732 output.afSampleRate = thread->sampleRate();
733 output.afLatencyMs = thread->latency();
734
Eric Laurent39e94f82010-07-28 01:32:47 -0700735 // move effect chain to this output thread if an effect on same session was waiting
736 // for a track to be created
737 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700738 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700739 Mutex::Autolock _dl(thread->mLock);
740 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800741 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700742 }
Eric Laurenta011e352012-03-29 15:51:43 -0700743
744 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700745 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800746 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700747 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700748 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700749 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700750 } else {
751 mPendingSyncEvents[i]->cancel();
752 }
Eric Laurenta011e352012-03-29 15:51:43 -0700753 mPendingSyncEvents.removeAt(i);
754 i--;
755 }
756 }
757 }
Glenn Kastene198c362013-08-13 09:13:36 -0700758
Eric Laurent21da6472017-11-09 16:29:26 -0800759 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 }
Glenn Kastene198c362013-08-13 09:13:36 -0700761
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700762 if (lStatus != NO_ERROR) {
763 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700764 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700765 // Don't hold mClientLock when releasing the reference on the track as the
766 // destructor will acquire it.
767 {
768 Mutex::Autolock _cl(mClientLock);
769 client.clear();
770 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700772 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773 }
774
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700775 // return handle to client
776 trackHandle = new TrackHandle(track);
777
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800779 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
780 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
781 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700782 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 return trackHandle;
784}
785
Glenn Kasten2c073da2016-02-26 09:14:08 -0800786uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787{
788 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800789 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800791 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 return 0;
793 }
794 return thread->sampleRate();
795}
796
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800797audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798{
799 Mutex::Autolock _l(mLock);
800 PlaybackThread *thread = checkPlaybackThread_l(output);
801 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000802 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800803 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805 return thread->format();
806}
807
Glenn Kasten2c073da2016-02-26 09:14:08 -0800808size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809{
810 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800811 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800813 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return 0;
815 }
Glenn Kasten58912562012-04-03 10:45:00 -0700816 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
817 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 return thread->frameCount();
819}
820
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700821size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
822{
823 Mutex::Autolock _l(mLock);
824 ThreadBase *thread = checkThread_l(ioHandle);
825 if (thread == NULL) {
826 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
827 return 0;
828 }
829 return thread->frameCountHAL();
830}
831
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800832uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833{
834 Mutex::Autolock _l(mLock);
835 PlaybackThread *thread = checkPlaybackThread_l(output);
836 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800837 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 return 0;
839 }
840 return thread->latency();
841}
842
843status_t AudioFlinger::setMasterVolume(float value)
844{
Eric Laurenta1884f92011-08-23 08:25:03 -0700845 status_t ret = initCheck();
846 if (ret != NO_ERROR) {
847 return ret;
848 }
849
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 // check calling permissions
851 if (!settingsAllowed()) {
852 return PERMISSION_DENIED;
853 }
854
Eric Laurenta4c5a552012-03-29 10:12:40 -0700855 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700856 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700857
John Grossmanee578c02012-07-23 17:05:46 -0700858 // Set master volume in the HALs which support it.
859 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
860 AutoMutex lock(mHardwareLock);
861 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800862
John Grossmanee578c02012-07-23 17:05:46 -0700863 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
864 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700865 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800866 }
John Grossmanee578c02012-07-23 17:05:46 -0700867 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869
John Grossmanee578c02012-07-23 17:05:46 -0700870 // Now set the master volume in each playback thread. Playback threads
871 // assigned to HALs which do not have master volume support will apply
872 // master volume during the mix operation. Threads with HALs which do
873 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700874 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
875 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
876 continue;
877 }
John Grossmanee578c02012-07-23 17:05:46 -0700878 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700879 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880
881 return NO_ERROR;
882}
883
Glenn Kastenf78aee72012-01-04 11:00:47 -0800884status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885{
Eric Laurenta1884f92011-08-23 08:25:03 -0700886 status_t ret = initCheck();
887 if (ret != NO_ERROR) {
888 return ret;
889 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890
891 // check calling permissions
892 if (!settingsAllowed()) {
893 return PERMISSION_DENIED;
894 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800895 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000896 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 return BAD_VALUE;
898 }
899
900 { // scope for the lock
901 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700902 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700904 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 mHardwareStatus = AUDIO_HW_IDLE;
906 }
907
908 if (NO_ERROR == ret) {
909 Mutex::Autolock _l(mLock);
910 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800911 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700912 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914
915 return ret;
916}
917
918status_t AudioFlinger::setMicMute(bool state)
919{
Eric Laurenta1884f92011-08-23 08:25:03 -0700920 status_t ret = initCheck();
921 if (ret != NO_ERROR) {
922 return ret;
923 }
924
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925 // check calling permissions
926 if (!settingsAllowed()) {
927 return PERMISSION_DENIED;
928 }
929
930 AutoMutex lock(mHardwareLock);
931 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700932 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700933 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
934 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700935 if (result != NO_ERROR) {
936 ret = result;
937 }
938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 mHardwareStatus = AUDIO_HW_IDLE;
940 return ret;
941}
942
943bool AudioFlinger::getMicMute() const
944{
Eric Laurenta1884f92011-08-23 08:25:03 -0700945 status_t ret = initCheck();
946 if (ret != NO_ERROR) {
947 return false;
948 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800949 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700950 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800951 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800953 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700954 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
955 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800956 if (result == NO_ERROR) {
957 mute = mute && state;
958 }
959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800961
962 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963}
964
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800965void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
966{
967 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
968
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800969 AutoMutex lock(mLock);
970 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -0700971 mRecordThreads[i]->setRecordSilenced(uid, silenced);
972 }
973 for (size_t i = 0; i < mMmapThreads.size(); i++) {
974 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800975 }
976}
977
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978status_t AudioFlinger::setMasterMute(bool muted)
979{
John Grossmand8f178d2012-07-20 14:51:35 -0700980 status_t ret = initCheck();
981 if (ret != NO_ERROR) {
982 return ret;
983 }
984
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 // check calling permissions
986 if (!settingsAllowed()) {
987 return PERMISSION_DENIED;
988 }
989
John Grossmanee578c02012-07-23 17:05:46 -0700990 Mutex::Autolock _l(mLock);
991 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700992
John Grossmanee578c02012-07-23 17:05:46 -0700993 // Set master mute in the HALs which support it.
994 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
995 AutoMutex lock(mHardwareLock);
996 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700997
John Grossmanee578c02012-07-23 17:05:46 -0700998 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
999 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001000 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001001 }
John Grossmanee578c02012-07-23 17:05:46 -07001002 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001003 }
1004
John Grossmanee578c02012-07-23 17:05:46 -07001005 // Now set the master mute in each playback thread. Playback threads
1006 // assigned to HALs which do not have master mute support will apply master
1007 // mute during the mix operation. Threads with HALs which do support master
1008 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001009 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1010 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1011 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001012 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013
1014 return NO_ERROR;
1015}
1016
1017float AudioFlinger::masterVolume() const
1018{
Glenn Kasten98067102011-12-13 11:47:54 -08001019 Mutex::Autolock _l(mLock);
1020 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021}
1022
1023bool AudioFlinger::masterMute() const
1024{
Glenn Kasten98067102011-12-13 11:47:54 -08001025 Mutex::Autolock _l(mLock);
1026 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027}
1028
John Grossman4ff14ba2012-02-08 16:37:41 -08001029float AudioFlinger::masterVolume_l() const
1030{
John Grossman4ff14ba2012-02-08 16:37:41 -08001031 return mMasterVolume;
1032}
1033
John Grossmand8f178d2012-07-20 14:51:35 -07001034bool AudioFlinger::masterMute_l() const
1035{
John Grossmanee578c02012-07-23 17:05:46 -07001036 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001037}
1038
Eric Laurent223fd5c2014-11-11 13:43:36 -08001039status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1040{
1041 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001042 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001043 return BAD_VALUE;
1044 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001045 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1046 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1047 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001048 return PERMISSION_DENIED;
1049 }
1050
1051 return NO_ERROR;
1052}
1053
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001054status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1055 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056{
1057 // check calling permissions
1058 if (!settingsAllowed()) {
1059 return PERMISSION_DENIED;
1060 }
1061
Eric Laurent223fd5c2014-11-11 13:43:36 -08001062 status_t status = checkStreamType(stream);
1063 if (status != NO_ERROR) {
1064 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 }
Eric Laurent98e38192018-02-15 18:31:53 -08001066 if (output == AUDIO_IO_HANDLE_NONE) {
1067 return BAD_VALUE;
1068 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001069 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070
1071 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001072 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1073 if (volumeInterface == NULL) {
1074 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 }
Eric Laurent98e38192018-02-15 18:31:53 -08001076 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077
1078 return NO_ERROR;
1079}
1080
Glenn Kastenfff6d712012-01-12 16:38:12 -08001081status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082{
1083 // check calling permissions
1084 if (!settingsAllowed()) {
1085 return PERMISSION_DENIED;
1086 }
1087
Eric Laurent223fd5c2014-11-11 13:43:36 -08001088 status_t status = checkStreamType(stream);
1089 if (status != NO_ERROR) {
1090 return status;
1091 }
1092 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1093
1094 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001095 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 return BAD_VALUE;
1097 }
1098
Eric Laurent93575202011-01-18 18:39:02 -08001099 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001101 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1102 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1103 volumeInterfaces[i]->setStreamMute(stream, muted);
1104 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105
1106 return NO_ERROR;
1107}
1108
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001109float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001111 status_t status = checkStreamType(stream);
1112 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 return 0.0f;
1114 }
Eric Laurent98e38192018-02-15 18:31:53 -08001115 if (output == AUDIO_IO_HANDLE_NONE) {
1116 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 }
1118
Eric Laurent98e38192018-02-15 18:31:53 -08001119 AutoMutex lock(mLock);
1120 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1121 if (volumeInterface == NULL) {
1122 return 0.0f;
1123 }
1124
1125 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126}
1127
Glenn Kastenfff6d712012-01-12 16:38:12 -08001128bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001130 status_t status = checkStreamType(stream);
1131 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 return true;
1133 }
1134
Glenn Kasten6637baa2012-01-09 09:40:36 -08001135 AutoMutex lock(mLock);
1136 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137}
1138
Eric Laurent054d9d32015-04-24 08:48:48 -07001139
1140void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1141{
1142 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1143 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1144 }
1145}
1146
Eric Laurentf1047e82018-04-16 19:18:20 -07001147// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1148// Some keys are used for audio routing and audio path configuration and should be reserved for use
1149// by audio policy and audio flinger for functional, privacy and security reasons.
1150void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1151{
1152 static const String8 kReservedParameters[] = {
1153 String8(AudioParameter::keyRouting),
1154 String8(AudioParameter::keySamplingRate),
1155 String8(AudioParameter::keyFormat),
1156 String8(AudioParameter::keyChannels),
1157 String8(AudioParameter::keyFrameCount),
1158 String8(AudioParameter::keyInputSource),
1159 String8(AudioParameter::keyMonoOutput),
1160 String8(AudioParameter::keyStreamConnect),
1161 String8(AudioParameter::keyStreamDisconnect),
1162 String8(AudioParameter::keyStreamSupportedFormats),
1163 String8(AudioParameter::keyStreamSupportedChannels),
1164 String8(AudioParameter::keyStreamSupportedSamplingRates),
1165 };
1166
Andy Hung4ef19fa2018-05-15 19:35:29 -07001167 if (isAudioServerUid(callingUid)) {
1168 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001169 }
1170
1171 AudioParameter param = AudioParameter(keyValuePairs);
1172 String8 value;
1173 for (auto& key : kReservedParameters) {
1174 if (param.get(key, value) == NO_ERROR) {
1175 ALOGW("%s: filtering key %s value %s from uid %d",
1176 __func__, key.string(), value.string(), callingUid);
1177 param.remove(key);
1178 }
1179 }
1180 keyValuePairs = param.toString();
1181}
1182
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001183status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184{
Eric Laurentf1047e82018-04-16 19:18:20 -07001185 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1186 ioHandle, keyValuePairs.string(),
1187 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001188
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 // check calling permissions
1190 if (!settingsAllowed()) {
1191 return PERMISSION_DENIED;
1192 }
1193
Eric Laurentf1047e82018-04-16 19:18:20 -07001194 String8 filteredKeyValuePairs = keyValuePairs;
1195 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1196
1197 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1198
Glenn Kasten142f5192014-03-25 17:44:59 -07001199 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1200 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001201 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001202 // result will remain NO_INIT if no audio device is present
1203 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001204 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001205 AutoMutex lock(mHardwareLock);
1206 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1207 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001208 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001209 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001210 // return success if at least one audio device accepts the parameters as not all
1211 // HALs are requested to support all parameters. If no audio device supports the
1212 // requested parameters, the last error is reported.
1213 if (final_result != NO_ERROR) {
1214 final_result = result;
1215 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001216 }
1217 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001218 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001219 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001220 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001221 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001222 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1223 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001224 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001225 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001226 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001227 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001228 }
1229 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001230 String8 screenState;
1231 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001232 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001233 if (isOff != (AudioFlinger::mScreenState & 1)) {
1234 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001235 }
1236 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001237 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238 }
1239
1240 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1241 // and the thread is exited once the lock is released
1242 sp<ThreadBase> thread;
1243 {
1244 Mutex::Autolock _l(mLock);
1245 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001246 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001248 if (thread == 0) {
1249 thread = checkMmapThread_l(ioHandle);
1250 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001251 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001252 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001253 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001254 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001255 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1256 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001257 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001259 }
1260 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001261 if (thread != 0) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001262 return thread->setParameters(filteredKeyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263 }
1264 return BAD_VALUE;
1265}
1266
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001267String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001269 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1270 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271
Eric Laurenta4c5a552012-03-29 10:12:40 -07001272 Mutex::Autolock _l(mLock);
1273
Glenn Kasten142f5192014-03-25 17:44:59 -07001274 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001275 String8 out_s8;
1276
Dima Zavin799a70e2011-04-18 16:57:27 -07001277 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001278 String8 s;
1279 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001280 {
1281 AutoMutex lock(mHardwareLock);
1282 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001283 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1284 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001285 mHardwareStatus = AUDIO_HW_IDLE;
1286 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001287 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001288 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001289 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290 }
1291
Eric Laurent6acd1d42017-01-04 14:23:29 -08001292 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1293 if (thread == NULL) {
1294 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1295 if (thread == NULL) {
1296 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1297 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001298 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001299 }
1300 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001302 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303}
1304
Glenn Kastendd8104c2012-07-02 12:42:44 -07001305size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1306 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307{
Eric Laurenta1884f92011-08-23 08:25:03 -07001308 status_t ret = initCheck();
1309 if (ret != NO_ERROR) {
1310 return 0;
1311 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001312 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001313 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001314 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001315 return 0;
1316 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001317
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001318 AutoMutex lock(mHardwareLock);
1319 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001320 audio_config_t config, proposed;
1321 memset(&proposed, 0, sizeof(proposed));
1322 proposed.sample_rate = sampleRate;
1323 proposed.channel_mask = channelMask;
1324 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001325
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001326 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001327 size_t frames;
1328 for (;;) {
1329 // Note: config is currently a const parameter for get_input_buffer_size()
1330 // but we use a copy from proposed in case config changes from the call.
1331 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001332 status_t result = dev->getInputBufferSize(&config, &frames);
1333 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001334 break; // hal success, config is the result
1335 }
1336 // change one parameter of the configuration each iteration to a more "common" value
1337 // to see if the device will support it.
1338 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1339 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1340 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1341 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1342 } else {
1343 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1344 "format %#x, channelMask 0x%X",
1345 sampleRate, format, channelMask);
1346 break; // retries failed, break out of loop with frames == 0.
1347 }
1348 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001349 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001350 if (frames > 0 && config.sample_rate != sampleRate) {
1351 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1352 }
1353 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354}
1355
Glenn Kasten5f972c02014-01-13 09:59:31 -08001356uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001357{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358 Mutex::Autolock _l(mLock);
1359
1360 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1361 if (recordThread != NULL) {
1362 return recordThread->getInputFramesLost();
1363 }
1364 return 0;
1365}
1366
1367status_t AudioFlinger::setVoiceVolume(float value)
1368{
Eric Laurenta1884f92011-08-23 08:25:03 -07001369 status_t ret = initCheck();
1370 if (ret != NO_ERROR) {
1371 return ret;
1372 }
1373
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374 // check calling permissions
1375 if (!settingsAllowed()) {
1376 return PERMISSION_DENIED;
1377 }
1378
1379 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001380 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001381 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001382 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 mHardwareStatus = AUDIO_HW_IDLE;
1384
1385 return ret;
1386}
1387
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001388status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001389 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 Mutex::Autolock _l(mLock);
1392
1393 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1394 if (playbackThread != NULL) {
1395 return playbackThread->getRenderPosition(halFrames, dspFrames);
1396 }
1397
1398 return BAD_VALUE;
1399}
1400
1401void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1402{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001404 if (client == 0) {
1405 return;
1406 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001407 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001408 {
1409 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001410 if (mNotificationClients.indexOfKey(pid) < 0) {
1411 sp<NotificationClient> notificationClient = new NotificationClient(this,
1412 client,
1413 pid);
1414 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415
Eric Laurent021cf962014-05-13 10:18:14 -07001416 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417
Marco Nelissen06b46062014-11-14 07:58:25 -08001418 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001419 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001420 }
1421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422
Eric Laurent021cf962014-05-13 10:18:14 -07001423 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001424 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001425 // the config change is always sent from playback or record threads to avoid deadlock
1426 // with AudioSystem::gLock
1427 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001428 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001429 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001430
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001431 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001432 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433 }
1434}
1435
1436void AudioFlinger::removeNotificationClient(pid_t pid)
1437{
1438 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001439 {
1440 Mutex::Autolock _cl(mClientLock);
1441 mNotificationClients.removeItem(pid);
1442 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001443
Steve Block3856b092011-10-20 11:56:00 +01001444 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001445 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001446 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001447 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001448 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001449 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001450 if (ref->mPid == pid) {
1451 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001452 mAudioSessionRefs.removeAt(i);
1453 delete ref;
1454 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001455 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001456 } else {
1457 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001458 }
1459 }
1460 if (removed) {
1461 purgeStaleEffects_l();
1462 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463}
1464
Eric Laurent73e26b62015-04-27 16:55:58 -07001465void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001466 const sp<AudioIoDescriptor>& ioDesc,
1467 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468{
Eric Laurent021cf962014-05-13 10:18:14 -07001469 Mutex::Autolock _l(mClientLock);
1470 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001472 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1473 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1474 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 }
1476}
1477
Eric Laurent021cf962014-05-13 10:18:14 -07001478// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479void AudioFlinger::removeClient_l(pid_t pid)
1480{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001481 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001482 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 mClients.removeItem(pid);
1484}
1485
Eric Laurent717e1282012-06-29 16:36:52 -07001486// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001487sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1488 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001489{
1490 sp<PlaybackThread> thread;
1491
1492 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1493 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1494 ALOG_ASSERT(thread == 0);
1495 thread = mPlaybackThreads.valueAt(i);
1496 }
1497 }
1498
1499 return thread;
1500}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503
1504// ----------------------------------------------------------------------------
1505
1506AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1507 : RefBase(),
1508 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001509 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510{
Andy Hung6f248bb2018-01-23 14:04:37 -08001511 mMemoryDealer = new MemoryDealer(
1512 audioFlinger->getClientSharedHeapSize(),
1513 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514}
1515
Eric Laurent021cf962014-05-13 10:18:14 -07001516// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517AudioFlinger::Client::~Client()
1518{
1519 mAudioFlinger->removeClient_l(mPid);
1520}
1521
Glenn Kasten435dbe62012-01-30 10:15:48 -08001522sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523{
1524 return mMemoryDealer;
1525}
1526
1527// ----------------------------------------------------------------------------
1528
1529AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1530 const sp<IAudioFlingerClient>& client,
1531 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001532 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533{
1534}
1535
1536AudioFlinger::NotificationClient::~NotificationClient()
1537{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538}
1539
Glenn Kasten0f11b512014-01-31 16:18:54 -08001540void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541{
1542 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001543 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544}
1545
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001546// ----------------------------------------------------------------------------
1547AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1548 : mPendingRequests(false) {}
1549
1550
1551void AudioFlinger::MediaLogNotifier::requestMerge() {
1552 AutoMutex _l(mMutex);
1553 mPendingRequests = true;
1554 mCond.signal();
1555}
1556
1557bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001558 // Should already have been checked, but just in case
1559 if (sMediaLogService == 0) {
1560 return false;
1561 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001562 // Wait until there are pending requests
1563 {
1564 AutoMutex _l(mMutex);
1565 mPendingRequests = false; // to ignore past requests
1566 while (!mPendingRequests) {
1567 mCond.wait(mMutex);
1568 // TODO may also need an exitPending check
1569 }
1570 mPendingRequests = false;
1571 }
1572 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001573 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001574 usleep(kPostTriggerSleepPeriod);
1575 return true;
1576}
1577
1578void AudioFlinger::requestLogMerge() {
1579 mMediaLogNotifier->requestMerge();
1580}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581
1582// ----------------------------------------------------------------------------
1583
Eric Laurentf14db3c2017-12-08 14:20:36 -08001584sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1585 CreateRecordOutput& output,
1586 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587{
1588 sp<RecordThread::RecordTrack> recordTrack;
1589 sp<RecordHandle> recordHandle;
1590 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001592 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001593 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594
Eric Laurentf14db3c2017-12-08 14:20:36 -08001595 output.cblk.clear();
1596 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001597 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001598
Eric Laurentf14db3c2017-12-08 14:20:36 -08001599 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001600 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001601 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001602 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001603 ALOGW_IF(clientUid != callingUid,
1604 "%s uid %d tried to pass itself off as %d",
1605 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001606 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001607 updatePid = true;
1608 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001609 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001610 if (updatePid) {
1611 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001612 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001613 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001614 __func__, callingUid, callingPid, clientPid);
1615 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001616 }
1617
Andy Hung6770c6f2015-04-07 13:43:36 -07001618 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001619 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1620 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001621 lStatus = BAD_VALUE;
1622 goto Exit;
1623 }
1624
Glenn Kasten53b5d092014-02-05 10:00:23 -08001625 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001626 if (!audio_is_input_channel(input.config.channel_mask)) {
1627 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001628 lStatus = BAD_VALUE;
1629 goto Exit;
1630 }
1631
Eric Laurentf14db3c2017-12-08 14:20:36 -08001632 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1633 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1634 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1635 lStatus = BAD_VALUE;
1636 goto Exit;
1637 }
1638
1639 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001640 output.selectedDeviceId = input.selectedDeviceId;
1641 output.flags = input.flags;
1642
1643 client = registerPid(clientPid);
1644
1645 // Not a conventional loop, but a retry loop for at most two iterations total.
1646 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1647 // Exits loop via break on no error of got exit on error
1648 // The sp<> references will be dropped when re-entering scope.
1649 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1650 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001651 // release previously opened input if retrying.
1652 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1653 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001654 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001655 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001656 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001657 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001658 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001659 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1660 sessionId,
1661 // FIXME compare to AudioTrack
1662 clientPid,
1663 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001664 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001665 &input.config,
1666 output.flags, &output.selectedDeviceId, &portId);
1667
Glenn Kasten05997e22014-03-13 15:08:33 -07001668 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001670 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001672 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 lStatus = BAD_VALUE;
1674 goto Exit;
1675 }
1676
Eric Laurentf14db3c2017-12-08 14:20:36 -08001677 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678
Eric Laurentf14db3c2017-12-08 14:20:36 -08001679 output.sampleRate = input.config.sample_rate;
1680 output.frameCount = input.frameCount;
1681 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001682
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001683 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001684 input.config.format, input.config.channel_mask,
1685 &output.frameCount, sessionId,
1686 &output.notificationFrameCount,
1687 clientUid, &output.flags,
1688 input.clientInfo.clientTid,
1689 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001690 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001691
Eric Laurentf14db3c2017-12-08 14:20:36 -08001692 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1693 // audio policy manager without FAST constraint
1694 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001695 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001696 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001697
1698 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001699 goto Exit;
1700 }
1701
1702 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1703 // session and move it to this thread.
1704 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1705 if (chain != 0) {
1706 Mutex::Autolock _l(thread->mLock);
1707 thread->addEffectChain_l(chain);
1708 }
1709 break;
1710 }
1711 // End of retry loop.
1712 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 }
Glenn Kastene198c362013-08-13 09:13:36 -07001714
Eric Laurentf14db3c2017-12-08 14:20:36 -08001715 output.cblk = recordTrack->getCblk();
1716 output.buffers = recordTrack->getBuffers();
1717
1718 // return handle to client
1719 recordHandle = new RecordHandle(recordTrack);
1720
1721Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001722 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001723 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001724 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001725 // Don't hold mClientLock when releasing the reference on the track as the
1726 // destructor will acquire it.
1727 {
1728 Mutex::Autolock _cl(mClientLock);
1729 client.clear();
1730 }
Eric Laurent896c9672017-12-08 14:08:45 -08001731 recordTrack.clear();
1732 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001733 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 }
1736
Glenn Kasten9156ef32013-08-06 15:39:08 -07001737 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 return recordHandle;
1739}
1740
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001741
1742
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743// ----------------------------------------------------------------------------
1744
Eric Laurenta4c5a552012-03-29 10:12:40 -07001745audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1746{
Eric Laurent44622db2014-08-01 19:00:33 -07001747 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001748 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001749 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001750 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001751 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001752 }
1753 Mutex::Autolock _l(mLock);
1754 return loadHwModule_l(name);
1755}
1756
1757// loadHwModule_l() must be called with AudioFlinger::mLock held
1758audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1759{
1760 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1761 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1762 ALOGW("loadHwModule() module %s already loaded", name);
1763 return mAudioHwDevs.keyAt(i);
1764 }
1765 }
1766
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001767 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001768
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001769 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001770 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001771 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001772 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001773 }
1774
1775 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001776 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001777 mHardwareStatus = AUDIO_HW_IDLE;
1778 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001779 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001780 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001781 }
1782
John Grossmanee578c02012-07-23 17:05:46 -07001783 // Check and cache this HAL's level of support for master mute and master
1784 // volume. If this is the first HAL opened, and it supports the get
1785 // methods, use the initial values provided by the HAL as the current
1786 // master mute and volume settings.
1787
1788 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1789 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001790 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001791
1792 if (0 == mAudioHwDevs.size()) {
1793 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001794 float mv;
1795 if (OK == dev->getMasterVolume(&mv)) {
1796 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001797 }
1798
1799 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001800 bool mm;
1801 if (OK == dev->getMasterMute(&mm)) {
1802 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001803 }
1804 }
1805
Eric Laurenta4c5a552012-03-29 10:12:40 -07001806 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001807 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001808 flags = static_cast<AudioHwDevice::Flags>(flags |
1809 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1810 }
1811
1812 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001813 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001814 flags = static_cast<AudioHwDevice::Flags>(flags |
1815 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1816 }
1817
Eric Laurenta4c5a552012-03-29 10:12:40 -07001818 mHardwareStatus = AUDIO_HW_IDLE;
1819 }
1820
Glenn Kastena13cde92016-03-28 15:26:02 -07001821 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001822 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001823
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001824 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001825
1826 return handle;
1827
1828}
1829
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001830// ----------------------------------------------------------------------------
1831
Glenn Kasten3b16c762012-11-14 08:44:39 -08001832uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001833{
1834 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001835 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001836 return thread != NULL ? thread->sampleRate() : 0;
1837}
1838
Glenn Kastene33054e2012-11-14 12:54:39 -08001839size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001840{
1841 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001842 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001843 return thread != NULL ? thread->frameCountHAL() : 0;
1844}
1845
1846// ----------------------------------------------------------------------------
1847
Andy Hung6f248bb2018-01-23 14:04:37 -08001848status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001849{
1850 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001851 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001852 return PERMISSION_DENIED;
1853 }
1854 Mutex::Autolock _l(mLock);
1855 if (mIsDeviceTypeKnown) {
1856 return INVALID_OPERATION;
1857 }
1858 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001859 mTotalMemory = totalMemory;
1860 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1861 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1862 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1863 // though actual setting is determined through device configuration.
1864 constexpr int64_t GB = 1024 * 1024 * 1024;
1865 mClientSharedHeapSize =
1866 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1867 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1868 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1869 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1870 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001871 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001872
1873 // TODO: Cache the client shared heap size in a persistent property.
1874 // It's possible that a native process or Java service or app accesses audioserver
1875 // after it is registered by system server, but before AudioService updates
1876 // the memory info. This would occur immediately after boot or an audioserver
1877 // crash and restore. Before update from AudioService, the client would get the
1878 // minimum heap size.
1879
1880 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1881 (isLowRamDevice ? "true" : "false"),
1882 (long long)mTotalMemory,
1883 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001884 return NO_ERROR;
1885}
1886
Andy Hung6f248bb2018-01-23 14:04:37 -08001887size_t AudioFlinger::getClientSharedHeapSize() const
1888{
1889 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1890 if (heapSizeInBytes != 0) { // read-only property overrides all.
1891 return heapSizeInBytes;
1892 }
1893 return mClientSharedHeapSize;
1894}
1895
Mikhail Naganovdea53042018-04-26 13:10:21 -07001896status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1897{
1898 ALOGV(__func__);
1899
1900 audio_module_handle_t module;
1901 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1902 module = config->ext.device.hw_module;
1903 } else {
1904 module = config->ext.mix.hw_module;
1905 }
1906
1907 Mutex::Autolock _l(mLock);
1908 ssize_t index = mAudioHwDevs.indexOfKey(module);
1909 if (index < 0) {
1910 ALOGW("%s() bad hw module %d", __func__, module);
1911 return BAD_VALUE;
1912 }
1913
1914 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
1915 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
1916}
1917
Eric Laurent93c3d412014-08-01 14:48:35 -07001918audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1919{
1920 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001921
1922 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1923 if (index >= 0) {
1924 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1925 mHwAvSyncIds.valueAt(index), sessionId);
1926 return mHwAvSyncIds.valueAt(index);
1927 }
1928
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001929 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001930 if (dev == NULL) {
1931 return AUDIO_HW_SYNC_INVALID;
1932 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001933 String8 reply;
1934 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001935 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001936 param = AudioParameter(reply);
1937 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001938
1939 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001940 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001941 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1942 return AUDIO_HW_SYNC_INVALID;
1943 }
1944
1945 // allow only one session for a given HW A/V sync ID.
1946 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1947 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1948 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1949 value, mHwAvSyncIds.keyAt(i));
1950 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001951 break;
1952 }
1953 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001954
1955 mHwAvSyncIds.add(sessionId, value);
1956
1957 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1958 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1959 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001960 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001961 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001962 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001963 thread->setParameters(param.toString());
1964 break;
1965 }
1966 }
1967
1968 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1969 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001970}
1971
Eric Laurent72e3f392015-05-20 14:43:50 -07001972status_t AudioFlinger::systemReady()
1973{
1974 Mutex::Autolock _l(mLock);
1975 ALOGI("%s", __FUNCTION__);
1976 if (mSystemReady) {
1977 ALOGW("%s called twice", __FUNCTION__);
1978 return NO_ERROR;
1979 }
1980 mSystemReady = true;
1981 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1982 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1983 thread->systemReady();
1984 }
1985 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1986 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1987 thread->systemReady();
1988 }
1989 return NO_ERROR;
1990}
1991
jiabin46a76fa2018-01-05 10:18:21 -08001992status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
1993{
jiabin9ff780e2018-03-19 18:19:52 -07001994 AutoMutex lock(mHardwareLock);
1995 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1996 status_t status = dev->getMicrophones(microphones);
1997 return status;
jiabin46a76fa2018-01-05 10:18:21 -08001998}
1999
Eric Laurentfa90e842014-10-17 18:12:31 -07002000// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2001void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2002{
2003 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2004 if (index >= 0) {
2005 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2006 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2007 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002008 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002009 thread->setParameters(param.toString());
2010 }
2011}
2012
2013
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002014// ----------------------------------------------------------------------------
2015
Eric Laurent83b88082014-06-20 18:31:16 -07002016
Eric Laurent6acd1d42017-01-04 14:23:29 -08002017sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002018 audio_io_handle_t *output,
2019 audio_config_t *config,
2020 audio_devices_t devices,
2021 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002022 audio_output_flags_t flags)
2023{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002024 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002025 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002026 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002027 }
2028
Eric Laurentcf2c0212014-07-25 16:20:43 -07002029 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002030 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2031 } else {
2032 // Audio Policy does not currently request a specific output handle.
2033 // If this is ever needed, see openInput_l() for example code.
2034 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2035 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002036 }
Eric Laurent83b88082014-06-20 18:31:16 -07002037
2038 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2039
Eric Laurent83b88082014-06-20 18:31:16 -07002040 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002041 // This if statement allows overriding the audio policy settings
2042 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2043 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2044 // Check only for Normal Mixing mode
2045 if (kEnableExtendedPrecision) {
2046 // Specify format (uncomment one below to choose)
2047 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2048 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2049 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2050 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002051 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002052 }
2053 if (kEnableExtendedChannels) {
2054 // Specify channel mask (uncomment one below to choose)
2055 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2056 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2057 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2058 }
Eric Laurent83b88082014-06-20 18:31:16 -07002059 }
2060
Phil Burk062e67a2015-02-11 13:40:50 -08002061 AudioStreamOut *outputStream = NULL;
2062 status_t status = outHwDev->openOutputStream(
2063 &outputStream,
2064 *output,
2065 devices,
2066 flags,
2067 config,
2068 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002069
2070 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002071
Phil Burk062e67a2015-02-11 13:40:50 -08002072 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002073 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2074 sp<MmapPlaybackThread> thread =
2075 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2076 devices, AUDIO_DEVICE_NONE, mSystemReady);
2077 mMmapThreads.add(*output, thread);
2078 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2079 *output, thread.get());
2080 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002081 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002082 sp<PlaybackThread> thread;
2083 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2084 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2085 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2086 *output, thread.get());
2087 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2088 || !isValidPcmSinkFormat(config->format)
2089 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2090 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2091 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2092 *output, thread.get());
2093 } else {
2094 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2095 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2096 *output, thread.get());
2097 }
2098 mPlaybackThreads.add(*output, thread);
2099 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002100 }
Eric Laurent83b88082014-06-20 18:31:16 -07002101 }
2102
2103 return 0;
2104}
2105
Eric Laurentcf2c0212014-07-25 16:20:43 -07002106status_t AudioFlinger::openOutput(audio_module_handle_t module,
2107 audio_io_handle_t *output,
2108 audio_config_t *config,
2109 audio_devices_t *devices,
2110 const String8& address,
2111 uint32_t *latencyMs,
2112 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002114 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2115 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002116 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002117 (devices != NULL) ? *devices : 0,
2118 config->sample_rate,
2119 config->format,
2120 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002121 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002123 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002124 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002126
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 Mutex::Autolock _l(mLock);
2128
Eric Laurent6acd1d42017-01-04 14:23:29 -08002129 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002130 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002131 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2132 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2133 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134
Eric Laurent6acd1d42017-01-04 14:23:29 -08002135 // notify client processes of the new output creation
2136 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002137
Eric Laurent6acd1d42017-01-04 14:23:29 -08002138 // the first primary output opened designates the primary hw device
2139 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002140 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002141 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002142
Eric Laurent6acd1d42017-01-04 14:23:29 -08002143 AutoMutex lock(mHardwareLock);
2144 mHardwareStatus = AUDIO_HW_SET_MODE;
2145 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2146 mHardwareStatus = AUDIO_HW_IDLE;
2147 }
2148 } else {
2149 MmapThread *mmapThread = (MmapThread *)thread.get();
2150 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002151 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002152 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 }
2154
Eric Laurentcf2c0212014-07-25 16:20:43 -07002155 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156}
2157
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002158audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2159 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160{
2161 Mutex::Autolock _l(mLock);
2162 MixerThread *thread1 = checkMixerThread_l(output1);
2163 MixerThread *thread2 = checkMixerThread_l(output2);
2164
2165 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002166 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2167 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002168 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 }
2170
Glenn Kasteneeecb982016-02-26 10:44:04 -08002171 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002172 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 thread->addOutputTrack(thread2);
2174 mPlaybackThreads.add(id, thread);
2175 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002176 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177 return id;
2178}
2179
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002180status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181{
Glenn Kastend96c5722012-04-25 13:44:49 -07002182 return closeOutput_nonvirtual(output);
2183}
2184
2185status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2186{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 // keep strong reference on the playback thread so that
2188 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002189 sp<PlaybackThread> playbackThread;
2190 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 {
2192 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002193 playbackThread = checkPlaybackThread_l(output);
2194 if (playbackThread != NULL) {
2195 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196
Eric Laurent6acd1d42017-01-04 14:23:29 -08002197 if (playbackThread->type() == ThreadBase::MIXER) {
2198 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2199 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2200 DuplicatingThread *dupThread =
2201 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2202 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2203 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 }
2205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206
2207
Eric Laurent6acd1d42017-01-04 14:23:29 -08002208 mPlaybackThreads.removeItem(output);
2209 // save all effects to the default thread
2210 if (mPlaybackThreads.size()) {
2211 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2212 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002213 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002214 Mutex::Autolock _dl(dstThread->mLock);
2215 Mutex::Autolock _sl(playbackThread->mLock);
2216 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2217 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002218 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2219 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221 }
2222 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002223 } else {
2224 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2225 if (mmapThread == 0) {
2226 return BAD_VALUE;
2227 }
2228 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002229 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002231 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2232 ioDesc->mIoHandle = output;
2233 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002235 // The thread entity (active unit of execution) is no longer running here,
2236 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237
Eric Laurent6acd1d42017-01-04 14:23:29 -08002238 if (playbackThread != 0) {
2239 playbackThread->exit();
2240 if (!playbackThread->isDuplicating()) {
2241 closeOutputFinish(playbackThread);
2242 }
2243 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002244 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245 mmapThread->exit();
2246 AudioStreamOut *out = mmapThread->clearOutput();
2247 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2248 // from now on thread->mOutput is NULL
2249 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 }
2251 return NO_ERROR;
2252}
2253
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002254void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002255{
2256 AudioStreamOut *out = thread->clearOutput();
2257 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2258 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002259 delete out;
2260}
2261
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002262void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002263{
2264 mPlaybackThreads.removeItem(thread->mId);
2265 thread->exit();
2266 closeOutputFinish(thread);
2267}
2268
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002269status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270{
2271 Mutex::Autolock _l(mLock);
2272 PlaybackThread *thread = checkPlaybackThread_l(output);
2273
2274 if (thread == NULL) {
2275 return BAD_VALUE;
2276 }
2277
Steve Block3856b092011-10-20 11:56:00 +01002278 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 thread->suspend();
2280
2281 return NO_ERROR;
2282}
2283
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002284status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002285{
2286 Mutex::Autolock _l(mLock);
2287 PlaybackThread *thread = checkPlaybackThread_l(output);
2288
2289 if (thread == NULL) {
2290 return BAD_VALUE;
2291 }
2292
Steve Block3856b092011-10-20 11:56:00 +01002293 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294
2295 thread->restore();
2296
2297 return NO_ERROR;
2298}
2299
Eric Laurentcf2c0212014-07-25 16:20:43 -07002300status_t AudioFlinger::openInput(audio_module_handle_t module,
2301 audio_io_handle_t *input,
2302 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002303 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002304 const String8& address,
2305 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002306 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307{
Eric Laurent83b88082014-06-20 18:31:16 -07002308 Mutex::Autolock _l(mLock);
2309
Glenn Kastene7d66712015-03-05 13:46:52 -08002310 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002311 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002312 }
2313
Eric Laurent6acd1d42017-01-04 14:23:29 -08002314 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002315
2316 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002317 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002318 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002319 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002321 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002322}
Dima Zavin799a70e2011-04-18 16:57:27 -07002323
Eric Laurent6acd1d42017-01-04 14:23:29 -08002324sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002325 audio_io_handle_t *input,
2326 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002327 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002328 const String8& address,
2329 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002330 audio_input_flags_t flags)
2331{
Glenn Kastene7d66712015-03-05 13:46:52 -08002332 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002333 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002334 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002335 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002336 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002337
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002338 // Some flags are specific to framework and must not leak to the HAL.
2339 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2340
Glenn Kasteneeecb982016-02-26 10:44:04 -08002341 // Audio Policy can request a specific handle for hardware hotword.
2342 // The goal here is not to re-open an already opened input.
2343 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002344 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002345 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2346 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2347 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2348 return 0;
2349 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2350 // This should not happen in a transient state with current design.
2351 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2352 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002353 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002354
Eric Laurentcf2c0212014-07-25 16:20:43 -07002355 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002356 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002357 sp<StreamInHalInterface> inStream;
2358 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002359 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002360 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2361 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002362 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002363 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002364 halconfig.sample_rate,
2365 halconfig.format,
2366 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002367 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002368 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002370 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002371 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002372 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002373 audio_is_linear_pcm(config->format) &&
2374 audio_is_linear_pcm(halconfig.format) &&
2375 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002376 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2377 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002378 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002379 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002380 inStream.clear();
2381 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002382 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002383 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 }
2385
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002386 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002387 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002388 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2389 sp<MmapCaptureThread> thread =
2390 new MmapCaptureThread(this, *input,
2391 inHwDev, inputStream,
2392 primaryOutputDevice_l(), devices, mSystemReady);
2393 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002394 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2395 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002396 return thread;
2397 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002398 // Start record thread
2399 // RecordThread requires both input and output device indication to forward to audio
2400 // pre processing modules
2401 sp<RecordThread> thread = new RecordThread(this,
2402 inputStream,
2403 *input,
2404 primaryOutputDevice_l(),
2405 devices,
2406 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002407 );
2408 mRecordThreads.add(*input, thread);
2409 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2410 return thread;
2411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 }
2413
Eric Laurentcf2c0212014-07-25 16:20:43 -07002414 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 return 0;
2416}
2417
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002418status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419{
Glenn Kastend96c5722012-04-25 13:44:49 -07002420 return closeInput_nonvirtual(input);
2421}
2422
2423status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2424{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 // keep strong reference on the record thread so that
2426 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002427 sp<RecordThread> recordThread;
2428 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 {
2430 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002431 recordThread = checkRecordThread_l(input);
2432 if (recordThread != 0) {
2433 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434
Eric Laurent6acd1d42017-01-04 14:23:29 -08002435 // If we still have effect chains, it means that a client still holds a handle
2436 // on at least one effect. We must either move the chain to an existing thread with the
2437 // same session ID or put it aside in case a new record thread is opened for a
2438 // new capture on the same session
2439 sp<EffectChain> chain;
2440 {
2441 Mutex::Autolock _sl(recordThread->mLock);
2442 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2443 // Note: maximum one chain per record thread
2444 if (effectChains.size() != 0) {
2445 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002446 }
2447 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002448 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002449 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002450 // This should only happen in case of overlap between one thread tear down and the
2451 // creation of its replacement
2452 size_t i;
2453 for (i = 0; i < mRecordThreads.size(); i++) {
2454 sp<RecordThread> t = mRecordThreads.valueAt(i);
2455 if (t == recordThread) {
2456 continue;
2457 }
2458 if (t->hasAudioSession(chain->sessionId()) != 0) {
2459 Mutex::Autolock _l(t->mLock);
2460 ALOGV("closeInput() found thread %d for effect session %d",
2461 t->id(), chain->sessionId());
2462 t->addEffectChain_l(chain);
2463 break;
2464 }
2465 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002466 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002467 if (i == mRecordThreads.size()) {
2468 putOrphanEffectChain_l(chain);
2469 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002470 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002471 mRecordThreads.removeItem(input);
2472 } else {
2473 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2474 if (mmapThread == 0) {
2475 return BAD_VALUE;
2476 }
2477 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002478 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002479 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2480 ioDesc->mIoHandle = input;
2481 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 }
Eric Laurent83b88082014-06-20 18:31:16 -07002483 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2484 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002485 if (recordThread != 0) {
2486 closeInputFinish(recordThread);
2487 } else if (mmapThread != 0) {
2488 mmapThread->exit();
2489 AudioStreamIn *in = mmapThread->clearInput();
2490 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2491 // from now on thread->mInput is NULL
2492 delete in;
2493 }
Eric Laurent83b88082014-06-20 18:31:16 -07002494 return NO_ERROR;
2495}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002497void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002498{
2499 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002500 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002501 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002502 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002503 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002504}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002506void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002507{
2508 mRecordThreads.removeItem(thread->mId);
2509 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510}
2511
Glenn Kastend2304db2014-02-03 07:40:31 -08002512status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513{
2514 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002515 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516
2517 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2518 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002519 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002520 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002521 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2522 mMmapThreads[i]->invalidateTracks(stream);
2523 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 return NO_ERROR;
2525}
2526
2527
Glenn Kasteneeecb982016-02-26 10:44:04 -08002528audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529{
Glenn Kasten9d003132016-04-06 14:38:09 -07002530 // This is a binder API, so a malicious client could pass in a bad parameter.
2531 // Check for that before calling the internal API nextUniqueId().
2532 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2533 ALOGE("newAudioUniqueId invalid use %d", use);
2534 return AUDIO_UNIQUE_ID_ALLOCATE;
2535 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002536 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537}
2538
Glenn Kastend848eb42016-03-08 13:42:11 -08002539void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002540{
2541 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002542 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002543 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002544 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2545 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002546 caller = pid;
2547 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002548
Eric Laurent021cf962014-05-13 10:18:14 -07002549 {
2550 Mutex::Autolock _cl(mClientLock);
2551 // Ignore requests received from processes not known as notification client. The request
2552 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2553 // called from a different pid leaving a stale session reference. Also we don't know how
2554 // to clear this reference if the client process dies.
2555 if (mNotificationClients.indexOfKey(caller) < 0) {
2556 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2557 return;
2558 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002559 }
2560
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002561 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002562 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002563 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002564 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2565 ref->mCnt++;
2566 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002567 return;
2568 }
2569 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002570 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2571 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002572}
2573
Glenn Kastend848eb42016-03-08 13:42:11 -08002574void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002575{
2576 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002577 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002578 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002579 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2580 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002581 caller = pid;
2582 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002583 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002584 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002585 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002586 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2587 ref->mCnt--;
2588 ALOGV(" decremented refcount to %d", ref->mCnt);
2589 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002590 mAudioSessionRefs.removeAt(i);
2591 delete ref;
2592 purgeStaleEffects_l();
2593 }
2594 return;
2595 }
2596 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002597 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002598 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002599 ALOGW_IF(!isAudioServerUid(callerUid),
2600 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002601}
2602
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002603bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2604{
2605 size_t num = mAudioSessionRefs.size();
2606 for (size_t i = 0; i < num; i++) {
2607 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2608 if (ref->mSessionid == audioSession) {
2609 return true;
2610 }
2611 }
2612 return false;
2613}
2614
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002615void AudioFlinger::purgeStaleEffects_l() {
2616
Steve Block3856b092011-10-20 11:56:00 +01002617 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002618
2619 Vector< sp<EffectChain> > chains;
2620
2621 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2622 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002623 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002624 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2625 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002626 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2627 chains.push(ec);
2628 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002629 }
2630 }
2631 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2632 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002633 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002634 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2635 sp<EffectChain> ec = t->mEffectChains[j];
2636 chains.push(ec);
2637 }
2638 }
2639
2640 for (size_t i = 0; i < chains.size(); i++) {
2641 sp<EffectChain> ec = chains[i];
2642 int sessionid = ec->sessionId();
2643 sp<ThreadBase> t = ec->mThread.promote();
2644 if (t == 0) {
2645 continue;
2646 }
2647 size_t numsessionrefs = mAudioSessionRefs.size();
2648 bool found = false;
2649 for (size_t k = 0; k < numsessionrefs; k++) {
2650 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002651 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002652 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002653 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002654 found = true;
2655 break;
2656 }
2657 }
2658 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002659 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002660 // remove all effects from the chain
2661 while (ec->mEffects.size()) {
2662 sp<EffectModule> effect = ec->mEffects[0];
2663 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002664 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002665 if (effect->purgeHandles()) {
2666 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002667 }
2668 AudioSystem::unregisterEffect(effect->id());
2669 }
2670 }
2671 }
2672 return;
2673}
2674
Glenn Kasteneeecb982016-02-26 10:44:04 -08002675// checkThread_l() must be called with AudioFlinger::mLock held
2676AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2677{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002678 ThreadBase *thread = checkMmapThread_l(ioHandle);
2679 if (thread == 0) {
2680 switch (audio_unique_id_get_use(ioHandle)) {
2681 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2682 thread = checkPlaybackThread_l(ioHandle);
2683 break;
2684 case AUDIO_UNIQUE_ID_USE_INPUT:
2685 thread = checkRecordThread_l(ioHandle);
2686 break;
2687 default:
2688 break;
2689 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002690 }
2691 return thread;
2692}
2693
Mathias Agopian65ab4712010-07-14 17:59:35 -07002694// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002695AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696{
Glenn Kastena1117922012-01-26 10:53:32 -08002697 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698}
2699
2700// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002701AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702{
2703 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002704 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705}
2706
2707// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002708AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709{
Glenn Kastena1117922012-01-26 10:53:32 -08002710 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711}
2712
Eric Laurent6acd1d42017-01-04 14:23:29 -08002713// checkMmapThread_l() must be called with AudioFlinger::mLock held
2714AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2715{
2716 return mMmapThreads.valueFor(io).get();
2717}
2718
2719
2720// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2721AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2722{
Eric Laurent7459b902017-04-19 18:10:41 -07002723 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002724 if (volumeInterface == nullptr) {
2725 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2726 if (mmapThread != nullptr) {
2727 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002728 MmapPlaybackThread *mmapPlaybackThread =
2729 static_cast<MmapPlaybackThread *>(mmapThread);
2730 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002731 }
2732 }
2733 }
2734 return volumeInterface;
2735}
2736
2737Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2738{
2739 Vector <VolumeInterface *> volumeInterfaces;
2740 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002741 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002742 }
2743 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2744 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002745 MmapPlaybackThread *mmapPlaybackThread =
2746 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2747 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002748 }
2749 }
2750 return volumeInterfaces;
2751}
2752
Glenn Kasteneeecb982016-02-26 10:44:04 -08002753audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754{
Glenn Kasten9d003132016-04-06 14:38:09 -07002755 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002756 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002757 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2758 for (int retry = 0; retry < maxRetries; retry++) {
2759 // The cast allows wraparound from max positive to min negative instead of abort
2760 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2761 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2762 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2763 // allow wrap by skipping 0 and -1 for session ids
2764 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2765 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2766 return (audio_unique_id_t) (base | use);
2767 }
2768 }
2769 // We have no way of recovering from wraparound
2770 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2771 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772}
2773
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002774AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002775{
2776 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2777 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002778 if(thread->isDuplicating()) {
2779 continue;
2780 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002781 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002782 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002783 return thread;
2784 }
2785 }
2786 return NULL;
2787}
2788
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002789audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002790{
2791 PlaybackThread *thread = primaryPlaybackThread_l();
2792
2793 if (thread == NULL) {
2794 return 0;
2795 }
2796
Eric Laurentf1c04f92012-08-28 14:26:53 -07002797 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002798}
2799
Glenn Kastena7335632016-06-09 17:09:53 -07002800AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2801{
2802 size_t minFrameCount = 0;
2803 PlaybackThread *minThread = NULL;
2804 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2805 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2806 if (!thread->isDuplicating()) {
2807 size_t frameCount = thread->frameCountHAL();
2808 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2809 (frameCount == minFrameCount && thread->hasFastMixer() &&
2810 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2811 minFrameCount = frameCount;
2812 minThread = thread;
2813 }
2814 }
2815 }
2816 return minThread;
2817}
2818
Eric Laurenta011e352012-03-29 15:51:43 -07002819sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002820 audio_session_t triggerSession,
2821 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002822 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002823 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002824{
2825 Mutex::Autolock _l(mLock);
2826
2827 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2828 status_t playStatus = NAME_NOT_FOUND;
2829 status_t recStatus = NAME_NOT_FOUND;
2830 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2831 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2832 if (playStatus == NO_ERROR) {
2833 return event;
2834 }
2835 }
2836 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2837 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2838 if (recStatus == NO_ERROR) {
2839 return event;
2840 }
2841 }
2842 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2843 mPendingSyncEvents.add(event);
2844 } else {
2845 ALOGV("createSyncEvent() invalid event %d", event->type());
2846 event.clear();
2847 }
2848 return event;
2849}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002850
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851// ----------------------------------------------------------------------------
2852// Effect management
2853// ----------------------------------------------------------------------------
2854
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002855sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2856 return mEffectsFactoryHal;
2857}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858
Glenn Kastenf587ba52012-01-26 16:25:10 -08002859status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860{
2861 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002862 if (mEffectsFactoryHal.get()) {
2863 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2864 } else {
2865 return -ENODEV;
2866 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867}
2868
Glenn Kastenf587ba52012-01-26 16:25:10 -08002869status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870{
2871 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002872 if (mEffectsFactoryHal.get()) {
2873 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2874 } else {
2875 return -ENODEV;
2876 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877}
2878
Glenn Kasten5e92a782012-01-30 07:40:52 -08002879status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002880 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881{
2882 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002883 if (mEffectsFactoryHal.get()) {
2884 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2885 } else {
2886 return -ENODEV;
2887 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888}
2889
2890
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002891sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 effect_descriptor_t *pDesc,
2893 const sp<IEffectClient>& effectClient,
2894 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002895 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002896 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002897 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002898 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002899 status_t *status,
2900 int *id,
2901 int *enabled)
2902{
2903 status_t lStatus = NO_ERROR;
2904 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906
Eric Laurentb6436272016-12-07 19:24:50 -08002907 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002908 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08002909 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2910 ALOGW_IF(pid != -1 && pid != callingPid,
2911 "%s uid %d pid %d tried to pass itself off as pid %d",
2912 __func__, callingUid, callingPid, pid);
2913 pid = callingPid;
2914 }
2915
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002916 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2917 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918
2919 if (pDesc == NULL) {
2920 lStatus = BAD_VALUE;
2921 goto Exit;
2922 }
2923
Eric Laurent84e9a102010-09-23 16:10:16 -07002924 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002925 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002926 lStatus = PERMISSION_DENIED;
2927 goto Exit;
2928 }
2929
Dima Zavinfce7a472011-04-19 22:30:36 -07002930 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07002931 // that can only be created by audio policy manager
2932 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002933 lStatus = PERMISSION_DENIED;
2934 goto Exit;
2935 }
2936
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002937 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002938 lStatus = NO_INIT;
2939 goto Exit;
2940 }
2941
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002943 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002945 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002947 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948 goto Exit;
2949 }
2950 } else {
2951 // if uuid is not specified, look for an available implementation
2952 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002953 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002954 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955 lStatus = BAD_VALUE;
2956 goto Exit;
2957 }
2958 uint32_t numEffects = 0;
2959 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002960 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961 bool found = false;
2962
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002963 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002965 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966 goto Exit;
2967 }
2968 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002969 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002971 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 continue;
2973 }
2974 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2975 // If matching type found save effect descriptor. If the session is
2976 // 0 and the effect is not auxiliary, continue enumeration in case
2977 // an auxiliary version of this effect type is available
2978 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002979 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002980 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2982 break;
2983 }
2984 }
2985 }
2986 if (!found) {
2987 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002988 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989 goto Exit;
2990 }
2991 // For same effect type, chose auxiliary version over insert version if
2992 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002993 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002995 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002996 }
2997 }
2998
2999 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003000 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3002 lStatus = INVALID_OPERATION;
3003 goto Exit;
3004 }
3005
Eric Laurent59255e42011-07-27 19:49:51 -07003006 // check recording permission for visualizer
3007 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003008 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003009 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003010 lStatus = PERMISSION_DENIED;
3011 goto Exit;
3012 }
3013
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003015 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003016 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003017 // if the output returned by getOutputForEffect() is removed before we lock the
3018 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3019 // and we will exit safely
3020 io = AudioSystem::getOutputForEffect(&desc);
3021 ALOGV("createEffect got output %d", io);
3022 }
3023
3024 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025
3026 // If output is not specified try to find a matching audio session ID in one of the
3027 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003028 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3029 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003030 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003031 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003032 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3033 // output must be specified by AudioPolicyManager when using session
3034 // AUDIO_SESSION_OUTPUT_STAGE
3035 lStatus = BAD_VALUE;
3036 goto Exit;
3037 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003038 // look for the thread where the specified audio session is present
3039 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3040 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3041 io = mPlaybackThreads.keyAt(i);
3042 break;
3043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003045 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003046 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3047 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3048 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003049 break;
3050 }
3051 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003052 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003053 if (io == AUDIO_IO_HANDLE_NONE) {
3054 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3055 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3056 io = mMmapThreads.keyAt(i);
3057 break;
3058 }
3059 }
3060 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003061 // If no output thread contains the requested session ID, default to
3062 // first output. The effect chain will be moved to the correct output
3063 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003064 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003065 io = mPlaybackThreads.keyAt(0);
3066 }
Steve Block3856b092011-10-20 11:56:00 +01003067 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003068 }
3069 ThreadBase *thread = checkRecordThread_l(io);
3070 if (thread == NULL) {
3071 thread = checkPlaybackThread_l(io);
3072 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003073 thread = checkMmapThread_l(io);
3074 if (thread == NULL) {
3075 ALOGE("createEffect() unknown output thread");
3076 lStatus = BAD_VALUE;
3077 goto Exit;
3078 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003079 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003080 } else {
3081 // Check if one effect chain was awaiting for an effect to be created on this
3082 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003083 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003084 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003085 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003086 thread->addEffectChain_l(chain);
3087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003089
Eric Laurent021cf962014-05-13 10:18:14 -07003090 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003092 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003093 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003094 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003095 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003096 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003097 // remove local strong reference to Client with mClientLock held
3098 Mutex::Autolock _cl(mClientLock);
3099 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003100 } else {
3101 // handle must be valid here, but check again to be safe.
3102 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 }
3105
haobo101735295ff7b0d2017-03-17 17:44:03 +08003106 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3107 // handle must be cleared outside lock.
3108 handle.clear();
3109 }
3110
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003112 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113 return handle;
3114}
3115
Glenn Kastend848eb42016-03-08 13:42:11 -08003116status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003117 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003118{
Steve Block3856b092011-10-20 11:56:00 +01003119 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003120 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003121 Mutex::Autolock _l(mLock);
3122 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003123 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003124 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 }
Eric Laurentde070132010-07-13 04:45:46 -07003126 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3127 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003128 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003129 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130 }
Eric Laurentde070132010-07-13 04:45:46 -07003131 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3132 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003133 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003134 return BAD_VALUE;
3135 }
3136
3137 Mutex::Autolock _dl(dstThread->mLock);
3138 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003139 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140}
3141
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003142// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003143status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003144 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003145 AudioFlinger::PlaybackThread *dstThread,
3146 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003147{
Steve Block3856b092011-10-20 11:56:00 +01003148 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003149 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003150
Eric Laurent59255e42011-07-27 19:49:51 -07003151 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003152 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003153 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003154 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003155 return INVALID_OPERATION;
3156 }
3157
Eric Laurent4c415062016-06-17 16:14:16 -07003158 // Check whether the destination thread and all effects in the chain are compatible
3159 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003160 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003161 " destination thread %p is not compatible with effects in the chain",
3162 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003163 return INVALID_OPERATION;
3164 }
3165
Eric Laurent39e94f82010-07-28 01:32:47 -07003166 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003167 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003168 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003169 // removed.
3170 srcThread->removeEffectChain_l(chain);
3171
3172 // transfer all effects one by one so that new effect chain is created on new thread with
3173 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003174 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003175 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003176 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003177 Vector< sp<EffectModule> > removed;
3178 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003179 while (effect != 0) {
3180 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003181 removed.add(effect);
3182 status = dstThread->addEffect_l(effect);
3183 if (status != NO_ERROR) {
3184 break;
3185 }
Eric Laurentec35a142011-10-05 17:42:25 -07003186 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3187 if (effect->state() == EffectModule::ACTIVE ||
3188 effect->state() == EffectModule::STOPPING) {
3189 effect->start();
3190 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003191 // if the move request is not received from audio policy manager, the effect must be
3192 // re-registered with the new strategy and output
3193 if (dstChain == 0) {
3194 dstChain = effect->chain().promote();
3195 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003196 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003197 status = NO_INIT;
3198 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003199 }
3200 strategy = dstChain->strategy();
3201 }
3202 if (reRegister) {
3203 AudioSystem::unregisterEffect(effect->id());
3204 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003205 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003206 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003207 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003208 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003209 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003210 }
Eric Laurentde070132010-07-13 04:45:46 -07003211 effect = chain->getEffectFromId_l(0);
3212 }
3213
Eric Laurent5baf2af2013-09-12 17:37:00 -07003214 if (status != NO_ERROR) {
3215 for (size_t i = 0; i < removed.size(); i++) {
3216 srcThread->addEffect_l(removed[i]);
3217 if (dstChain != 0 && reRegister) {
3218 AudioSystem::unregisterEffect(removed[i]->id());
3219 AudioSystem::registerEffect(&removed[i]->desc(),
3220 srcThread->id(),
3221 strategy,
3222 sessionId,
3223 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003224 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003225 }
3226 }
3227 }
3228
3229 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230}
3231
Eric Laurent5baf2af2013-09-12 17:37:00 -07003232bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003233{
3234 if (mGlobalEffectEnableTime != 0 &&
3235 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3236 return true;
3237 }
3238
3239 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3240 sp<EffectChain> ec =
3241 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003242 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003243 return true;
3244 }
3245 }
3246 return false;
3247}
3248
Eric Laurent5baf2af2013-09-12 17:37:00 -07003249void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003250{
3251 Mutex::Autolock _l(mLock);
3252
3253 mGlobalEffectEnableTime = systemTime();
3254
3255 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3256 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3257 if (t->mType == ThreadBase::OFFLOAD) {
3258 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3259 }
3260 }
3261
3262}
3263
Eric Laurentaaa44472014-09-12 17:41:50 -07003264status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3265{
Eric Laurentd8365c52017-07-16 15:27:05 -07003266 // clear possible suspended state before parking the chain so that it starts in default state
3267 // when attached to a new record thread
3268 chain->setEffectSuspended_l(FX_IID_AEC, false);
3269 chain->setEffectSuspended_l(FX_IID_NS, false);
3270
Glenn Kastend848eb42016-03-08 13:42:11 -08003271 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003272 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003273 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003274 if (index >= 0) {
3275 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3276 return ALREADY_EXISTS;
3277 }
3278 mOrphanEffectChains.add(session, chain);
3279 return NO_ERROR;
3280}
3281
3282sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3283{
3284 sp<EffectChain> chain;
3285 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003286 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003287 if (index >= 0) {
3288 chain = mOrphanEffectChains.valueAt(index);
3289 mOrphanEffectChains.removeItemsAt(index);
3290 }
3291 return chain;
3292}
3293
3294bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3295{
3296 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003297 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003298 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003299 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003300 if (index >= 0) {
3301 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003302 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003303 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003304 mOrphanEffectChains.removeItemsAt(index);
3305 }
3306 return true;
3307 }
3308 return false;
3309}
3310
3311
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312// ----------------------------------------------------------------------------
3313
3314status_t AudioFlinger::onTransact(
3315 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3316{
3317 return BnAudioFlinger::onTransact(code, data, reply, flags);
3318}
3319
Glenn Kasten63238ef2015-03-02 15:50:29 -08003320} // namespace android