blob: 9d1142fa97f0fa60eb5a022622b82acfbfee3f8c [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>
Eric Laurentf1047e82018-04-16 19:18:20 -070031#include <cutils/multiuser.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070033#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070035#include <media/audiohal/DeviceHalInterface.h>
36#include <media/audiohal/DevicesFactoryHalInterface.h>
37#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070038#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070040#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <utils/String16.h>
42#include <utils/threads.h>
43
Steven Morelandf0c02ce2018-02-23 14:53:55 -080044#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070050#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_visualizer.h>
55#include <system/audio_effects/effect_ns.h>
56#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten9e58b552013-01-18 15:09:48 -080062#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070063#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080064#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070066#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070068#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080074#include "TypedLogger.h"
75
Mathias Agopian65ab4712010-07-14 17:59:35 -070076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
John Grossman1c345192012-03-27 14:00:17 -070078// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
Eric Laurentde070132010-07-13 04:45:46 -070090
Mathias Agopian65ab4712010-07-14 17:59:35 -070091namespace android {
92
Glenn Kastenec1d6b52011-12-12 09:04:45 -080093static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
94static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070095static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070096static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten58912562012-04-03 10:45:00 -070098
John Grossman4ff14ba2012-02-08 16:37:41 -080099nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700102
Eric Laurent813e2a72013-08-31 12:59:48 -0700103// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
104// we define a minimum time during which a global effect is considered enabled.
105static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
106
Eric Laurentfc235202016-12-20 18:48:17 -0800107Mutex gLock;
108wp<AudioFlinger> gAudioFlinger;
109
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700110// Keep a strong reference to media.log service around forever.
111// The service is within our parent process so it can never die in a way that we could observe.
112// These two variables are const after initialization.
113static sp<IBinder> sMediaLogServiceAsBinder;
114static sp<IMediaLogService> sMediaLogService;
115
116static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
117
118static void sMediaLogInit()
119{
120 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
121 if (sMediaLogServiceAsBinder != 0) {
122 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
123 }
124}
125
Mathias Agopian65ab4712010-07-14 17:59:35 -0700126// ----------------------------------------------------------------------------
127
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700128std::string formatToString(audio_format_t format) {
129 std::string result;
130 FormatConverter::toString(format, result);
131 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800132}
133
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134// ----------------------------------------------------------------------------
135
136AudioFlinger::AudioFlinger()
137 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800138 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800139 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800140 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700141 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800142 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800143 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700144 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800145 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700146 mBtNrecIsOff(false),
147 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700148 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800149 mTotalMemory(0),
150 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700151 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700152 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700153 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700154{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700155 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
156 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
157 // zero ID has a special meaning, so unavailable
158 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
159 }
160
Glenn Kasten949a9262013-04-16 12:35:20 -0700161 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800162 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800163 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800164 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
165 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700166 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800167 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700168
Wei Jia3f273d12015-11-24 09:06:49 -0800169 // reset battery stats.
170 // if the audio service has crashed, battery stats could be left
171 // in bad state, reset the state upon service start.
172 BatteryNotifier::getInstance().noteResetAudio();
173
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700174 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700175 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
176
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800177 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700178}
179
180void AudioFlinger::onFirstRef()
181{
Eric Laurent93575202011-01-18 18:39:02 -0800182 Mutex::Autolock _l(mLock);
183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800185 char val_str[PROPERTY_VALUE_MAX] = { 0 };
186 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
187 uint32_t int_val;
188 if (1 == sscanf(val_str, "%u", &int_val)) {
189 mStandbyTimeInNsecs = milliseconds(int_val);
190 ALOGI("Using %u mSec as standby time.", int_val);
191 } else {
192 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
193 ALOGI("Using default %u mSec as standby time.",
194 (uint32_t)(mStandbyTimeInNsecs / 1000000));
195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
Eric Laurenta4c5a552012-03-29 10:12:40 -0700198 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800199
200 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201}
202
203AudioFlinger::~AudioFlinger()
204{
205 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700206 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700207 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208 }
209 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700210 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700211 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700213
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800214 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
215 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700216 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700218
219 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700220 if (sMediaLogService != 0) {
221 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
222 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
223 mUnregisteredWriters.pop();
224 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700225 }
226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227}
228
Eric Laurentfc235202016-12-20 18:48:17 -0800229//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800230__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800231status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
232 const audio_attributes_t *attr,
233 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700234 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800235 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800236 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800237 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700238 sp<MmapStreamInterface>& interface,
239 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800240{
241 sp<AudioFlinger> af;
242 {
243 Mutex::Autolock _l(gLock);
244 af = gAudioFlinger.promote();
245 }
246 status_t ret = NO_INIT;
247 if (af != 0) {
248 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800249 direction, attr, config, client, deviceId,
250 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800251 }
252 return ret;
253}
254
Eric Laurent6acd1d42017-01-04 14:23:29 -0800255status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
256 const audio_attributes_t *attr,
257 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700258 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800259 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800260 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800261 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700262 sp<MmapStreamInterface>& interface,
263 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800264{
265 status_t ret = initCheck();
266 if (ret != NO_ERROR) {
267 return ret;
268 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800269 audio_session_t actualSessionId = *sessionId;
270 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
271 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
272 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800273 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700274 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800275 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
276 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
277 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
278 fullConfig.sample_rate = config->sample_rate;
279 fullConfig.channel_mask = config->channel_mask;
280 fullConfig.format = config->format;
281 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800282 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200283 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800284 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800285 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
286 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700287 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800288 } else {
289 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800290 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800291 client.clientPid,
292 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800293 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800294 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700295 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800296 }
297 if (ret != NO_ERROR) {
298 return ret;
299 }
300
301 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
302 // audio policy manager and we can retrieve it
303 sp<MmapThread> thread = mMmapThreads.valueFor(io);
304 if (thread != 0) {
305 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800306 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700307 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800308 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800309 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700310 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800311 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700312 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800313 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700314 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800315 ret = NO_INIT;
316 }
317
318 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
319
Eric Laurentfc235202016-12-20 18:48:17 -0800320 return ret;
321}
322
Eric Laurenta4c5a552012-03-29 10:12:40 -0700323static const char * const audio_interfaces[] = {
324 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
325 AUDIO_HARDWARE_MODULE_ID_A2DP,
326 AUDIO_HARDWARE_MODULE_ID_USB,
327};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700328
Phil Burk062e67a2015-02-11 13:40:50 -0800329AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700330 audio_module_handle_t module,
331 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700332{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700333 // if module is 0, the request comes from an old policy manager and we should load
334 // well known modules
335 if (module == 0) {
336 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700337 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700338 loadHwModule_l(audio_interfaces[i]);
339 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700340 // then try to find a module supporting the requested device.
341 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
342 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700343 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
344 uint32_t supportedDevices;
345 if (dev->getSupportedDevices(&supportedDevices) == OK &&
346 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700347 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700348 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700349 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700350 } else {
351 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700352 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
353 if (audioHwDevice != NULL) {
354 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355 }
356 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700357
Dima Zavin799a70e2011-04-18 16:57:27 -0700358 return NULL;
359}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360
Glenn Kasten0f11b512014-01-31 16:18:54 -0800361void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362{
363 const size_t SIZE = 256;
364 char buffer[SIZE];
365 String8 result;
366
367 result.append("Clients:\n");
368 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800369 sp<Client> client = mClients.valueAt(i).promote();
370 if (client != 0) {
371 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
372 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 }
374 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700375
Eric Laurentd1b28d42013-09-18 18:47:13 -0700376 result.append("Notification Clients:\n");
377 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
378 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
379 result.append(buffer);
380 }
381
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700382 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800383 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700384 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
385 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800386 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700387 result.append(buffer);
388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700389 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390}
391
392
Glenn Kasten0f11b512014-01-31 16:18:54 -0800393void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700394{
395 const size_t SIZE = 256;
396 char buffer[SIZE];
397 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800398 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399
John Grossman4ff14ba2012-02-08 16:37:41 -0800400 snprintf(buffer, SIZE, "Hardware status: %d\n"
401 "Standby Time mSec: %u\n",
402 hardwareStatus,
403 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 result.append(buffer);
405 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406}
407
Glenn Kasten0f11b512014-01-31 16:18:54 -0800408void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
412 String8 result;
413 snprintf(buffer, SIZE, "Permission Denial: "
414 "can't dump AudioFlinger from pid=%d, uid=%d\n",
415 IPCThreadState::self()->getCallingPid(),
416 IPCThreadState::self()->getCallingUid());
417 result.append(buffer);
418 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419}
420
Eric Laurent81784c32012-11-19 14:55:58 -0800421bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422{
423 bool locked = false;
424 for (int i = 0; i < kDumpLockRetries; ++i) {
425 if (mutex.tryLock() == NO_ERROR) {
426 locked = true;
427 break;
428 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800429 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700430 }
431 return locked;
432}
433
434status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
435{
Glenn Kasten44deb052012-02-05 18:09:08 -0800436 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 dumpPermissionDenial(fd, args);
438 } else {
439 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800440 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 if (!hardwareLocked) {
442 String8 result(kHardwareLockedString);
443 write(fd, result.string(), result.size());
444 } else {
445 mHardwareLock.unlock();
446 }
447
Eric Laurent81784c32012-11-19 14:55:58 -0800448 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449
450 // failed to lock - AudioFlinger is probably deadlocked
451 if (!locked) {
452 String8 result(kDeadlockedString);
453 write(fd, result.string(), result.size());
454 }
455
Eric Laurent021cf962014-05-13 10:18:14 -0700456 bool clientLocked = dumpTryLock(mClientLock);
457 if (!clientLocked) {
458 String8 result(kClientLockedString);
459 write(fd, result.string(), result.size());
460 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700461
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700462 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700463 mEffectsFactoryHal->dumpEffects(fd);
464 } else {
465 String8 result(kNoEffectsFactory);
466 write(fd, result.string(), result.size());
467 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700468
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700470 if (clientLocked) {
471 mClientLock.unlock();
472 }
473
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 dumpInternals(fd, args);
475
476 // dump playback threads
477 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
478 mPlaybackThreads.valueAt(i)->dump(fd, args);
479 }
480
481 // dump record threads
482 for (size_t i = 0; i < mRecordThreads.size(); i++) {
483 mRecordThreads.valueAt(i)->dump(fd, args);
484 }
485
Eric Laurent6acd1d42017-01-04 14:23:29 -0800486 // dump mmap threads
487 for (size_t i = 0; i < mMmapThreads.size(); i++) {
488 mMmapThreads.valueAt(i)->dump(fd, args);
489 }
490
Eric Laurentaaa44472014-09-12 17:41:50 -0700491 // dump orphan effect chains
492 if (mOrphanEffectChains.size() != 0) {
493 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
494 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
495 mOrphanEffectChains.valueAt(i)->dump(fd, args);
496 }
497 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700498 // dump all hardware devs
499 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700500 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
501 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700503
Mikhail Naganov201369b2018-05-16 16:52:32 -0700504 mPatchPanel.dump(fd);
505
rago3bd1c872016-09-26 12:58:14 -0700506 BUFLOG_RESET;
507
Glenn Kastend65d73c2012-06-22 17:21:07 -0700508 if (locked) {
509 mLock.unlock();
510 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800511
Andy Hung8946a282018-04-19 20:04:56 -0700512#ifdef TEE_SINK
513 // NBAIO_Tee dump is safe to call outside of AF lock.
514 NBAIO_Tee::dumpAll(fd, "_DUMP");
515#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800516 // append a copy of media.log here by forwarding fd to it, but don't attempt
517 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700518 if (sMediaLogServiceAsBinder != 0) {
519 dprintf(fd, "\nmedia.log:\n");
520 Vector<String16> args;
521 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800522 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700523
524 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700525 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700526 bool unreachableMemory = false;
527 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700528 if (arg == String16("-m")) {
529 dumpMem = true;
530 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700531 unreachableMemory = true;
532 }
533 }
534
Andy Hung07b745e2016-05-23 16:21:07 -0700535 if (dumpMem) {
536 dprintf(fd, "\nDumping memory:\n");
537 std::string s = dumpMemoryAddresses(100 /* limit */);
538 write(fd, s.c_str(), s.size());
539 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700540 if (unreachableMemory) {
541 dprintf(fd, "\nDumping unreachable memory:\n");
542 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700543 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700544 write(fd, s.c_str(), s.size());
545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 }
547 return NO_ERROR;
548}
549
Eric Laurent021cf962014-05-13 10:18:14 -0700550sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800551{
Eric Laurent021cf962014-05-13 10:18:14 -0700552 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800553 // If pid is already in the mClients wp<> map, then use that entry
554 // (for which promote() is always != 0), otherwise create a new entry and Client.
555 sp<Client> client = mClients.valueFor(pid).promote();
556 if (client == 0) {
557 client = new Client(this, pid);
558 mClients.add(pid, client);
559 }
560
561 return client;
562}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563
Glenn Kasten9e58b552013-01-18 15:09:48 -0800564sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
565{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700566 // If there is no memory allocated for logs, return a dummy writer that does nothing.
567 // Similarly if we can't contact the media.log service, also return a dummy writer.
568 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800569 return new NBLog::Writer();
570 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700571 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
572 // If allocation fails, consult the vector of previously unregistered writers
573 // and garbage-collect one or more them until an allocation succeeds
574 if (shared == 0) {
575 Mutex::Autolock _l(mUnregisteredWritersLock);
576 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
577 {
578 // Pick the oldest stale writer to garbage-collect
579 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
580 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700581 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700582 // Now the media.log remote reference to IMemory is gone. When our last local
583 // reference to IMemory also drops to zero at end of this block,
584 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
585 }
586 // Re-attempt the allocation
587 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
588 if (shared != 0) {
589 goto success;
590 }
591 }
592 // Even after garbage-collecting all old writers, there is still not enough memory,
593 // so return a dummy writer
594 return new NBLog::Writer();
595 }
596success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800597 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
598 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
599 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700600 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800601 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800602}
603
604void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
605{
Glenn Kasten685ef092013-02-04 08:15:34 -0800606 if (writer == 0) {
607 return;
608 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800609 sp<IMemory> iMemory(writer->getIMemory());
610 if (iMemory == 0) {
611 return;
612 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700613 // Rather than removing the writer immediately, append it to a queue of old writers to
614 // be garbage-collected later. This allows us to continue to view old logs for a while.
615 Mutex::Autolock _l(mUnregisteredWritersLock);
616 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800617}
618
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619// IAudioFlinger interface
620
Eric Laurent21da6472017-11-09 16:29:26 -0800621sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
622 CreateTrackOutput& output,
623 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624{
625 sp<PlaybackThread::Track> track;
626 sp<TrackHandle> trackHandle;
627 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800629 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800630 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631
Eric Laurent21da6472017-11-09 16:29:26 -0800632 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700633 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800634 uid_t clientUid = input.clientInfo.clientUid;
635 if (!isTrustedCallingUid(callingUid)) {
636 ALOGW_IF(clientUid != callingUid,
637 "%s uid %d tried to pass itself off as %d",
638 __FUNCTION__, callingUid, clientUid);
639 clientUid = callingUid;
640 updatePid = true;
641 }
642 pid_t clientPid = input.clientInfo.clientPid;
643 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700644 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800645 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700646 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800647 __func__, callingUid, callingPid, clientPid);
648 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700649 }
650
Eric Laurent21da6472017-11-09 16:29:26 -0800651 audio_session_t sessionId = input.sessionId;
652 if (sessionId == AUDIO_SESSION_ALLOCATE) {
653 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800654 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
655 lStatus = BAD_VALUE;
656 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800657 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800658
Eric Laurent21da6472017-11-09 16:29:26 -0800659 output.sessionId = sessionId;
660 output.outputId = AUDIO_IO_HANDLE_NONE;
661 output.selectedDeviceId = input.selectedDeviceId;
662
663 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200664 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800665 &output.selectedDeviceId, &portId);
666
667 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
668 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
669 goto Exit;
670 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800671 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
672 // but if someone uses binder directly they could bypass that and cause us to crash
673 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000674 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675 lStatus = BAD_VALUE;
676 goto Exit;
677 }
678
Glenn Kasten53b5d092014-02-05 10:00:23 -0800679 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800680 if (!audio_is_output_channel(input.config.channel_mask)) {
681 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800682 lStatus = BAD_VALUE;
683 goto Exit;
684 }
685
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700686 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800687 if (!audio_is_valid_format(input.config.format)) {
688 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700689 lStatus = BAD_VALUE;
690 goto Exit;
691 }
692
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693 {
694 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800695 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800697 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 lStatus = BAD_VALUE;
699 goto Exit;
700 }
701
Eric Laurent21da6472017-11-09 16:29:26 -0800702 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703
Glenn Kastene848bd92014-03-13 15:00:32 -0700704 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800705 // check if an effect chain with the same session ID is present on another
706 // output thread and move it here.
707 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
708 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
709 if (mPlaybackThreads.keyAt(i) != output.outputId) {
710 uint32_t sessions = t->hasAudioSession(sessionId);
711 if (sessions & ThreadBase::EFFECT_SESSION) {
712 effectThread = t.get();
713 break;
Eric Laurentde070132010-07-13 04:45:46 -0700714 }
715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 }
Eric Laurent21da6472017-11-09 16:29:26 -0800717 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718
Eric Laurent21da6472017-11-09 16:29:26 -0800719 output.sampleRate = input.config.sample_rate;
720 output.frameCount = input.frameCount;
721 output.notificationFrameCount = input.notificationFrameCount;
722 output.flags = input.flags;
723
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700724 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
725 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800726 &output.frameCount, &output.notificationFrameCount,
727 input.notificationsPerBuffer, input.speed,
728 input.sharedBuffer, sessionId, &output.flags,
729 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800730 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700731 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700732
Eric Laurent21da6472017-11-09 16:29:26 -0800733 output.afFrameCount = thread->frameCount();
734 output.afSampleRate = thread->sampleRate();
735 output.afLatencyMs = thread->latency();
736
Eric Laurent39e94f82010-07-28 01:32:47 -0700737 // move effect chain to this output thread if an effect on same session was waiting
738 // for a track to be created
739 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700740 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700741 Mutex::Autolock _dl(thread->mLock);
742 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800743 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700744 }
Eric Laurenta011e352012-03-29 15:51:43 -0700745
746 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700747 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800748 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700749 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700750 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700751 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700752 } else {
753 mPendingSyncEvents[i]->cancel();
754 }
Eric Laurenta011e352012-03-29 15:51:43 -0700755 mPendingSyncEvents.removeAt(i);
756 i--;
757 }
758 }
759 }
Glenn Kastene198c362013-08-13 09:13:36 -0700760
Eric Laurent21da6472017-11-09 16:29:26 -0800761 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762 }
Glenn Kastene198c362013-08-13 09:13:36 -0700763
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700764 if (lStatus != NO_ERROR) {
765 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700766 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700767 // Don't hold mClientLock when releasing the reference on the track as the
768 // destructor will acquire it.
769 {
770 Mutex::Autolock _cl(mClientLock);
771 client.clear();
772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700774 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700775 }
776
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700777 // return handle to client
778 trackHandle = new TrackHandle(track);
779
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800781 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
782 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
783 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700784 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 return trackHandle;
786}
787
Glenn Kasten2c073da2016-02-26 09:14:08 -0800788uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789{
790 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800791 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800793 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 return 0;
795 }
796 return thread->sampleRate();
797}
798
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800799audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800{
801 Mutex::Autolock _l(mLock);
802 PlaybackThread *thread = checkPlaybackThread_l(output);
803 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000804 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800805 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 }
807 return thread->format();
808}
809
Glenn Kasten2c073da2016-02-26 09:14:08 -0800810size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811{
812 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800813 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800815 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 return 0;
817 }
Glenn Kasten58912562012-04-03 10:45:00 -0700818 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
819 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 return thread->frameCount();
821}
822
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700823size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
824{
825 Mutex::Autolock _l(mLock);
826 ThreadBase *thread = checkThread_l(ioHandle);
827 if (thread == NULL) {
828 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
829 return 0;
830 }
831 return thread->frameCountHAL();
832}
833
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800834uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835{
836 Mutex::Autolock _l(mLock);
837 PlaybackThread *thread = checkPlaybackThread_l(output);
838 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800839 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 return 0;
841 }
842 return thread->latency();
843}
844
845status_t AudioFlinger::setMasterVolume(float value)
846{
Eric Laurenta1884f92011-08-23 08:25:03 -0700847 status_t ret = initCheck();
848 if (ret != NO_ERROR) {
849 return ret;
850 }
851
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 // check calling permissions
853 if (!settingsAllowed()) {
854 return PERMISSION_DENIED;
855 }
856
Eric Laurenta4c5a552012-03-29 10:12:40 -0700857 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700858 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700859
John Grossmanee578c02012-07-23 17:05:46 -0700860 // Set master volume in the HALs which support it.
861 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
862 AutoMutex lock(mHardwareLock);
863 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800864
John Grossmanee578c02012-07-23 17:05:46 -0700865 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
866 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700867 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800868 }
John Grossmanee578c02012-07-23 17:05:46 -0700869 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871
John Grossmanee578c02012-07-23 17:05:46 -0700872 // Now set the master volume in each playback thread. Playback threads
873 // assigned to HALs which do not have master volume support will apply
874 // master volume during the mix operation. Threads with HALs which do
875 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700876 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
877 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
878 continue;
879 }
John Grossmanee578c02012-07-23 17:05:46 -0700880 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882
883 return NO_ERROR;
884}
885
Glenn Kastenf78aee72012-01-04 11:00:47 -0800886status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887{
Eric Laurenta1884f92011-08-23 08:25:03 -0700888 status_t ret = initCheck();
889 if (ret != NO_ERROR) {
890 return ret;
891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892
893 // check calling permissions
894 if (!settingsAllowed()) {
895 return PERMISSION_DENIED;
896 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800897 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000898 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899 return BAD_VALUE;
900 }
901
902 { // scope for the lock
903 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700904 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700906 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907 mHardwareStatus = AUDIO_HW_IDLE;
908 }
909
910 if (NO_ERROR == ret) {
911 Mutex::Autolock _l(mLock);
912 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800913 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700914 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915 }
916
917 return ret;
918}
919
920status_t AudioFlinger::setMicMute(bool state)
921{
Eric Laurenta1884f92011-08-23 08:25:03 -0700922 status_t ret = initCheck();
923 if (ret != NO_ERROR) {
924 return ret;
925 }
926
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 // check calling permissions
928 if (!settingsAllowed()) {
929 return PERMISSION_DENIED;
930 }
931
932 AutoMutex lock(mHardwareLock);
933 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700934 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700935 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
936 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700937 if (result != NO_ERROR) {
938 ret = result;
939 }
940 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941 mHardwareStatus = AUDIO_HW_IDLE;
942 return ret;
943}
944
945bool AudioFlinger::getMicMute() const
946{
Eric Laurenta1884f92011-08-23 08:25:03 -0700947 status_t ret = initCheck();
948 if (ret != NO_ERROR) {
949 return false;
950 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800951 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700952 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800953 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800955 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700956 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
957 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800958 if (result == NO_ERROR) {
959 mute = mute && state;
960 }
961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800963
964 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965}
966
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800967void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
968{
969 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
970
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800971 AutoMutex lock(mLock);
972 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -0700973 mRecordThreads[i]->setRecordSilenced(uid, silenced);
974 }
975 for (size_t i = 0; i < mMmapThreads.size(); i++) {
976 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800977 }
978}
979
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980status_t AudioFlinger::setMasterMute(bool muted)
981{
John Grossmand8f178d2012-07-20 14:51:35 -0700982 status_t ret = initCheck();
983 if (ret != NO_ERROR) {
984 return ret;
985 }
986
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 // check calling permissions
988 if (!settingsAllowed()) {
989 return PERMISSION_DENIED;
990 }
991
John Grossmanee578c02012-07-23 17:05:46 -0700992 Mutex::Autolock _l(mLock);
993 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700994
John Grossmanee578c02012-07-23 17:05:46 -0700995 // Set master mute in the HALs which support it.
996 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
997 AutoMutex lock(mHardwareLock);
998 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700999
John Grossmanee578c02012-07-23 17:05:46 -07001000 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1001 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001002 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001003 }
John Grossmanee578c02012-07-23 17:05:46 -07001004 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001005 }
1006
John Grossmanee578c02012-07-23 17:05:46 -07001007 // Now set the master mute in each playback thread. Playback threads
1008 // assigned to HALs which do not have master mute support will apply master
1009 // mute during the mix operation. Threads with HALs which do support master
1010 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001011 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1012 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1013 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015
1016 return NO_ERROR;
1017}
1018
1019float AudioFlinger::masterVolume() const
1020{
Glenn Kasten98067102011-12-13 11:47:54 -08001021 Mutex::Autolock _l(mLock);
1022 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023}
1024
1025bool AudioFlinger::masterMute() const
1026{
Glenn Kasten98067102011-12-13 11:47:54 -08001027 Mutex::Autolock _l(mLock);
1028 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029}
1030
John Grossman4ff14ba2012-02-08 16:37:41 -08001031float AudioFlinger::masterVolume_l() const
1032{
John Grossman4ff14ba2012-02-08 16:37:41 -08001033 return mMasterVolume;
1034}
1035
John Grossmand8f178d2012-07-20 14:51:35 -07001036bool AudioFlinger::masterMute_l() const
1037{
John Grossmanee578c02012-07-23 17:05:46 -07001038 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001039}
1040
Eric Laurent223fd5c2014-11-11 13:43:36 -08001041status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1042{
1043 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001044 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001045 return BAD_VALUE;
1046 }
1047 pid_t caller = IPCThreadState::self()->getCallingPid();
1048 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001049 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001050 return PERMISSION_DENIED;
1051 }
1052
1053 return NO_ERROR;
1054}
1055
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001056status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1057 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058{
1059 // check calling permissions
1060 if (!settingsAllowed()) {
1061 return PERMISSION_DENIED;
1062 }
1063
Eric Laurent223fd5c2014-11-11 13:43:36 -08001064 status_t status = checkStreamType(stream);
1065 if (status != NO_ERROR) {
1066 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
Eric Laurent98e38192018-02-15 18:31:53 -08001068 if (output == AUDIO_IO_HANDLE_NONE) {
1069 return BAD_VALUE;
1070 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001071 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072
1073 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001074 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1075 if (volumeInterface == NULL) {
1076 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 }
Eric Laurent98e38192018-02-15 18:31:53 -08001078 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079
1080 return NO_ERROR;
1081}
1082
Glenn Kastenfff6d712012-01-12 16:38:12 -08001083status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084{
1085 // check calling permissions
1086 if (!settingsAllowed()) {
1087 return PERMISSION_DENIED;
1088 }
1089
Eric Laurent223fd5c2014-11-11 13:43:36 -08001090 status_t status = checkStreamType(stream);
1091 if (status != NO_ERROR) {
1092 return status;
1093 }
1094 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1095
1096 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001097 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 return BAD_VALUE;
1099 }
1100
Eric Laurent93575202011-01-18 18:39:02 -08001101 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001103 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1104 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1105 volumeInterfaces[i]->setStreamMute(stream, muted);
1106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107
1108 return NO_ERROR;
1109}
1110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001111float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001113 status_t status = checkStreamType(stream);
1114 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 return 0.0f;
1116 }
Eric Laurent98e38192018-02-15 18:31:53 -08001117 if (output == AUDIO_IO_HANDLE_NONE) {
1118 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 }
1120
Eric Laurent98e38192018-02-15 18:31:53 -08001121 AutoMutex lock(mLock);
1122 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1123 if (volumeInterface == NULL) {
1124 return 0.0f;
1125 }
1126
1127 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128}
1129
Glenn Kastenfff6d712012-01-12 16:38:12 -08001130bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001132 status_t status = checkStreamType(stream);
1133 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134 return true;
1135 }
1136
Glenn Kasten6637baa2012-01-09 09:40:36 -08001137 AutoMutex lock(mLock);
1138 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139}
1140
Eric Laurent054d9d32015-04-24 08:48:48 -07001141
1142void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1143{
1144 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1145 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1146 }
1147}
1148
Eric Laurentf1047e82018-04-16 19:18:20 -07001149// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1150// Some keys are used for audio routing and audio path configuration and should be reserved for use
1151// by audio policy and audio flinger for functional, privacy and security reasons.
1152void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1153{
1154 static const String8 kReservedParameters[] = {
1155 String8(AudioParameter::keyRouting),
1156 String8(AudioParameter::keySamplingRate),
1157 String8(AudioParameter::keyFormat),
1158 String8(AudioParameter::keyChannels),
1159 String8(AudioParameter::keyFrameCount),
1160 String8(AudioParameter::keyInputSource),
1161 String8(AudioParameter::keyMonoOutput),
1162 String8(AudioParameter::keyStreamConnect),
1163 String8(AudioParameter::keyStreamDisconnect),
1164 String8(AudioParameter::keyStreamSupportedFormats),
1165 String8(AudioParameter::keyStreamSupportedChannels),
1166 String8(AudioParameter::keyStreamSupportedSamplingRates),
1167 };
1168
1169 // multiuser friendly app ID check for requests coming from audioserver
1170 if (multiuser_get_app_id(callingUid) == AID_AUDIOSERVER) {
1171 return;
1172 }
1173
1174 AudioParameter param = AudioParameter(keyValuePairs);
1175 String8 value;
1176 for (auto& key : kReservedParameters) {
1177 if (param.get(key, value) == NO_ERROR) {
1178 ALOGW("%s: filtering key %s value %s from uid %d",
1179 __func__, key.string(), value.string(), callingUid);
1180 param.remove(key);
1181 }
1182 }
1183 keyValuePairs = param.toString();
1184}
1185
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001186status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187{
Eric Laurentf1047e82018-04-16 19:18:20 -07001188 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1189 ioHandle, keyValuePairs.string(),
1190 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001191
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 // check calling permissions
1193 if (!settingsAllowed()) {
1194 return PERMISSION_DENIED;
1195 }
1196
Eric Laurentf1047e82018-04-16 19:18:20 -07001197 String8 filteredKeyValuePairs = keyValuePairs;
1198 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1199
1200 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1201
Glenn Kasten142f5192014-03-25 17:44:59 -07001202 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1203 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001204 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001205 // result will remain NO_INIT if no audio device is present
1206 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001207 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001208 AutoMutex lock(mHardwareLock);
1209 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1210 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001211 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001212 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001213 // return success if at least one audio device accepts the parameters as not all
1214 // HALs are requested to support all parameters. If no audio device supports the
1215 // requested parameters, the last error is reported.
1216 if (final_result != NO_ERROR) {
1217 final_result = result;
1218 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001219 }
1220 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001221 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001222 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001223 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001224 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001225 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1226 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001227 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001228 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001229 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001230 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001231 }
1232 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001233 String8 screenState;
1234 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001235 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001236 if (isOff != (AudioFlinger::mScreenState & 1)) {
1237 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001238 }
1239 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001240 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 }
1242
1243 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1244 // and the thread is exited once the lock is released
1245 sp<ThreadBase> thread;
1246 {
1247 Mutex::Autolock _l(mLock);
1248 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001249 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001251 if (thread == 0) {
1252 thread = checkMmapThread_l(ioHandle);
1253 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001254 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001255 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001256 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001257 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001258 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1259 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001260 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262 }
1263 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001264 if (thread != 0) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001265 return thread->setParameters(filteredKeyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266 }
1267 return BAD_VALUE;
1268}
1269
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001270String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001272 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1273 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274
Eric Laurenta4c5a552012-03-29 10:12:40 -07001275 Mutex::Autolock _l(mLock);
1276
Glenn Kasten142f5192014-03-25 17:44:59 -07001277 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001278 String8 out_s8;
1279
Dima Zavin799a70e2011-04-18 16:57:27 -07001280 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001281 String8 s;
1282 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001283 {
1284 AutoMutex lock(mHardwareLock);
1285 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001286 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1287 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001288 mHardwareStatus = AUDIO_HW_IDLE;
1289 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001290 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001291 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001292 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293 }
1294
Eric Laurent6acd1d42017-01-04 14:23:29 -08001295 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1296 if (thread == NULL) {
1297 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1298 if (thread == NULL) {
1299 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1300 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001301 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001302 }
1303 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001305 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306}
1307
Glenn Kastendd8104c2012-07-02 12:42:44 -07001308size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1309 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310{
Eric Laurenta1884f92011-08-23 08:25:03 -07001311 status_t ret = initCheck();
1312 if (ret != NO_ERROR) {
1313 return 0;
1314 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001315 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001316 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001317 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001318 return 0;
1319 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001320
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001321 AutoMutex lock(mHardwareLock);
1322 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001323 audio_config_t config, proposed;
1324 memset(&proposed, 0, sizeof(proposed));
1325 proposed.sample_rate = sampleRate;
1326 proposed.channel_mask = channelMask;
1327 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001328
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001329 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001330 size_t frames;
1331 for (;;) {
1332 // Note: config is currently a const parameter for get_input_buffer_size()
1333 // but we use a copy from proposed in case config changes from the call.
1334 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001335 status_t result = dev->getInputBufferSize(&config, &frames);
1336 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001337 break; // hal success, config is the result
1338 }
1339 // change one parameter of the configuration each iteration to a more "common" value
1340 // to see if the device will support it.
1341 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1342 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1343 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1344 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1345 } else {
1346 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1347 "format %#x, channelMask 0x%X",
1348 sampleRate, format, channelMask);
1349 break; // retries failed, break out of loop with frames == 0.
1350 }
1351 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001352 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001353 if (frames > 0 && config.sample_rate != sampleRate) {
1354 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1355 }
1356 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001357}
1358
Glenn Kasten5f972c02014-01-13 09:59:31 -08001359uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361 Mutex::Autolock _l(mLock);
1362
1363 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1364 if (recordThread != NULL) {
1365 return recordThread->getInputFramesLost();
1366 }
1367 return 0;
1368}
1369
1370status_t AudioFlinger::setVoiceVolume(float value)
1371{
Eric Laurenta1884f92011-08-23 08:25:03 -07001372 status_t ret = initCheck();
1373 if (ret != NO_ERROR) {
1374 return ret;
1375 }
1376
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 // check calling permissions
1378 if (!settingsAllowed()) {
1379 return PERMISSION_DENIED;
1380 }
1381
1382 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001383 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001384 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001385 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 mHardwareStatus = AUDIO_HW_IDLE;
1387
1388 return ret;
1389}
1390
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001391status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001392 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394 Mutex::Autolock _l(mLock);
1395
1396 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1397 if (playbackThread != NULL) {
1398 return playbackThread->getRenderPosition(halFrames, dspFrames);
1399 }
1400
1401 return BAD_VALUE;
1402}
1403
1404void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1405{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001407 if (client == 0) {
1408 return;
1409 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001410 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001411 {
1412 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001413 if (mNotificationClients.indexOfKey(pid) < 0) {
1414 sp<NotificationClient> notificationClient = new NotificationClient(this,
1415 client,
1416 pid);
1417 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001418
Eric Laurent021cf962014-05-13 10:18:14 -07001419 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420
Marco Nelissen06b46062014-11-14 07:58:25 -08001421 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001422 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001423 }
1424 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425
Eric Laurent021cf962014-05-13 10:18:14 -07001426 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001427 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001428 // the config change is always sent from playback or record threads to avoid deadlock
1429 // with AudioSystem::gLock
1430 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001431 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001432 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001434 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001435 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 }
1437}
1438
1439void AudioFlinger::removeNotificationClient(pid_t pid)
1440{
1441 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001442 {
1443 Mutex::Autolock _cl(mClientLock);
1444 mNotificationClients.removeItem(pid);
1445 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001446
Steve Block3856b092011-10-20 11:56:00 +01001447 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001448 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001449 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001450 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001451 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001452 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001453 if (ref->mPid == pid) {
1454 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001455 mAudioSessionRefs.removeAt(i);
1456 delete ref;
1457 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001458 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001459 } else {
1460 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001461 }
1462 }
1463 if (removed) {
1464 purgeStaleEffects_l();
1465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466}
1467
Eric Laurent73e26b62015-04-27 16:55:58 -07001468void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001469 const sp<AudioIoDescriptor>& ioDesc,
1470 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471{
Eric Laurent021cf962014-05-13 10:18:14 -07001472 Mutex::Autolock _l(mClientLock);
1473 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001475 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1476 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1477 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001478 }
1479}
1480
Eric Laurent021cf962014-05-13 10:18:14 -07001481// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482void AudioFlinger::removeClient_l(pid_t pid)
1483{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001484 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001485 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486 mClients.removeItem(pid);
1487}
1488
Eric Laurent717e1282012-06-29 16:36:52 -07001489// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001490sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1491 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001492{
1493 sp<PlaybackThread> thread;
1494
1495 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1496 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1497 ALOG_ASSERT(thread == 0);
1498 thread = mPlaybackThreads.valueAt(i);
1499 }
1500 }
1501
1502 return thread;
1503}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506
1507// ----------------------------------------------------------------------------
1508
1509AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1510 : RefBase(),
1511 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001512 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513{
Andy Hung6f248bb2018-01-23 14:04:37 -08001514 mMemoryDealer = new MemoryDealer(
1515 audioFlinger->getClientSharedHeapSize(),
1516 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517}
1518
Eric Laurent021cf962014-05-13 10:18:14 -07001519// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520AudioFlinger::Client::~Client()
1521{
1522 mAudioFlinger->removeClient_l(mPid);
1523}
1524
Glenn Kasten435dbe62012-01-30 10:15:48 -08001525sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526{
1527 return mMemoryDealer;
1528}
1529
1530// ----------------------------------------------------------------------------
1531
1532AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1533 const sp<IAudioFlingerClient>& client,
1534 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001535 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536{
1537}
1538
1539AudioFlinger::NotificationClient::~NotificationClient()
1540{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541}
1542
Glenn Kasten0f11b512014-01-31 16:18:54 -08001543void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544{
1545 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001546 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547}
1548
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001549// ----------------------------------------------------------------------------
1550AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1551 : mPendingRequests(false) {}
1552
1553
1554void AudioFlinger::MediaLogNotifier::requestMerge() {
1555 AutoMutex _l(mMutex);
1556 mPendingRequests = true;
1557 mCond.signal();
1558}
1559
1560bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001561 // Should already have been checked, but just in case
1562 if (sMediaLogService == 0) {
1563 return false;
1564 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001565 // Wait until there are pending requests
1566 {
1567 AutoMutex _l(mMutex);
1568 mPendingRequests = false; // to ignore past requests
1569 while (!mPendingRequests) {
1570 mCond.wait(mMutex);
1571 // TODO may also need an exitPending check
1572 }
1573 mPendingRequests = false;
1574 }
1575 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001576 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001577 usleep(kPostTriggerSleepPeriod);
1578 return true;
1579}
1580
1581void AudioFlinger::requestLogMerge() {
1582 mMediaLogNotifier->requestMerge();
1583}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584
1585// ----------------------------------------------------------------------------
1586
Eric Laurentf14db3c2017-12-08 14:20:36 -08001587sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1588 CreateRecordOutput& output,
1589 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590{
1591 sp<RecordThread::RecordTrack> recordTrack;
1592 sp<RecordHandle> recordHandle;
1593 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001595 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001596 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597
Eric Laurentf14db3c2017-12-08 14:20:36 -08001598 output.cblk.clear();
1599 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001600 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001601
Eric Laurentf14db3c2017-12-08 14:20:36 -08001602 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001603 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001604 uid_t clientUid = input.clientInfo.clientUid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001605 if (!isTrustedCallingUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001606 ALOGW_IF(clientUid != callingUid,
1607 "%s uid %d tried to pass itself off as %d",
1608 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001609 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001610 updatePid = true;
1611 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001612 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001613 if (updatePid) {
1614 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001615 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001616 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001617 __func__, callingUid, callingPid, clientPid);
1618 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001619 }
1620
Andy Hung6770c6f2015-04-07 13:43:36 -07001621 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001622 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1623 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001624 lStatus = BAD_VALUE;
1625 goto Exit;
1626 }
1627
Glenn Kasten53b5d092014-02-05 10:00:23 -08001628 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001629 if (!audio_is_input_channel(input.config.channel_mask)) {
1630 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001631 lStatus = BAD_VALUE;
1632 goto Exit;
1633 }
1634
Eric Laurentf14db3c2017-12-08 14:20:36 -08001635 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1636 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1637 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1638 lStatus = BAD_VALUE;
1639 goto Exit;
1640 }
1641
1642 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001643 output.selectedDeviceId = input.selectedDeviceId;
1644 output.flags = input.flags;
1645
1646 client = registerPid(clientPid);
1647
1648 // Not a conventional loop, but a retry loop for at most two iterations total.
1649 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1650 // Exits loop via break on no error of got exit on error
1651 // The sp<> references will be dropped when re-entering scope.
1652 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1653 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001654 // release previously opened input if retrying.
1655 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1656 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001657 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001658 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001659 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001660 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001661 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001662 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1663 sessionId,
1664 // FIXME compare to AudioTrack
1665 clientPid,
1666 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001667 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001668 &input.config,
1669 output.flags, &output.selectedDeviceId, &portId);
1670
Glenn Kasten05997e22014-03-13 15:08:33 -07001671 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001673 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001675 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 lStatus = BAD_VALUE;
1677 goto Exit;
1678 }
1679
Eric Laurentf14db3c2017-12-08 14:20:36 -08001680 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681
Eric Laurentf14db3c2017-12-08 14:20:36 -08001682 output.sampleRate = input.config.sample_rate;
1683 output.frameCount = input.frameCount;
1684 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001685
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001686 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001687 input.config.format, input.config.channel_mask,
1688 &output.frameCount, sessionId,
1689 &output.notificationFrameCount,
1690 clientUid, &output.flags,
1691 input.clientInfo.clientTid,
1692 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001693 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001694
Eric Laurentf14db3c2017-12-08 14:20:36 -08001695 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1696 // audio policy manager without FAST constraint
1697 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001698 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001699 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001700
1701 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001702 goto Exit;
1703 }
1704
1705 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1706 // session and move it to this thread.
1707 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1708 if (chain != 0) {
1709 Mutex::Autolock _l(thread->mLock);
1710 thread->addEffectChain_l(chain);
1711 }
1712 break;
1713 }
1714 // End of retry loop.
1715 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 }
Glenn Kastene198c362013-08-13 09:13:36 -07001717
Eric Laurentf14db3c2017-12-08 14:20:36 -08001718 output.cblk = recordTrack->getCblk();
1719 output.buffers = recordTrack->getBuffers();
1720
1721 // return handle to client
1722 recordHandle = new RecordHandle(recordTrack);
1723
1724Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001725 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001726 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001727 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001728 // Don't hold mClientLock when releasing the reference on the track as the
1729 // destructor will acquire it.
1730 {
1731 Mutex::Autolock _cl(mClientLock);
1732 client.clear();
1733 }
Eric Laurent896c9672017-12-08 14:08:45 -08001734 recordTrack.clear();
1735 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001736 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 }
1739
Glenn Kasten9156ef32013-08-06 15:39:08 -07001740 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 return recordHandle;
1742}
1743
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001744
1745
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746// ----------------------------------------------------------------------------
1747
Eric Laurenta4c5a552012-03-29 10:12:40 -07001748audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1749{
Eric Laurent44622db2014-08-01 19:00:33 -07001750 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001751 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001752 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001753 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001754 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001755 }
1756 Mutex::Autolock _l(mLock);
1757 return loadHwModule_l(name);
1758}
1759
1760// loadHwModule_l() must be called with AudioFlinger::mLock held
1761audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1762{
1763 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1764 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1765 ALOGW("loadHwModule() module %s already loaded", name);
1766 return mAudioHwDevs.keyAt(i);
1767 }
1768 }
1769
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001770 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001771
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001772 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001773 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001774 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001775 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001776 }
1777
1778 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001779 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001780 mHardwareStatus = AUDIO_HW_IDLE;
1781 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001782 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001783 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001784 }
1785
John Grossmanee578c02012-07-23 17:05:46 -07001786 // Check and cache this HAL's level of support for master mute and master
1787 // volume. If this is the first HAL opened, and it supports the get
1788 // methods, use the initial values provided by the HAL as the current
1789 // master mute and volume settings.
1790
1791 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1792 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001793 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001794
1795 if (0 == mAudioHwDevs.size()) {
1796 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001797 float mv;
1798 if (OK == dev->getMasterVolume(&mv)) {
1799 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001800 }
1801
1802 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001803 bool mm;
1804 if (OK == dev->getMasterMute(&mm)) {
1805 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001806 }
1807 }
1808
Eric Laurenta4c5a552012-03-29 10:12:40 -07001809 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001810 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001811 flags = static_cast<AudioHwDevice::Flags>(flags |
1812 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1813 }
1814
1815 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001816 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001817 flags = static_cast<AudioHwDevice::Flags>(flags |
1818 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1819 }
1820
Eric Laurenta4c5a552012-03-29 10:12:40 -07001821 mHardwareStatus = AUDIO_HW_IDLE;
1822 }
1823
Glenn Kastena13cde92016-03-28 15:26:02 -07001824 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001825 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001826
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001827 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001828
1829 return handle;
1830
1831}
1832
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001833// ----------------------------------------------------------------------------
1834
Glenn Kasten3b16c762012-11-14 08:44:39 -08001835uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001836{
1837 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001838 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001839 return thread != NULL ? thread->sampleRate() : 0;
1840}
1841
Glenn Kastene33054e2012-11-14 12:54:39 -08001842size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001843{
1844 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001845 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001846 return thread != NULL ? thread->frameCountHAL() : 0;
1847}
1848
1849// ----------------------------------------------------------------------------
1850
Andy Hung6f248bb2018-01-23 14:04:37 -08001851status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001852{
1853 uid_t uid = IPCThreadState::self()->getCallingUid();
1854 if (uid != AID_SYSTEM) {
1855 return PERMISSION_DENIED;
1856 }
1857 Mutex::Autolock _l(mLock);
1858 if (mIsDeviceTypeKnown) {
1859 return INVALID_OPERATION;
1860 }
1861 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001862 mTotalMemory = totalMemory;
1863 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1864 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1865 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1866 // though actual setting is determined through device configuration.
1867 constexpr int64_t GB = 1024 * 1024 * 1024;
1868 mClientSharedHeapSize =
1869 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1870 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1871 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1872 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1873 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001874 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001875
1876 // TODO: Cache the client shared heap size in a persistent property.
1877 // It's possible that a native process or Java service or app accesses audioserver
1878 // after it is registered by system server, but before AudioService updates
1879 // the memory info. This would occur immediately after boot or an audioserver
1880 // crash and restore. Before update from AudioService, the client would get the
1881 // minimum heap size.
1882
1883 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1884 (isLowRamDevice ? "true" : "false"),
1885 (long long)mTotalMemory,
1886 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001887 return NO_ERROR;
1888}
1889
Andy Hung6f248bb2018-01-23 14:04:37 -08001890size_t AudioFlinger::getClientSharedHeapSize() const
1891{
1892 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1893 if (heapSizeInBytes != 0) { // read-only property overrides all.
1894 return heapSizeInBytes;
1895 }
1896 return mClientSharedHeapSize;
1897}
1898
Mikhail Naganovdea53042018-04-26 13:10:21 -07001899status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1900{
1901 ALOGV(__func__);
1902
1903 audio_module_handle_t module;
1904 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1905 module = config->ext.device.hw_module;
1906 } else {
1907 module = config->ext.mix.hw_module;
1908 }
1909
1910 Mutex::Autolock _l(mLock);
1911 ssize_t index = mAudioHwDevs.indexOfKey(module);
1912 if (index < 0) {
1913 ALOGW("%s() bad hw module %d", __func__, module);
1914 return BAD_VALUE;
1915 }
1916
1917 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
1918 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
1919}
1920
Eric Laurent93c3d412014-08-01 14:48:35 -07001921audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1922{
1923 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001924
1925 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1926 if (index >= 0) {
1927 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1928 mHwAvSyncIds.valueAt(index), sessionId);
1929 return mHwAvSyncIds.valueAt(index);
1930 }
1931
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001932 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001933 if (dev == NULL) {
1934 return AUDIO_HW_SYNC_INVALID;
1935 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001936 String8 reply;
1937 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001938 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001939 param = AudioParameter(reply);
1940 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001941
1942 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001943 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001944 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1945 return AUDIO_HW_SYNC_INVALID;
1946 }
1947
1948 // allow only one session for a given HW A/V sync ID.
1949 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1950 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1951 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1952 value, mHwAvSyncIds.keyAt(i));
1953 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001954 break;
1955 }
1956 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001957
1958 mHwAvSyncIds.add(sessionId, value);
1959
1960 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1961 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1962 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001963 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001964 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001965 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001966 thread->setParameters(param.toString());
1967 break;
1968 }
1969 }
1970
1971 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1972 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001973}
1974
Eric Laurent72e3f392015-05-20 14:43:50 -07001975status_t AudioFlinger::systemReady()
1976{
1977 Mutex::Autolock _l(mLock);
1978 ALOGI("%s", __FUNCTION__);
1979 if (mSystemReady) {
1980 ALOGW("%s called twice", __FUNCTION__);
1981 return NO_ERROR;
1982 }
1983 mSystemReady = true;
1984 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1985 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1986 thread->systemReady();
1987 }
1988 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1989 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1990 thread->systemReady();
1991 }
1992 return NO_ERROR;
1993}
1994
jiabin46a76fa2018-01-05 10:18:21 -08001995status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
1996{
jiabin9ff780e2018-03-19 18:19:52 -07001997 AutoMutex lock(mHardwareLock);
1998 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1999 status_t status = dev->getMicrophones(microphones);
2000 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002001}
2002
Eric Laurentfa90e842014-10-17 18:12:31 -07002003// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2004void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2005{
2006 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2007 if (index >= 0) {
2008 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2009 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2010 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002011 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002012 thread->setParameters(param.toString());
2013 }
2014}
2015
2016
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002017// ----------------------------------------------------------------------------
2018
Eric Laurent83b88082014-06-20 18:31:16 -07002019
Eric Laurent6acd1d42017-01-04 14:23:29 -08002020sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002021 audio_io_handle_t *output,
2022 audio_config_t *config,
2023 audio_devices_t devices,
2024 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002025 audio_output_flags_t flags)
2026{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002027 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002028 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002029 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002030 }
2031
Eric Laurentcf2c0212014-07-25 16:20:43 -07002032 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002033 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2034 } else {
2035 // Audio Policy does not currently request a specific output handle.
2036 // If this is ever needed, see openInput_l() for example code.
2037 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2038 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002039 }
Eric Laurent83b88082014-06-20 18:31:16 -07002040
2041 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2042
Eric Laurent83b88082014-06-20 18:31:16 -07002043 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002044 // This if statement allows overriding the audio policy settings
2045 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2046 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2047 // Check only for Normal Mixing mode
2048 if (kEnableExtendedPrecision) {
2049 // Specify format (uncomment one below to choose)
2050 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2051 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2052 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2053 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002054 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002055 }
2056 if (kEnableExtendedChannels) {
2057 // Specify channel mask (uncomment one below to choose)
2058 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2059 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2060 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2061 }
Eric Laurent83b88082014-06-20 18:31:16 -07002062 }
2063
Phil Burk062e67a2015-02-11 13:40:50 -08002064 AudioStreamOut *outputStream = NULL;
2065 status_t status = outHwDev->openOutputStream(
2066 &outputStream,
2067 *output,
2068 devices,
2069 flags,
2070 config,
2071 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002072
2073 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002074
Phil Burk062e67a2015-02-11 13:40:50 -08002075 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002076 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2077 sp<MmapPlaybackThread> thread =
2078 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2079 devices, AUDIO_DEVICE_NONE, mSystemReady);
2080 mMmapThreads.add(*output, thread);
2081 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2082 *output, thread.get());
2083 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002084 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002085 sp<PlaybackThread> thread;
2086 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2087 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2088 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2089 *output, thread.get());
2090 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2091 || !isValidPcmSinkFormat(config->format)
2092 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2093 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2094 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2095 *output, thread.get());
2096 } else {
2097 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2098 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2099 *output, thread.get());
2100 }
2101 mPlaybackThreads.add(*output, thread);
2102 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002103 }
Eric Laurent83b88082014-06-20 18:31:16 -07002104 }
2105
2106 return 0;
2107}
2108
Eric Laurentcf2c0212014-07-25 16:20:43 -07002109status_t AudioFlinger::openOutput(audio_module_handle_t module,
2110 audio_io_handle_t *output,
2111 audio_config_t *config,
2112 audio_devices_t *devices,
2113 const String8& address,
2114 uint32_t *latencyMs,
2115 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002117 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2118 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002119 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002120 (devices != NULL) ? *devices : 0,
2121 config->sample_rate,
2122 config->format,
2123 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002124 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002126 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002127 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002129
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 Mutex::Autolock _l(mLock);
2131
Eric Laurent6acd1d42017-01-04 14:23:29 -08002132 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002133 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002134 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2135 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2136 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137
Eric Laurent6acd1d42017-01-04 14:23:29 -08002138 // notify client processes of the new output creation
2139 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002140
Eric Laurent6acd1d42017-01-04 14:23:29 -08002141 // the first primary output opened designates the primary hw device
2142 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002143 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002144 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002145
Eric Laurent6acd1d42017-01-04 14:23:29 -08002146 AutoMutex lock(mHardwareLock);
2147 mHardwareStatus = AUDIO_HW_SET_MODE;
2148 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2149 mHardwareStatus = AUDIO_HW_IDLE;
2150 }
2151 } else {
2152 MmapThread *mmapThread = (MmapThread *)thread.get();
2153 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002154 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002155 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156 }
2157
Eric Laurentcf2c0212014-07-25 16:20:43 -07002158 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159}
2160
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002161audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2162 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163{
2164 Mutex::Autolock _l(mLock);
2165 MixerThread *thread1 = checkMixerThread_l(output1);
2166 MixerThread *thread2 = checkMixerThread_l(output2);
2167
2168 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002169 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2170 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002171 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172 }
2173
Glenn Kasteneeecb982016-02-26 10:44:04 -08002174 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002175 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 thread->addOutputTrack(thread2);
2177 mPlaybackThreads.add(id, thread);
2178 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002179 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 return id;
2181}
2182
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002183status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184{
Glenn Kastend96c5722012-04-25 13:44:49 -07002185 return closeOutput_nonvirtual(output);
2186}
2187
2188status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2189{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 // keep strong reference on the playback thread so that
2191 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002192 sp<PlaybackThread> playbackThread;
2193 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 {
2195 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002196 playbackThread = checkPlaybackThread_l(output);
2197 if (playbackThread != NULL) {
2198 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199
Eric Laurent6acd1d42017-01-04 14:23:29 -08002200 if (playbackThread->type() == ThreadBase::MIXER) {
2201 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2202 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2203 DuplicatingThread *dupThread =
2204 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2205 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2206 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207 }
2208 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209
2210
Eric Laurent6acd1d42017-01-04 14:23:29 -08002211 mPlaybackThreads.removeItem(output);
2212 // save all effects to the default thread
2213 if (mPlaybackThreads.size()) {
2214 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2215 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002216 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002217 Mutex::Autolock _dl(dstThread->mLock);
2218 Mutex::Autolock _sl(playbackThread->mLock);
2219 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2220 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002221 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2222 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 }
2225 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002226 } else {
2227 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2228 if (mmapThread == 0) {
2229 return BAD_VALUE;
2230 }
2231 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002232 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002234 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2235 ioDesc->mIoHandle = output;
2236 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002238 // The thread entity (active unit of execution) is no longer running here,
2239 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240
Eric Laurent6acd1d42017-01-04 14:23:29 -08002241 if (playbackThread != 0) {
2242 playbackThread->exit();
2243 if (!playbackThread->isDuplicating()) {
2244 closeOutputFinish(playbackThread);
2245 }
2246 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002247 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002248 mmapThread->exit();
2249 AudioStreamOut *out = mmapThread->clearOutput();
2250 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2251 // from now on thread->mOutput is NULL
2252 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 }
2254 return NO_ERROR;
2255}
2256
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002257void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002258{
2259 AudioStreamOut *out = thread->clearOutput();
2260 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2261 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002262 delete out;
2263}
2264
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002265void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002266{
2267 mPlaybackThreads.removeItem(thread->mId);
2268 thread->exit();
2269 closeOutputFinish(thread);
2270}
2271
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002272status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002273{
2274 Mutex::Autolock _l(mLock);
2275 PlaybackThread *thread = checkPlaybackThread_l(output);
2276
2277 if (thread == NULL) {
2278 return BAD_VALUE;
2279 }
2280
Steve Block3856b092011-10-20 11:56:00 +01002281 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 thread->suspend();
2283
2284 return NO_ERROR;
2285}
2286
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002287status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288{
2289 Mutex::Autolock _l(mLock);
2290 PlaybackThread *thread = checkPlaybackThread_l(output);
2291
2292 if (thread == NULL) {
2293 return BAD_VALUE;
2294 }
2295
Steve Block3856b092011-10-20 11:56:00 +01002296 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297
2298 thread->restore();
2299
2300 return NO_ERROR;
2301}
2302
Eric Laurentcf2c0212014-07-25 16:20:43 -07002303status_t AudioFlinger::openInput(audio_module_handle_t module,
2304 audio_io_handle_t *input,
2305 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002306 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002307 const String8& address,
2308 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002309 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310{
Eric Laurent83b88082014-06-20 18:31:16 -07002311 Mutex::Autolock _l(mLock);
2312
Glenn Kastene7d66712015-03-05 13:46:52 -08002313 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002314 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002315 }
2316
Eric Laurent6acd1d42017-01-04 14:23:29 -08002317 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002318
2319 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002320 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002321 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002322 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002324 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002325}
Dima Zavin799a70e2011-04-18 16:57:27 -07002326
Eric Laurent6acd1d42017-01-04 14:23:29 -08002327sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002328 audio_io_handle_t *input,
2329 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002330 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002331 const String8& address,
2332 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002333 audio_input_flags_t flags)
2334{
Glenn Kastene7d66712015-03-05 13:46:52 -08002335 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002336 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002337 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002338 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002339 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002340
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);
2544 if (pid != -1 && (caller == getpid_cached)) {
2545 caller = pid;
2546 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002547
Eric Laurent021cf962014-05-13 10:18:14 -07002548 {
2549 Mutex::Autolock _cl(mClientLock);
2550 // Ignore requests received from processes not known as notification client. The request
2551 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2552 // called from a different pid leaving a stale session reference. Also we don't know how
2553 // to clear this reference if the client process dies.
2554 if (mNotificationClients.indexOfKey(caller) < 0) {
2555 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2556 return;
2557 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002558 }
2559
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002560 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002561 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002562 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002563 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2564 ref->mCnt++;
2565 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002566 return;
2567 }
2568 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002569 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2570 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002571}
2572
Glenn Kastend848eb42016-03-08 13:42:11 -08002573void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002574{
2575 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002576 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002577 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2578 if (pid != -1 && (caller == getpid_cached)) {
2579 caller = pid;
2580 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002581 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002582 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002583 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002584 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2585 ref->mCnt--;
2586 ALOGV(" decremented refcount to %d", ref->mCnt);
2587 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002588 mAudioSessionRefs.removeAt(i);
2589 delete ref;
2590 purgeStaleEffects_l();
2591 }
2592 return;
2593 }
2594 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002595 // If the caller is mediaserver it is likely that the session being released was acquired
2596 // on behalf of a process not in notification clients and we ignore the warning.
2597 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002598}
2599
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002600bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2601{
2602 size_t num = mAudioSessionRefs.size();
2603 for (size_t i = 0; i < num; i++) {
2604 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2605 if (ref->mSessionid == audioSession) {
2606 return true;
2607 }
2608 }
2609 return false;
2610}
2611
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002612void AudioFlinger::purgeStaleEffects_l() {
2613
Steve Block3856b092011-10-20 11:56:00 +01002614 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002615
2616 Vector< sp<EffectChain> > chains;
2617
2618 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2619 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002620 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002621 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2622 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002623 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2624 chains.push(ec);
2625 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002626 }
2627 }
2628 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2629 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002630 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002631 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2632 sp<EffectChain> ec = t->mEffectChains[j];
2633 chains.push(ec);
2634 }
2635 }
2636
2637 for (size_t i = 0; i < chains.size(); i++) {
2638 sp<EffectChain> ec = chains[i];
2639 int sessionid = ec->sessionId();
2640 sp<ThreadBase> t = ec->mThread.promote();
2641 if (t == 0) {
2642 continue;
2643 }
2644 size_t numsessionrefs = mAudioSessionRefs.size();
2645 bool found = false;
2646 for (size_t k = 0; k < numsessionrefs; k++) {
2647 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002648 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002649 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002650 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002651 found = true;
2652 break;
2653 }
2654 }
2655 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002656 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002657 // remove all effects from the chain
2658 while (ec->mEffects.size()) {
2659 sp<EffectModule> effect = ec->mEffects[0];
2660 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002661 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002662 if (effect->purgeHandles()) {
2663 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002664 }
2665 AudioSystem::unregisterEffect(effect->id());
2666 }
2667 }
2668 }
2669 return;
2670}
2671
Glenn Kasteneeecb982016-02-26 10:44:04 -08002672// checkThread_l() must be called with AudioFlinger::mLock held
2673AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2674{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002675 ThreadBase *thread = checkMmapThread_l(ioHandle);
2676 if (thread == 0) {
2677 switch (audio_unique_id_get_use(ioHandle)) {
2678 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2679 thread = checkPlaybackThread_l(ioHandle);
2680 break;
2681 case AUDIO_UNIQUE_ID_USE_INPUT:
2682 thread = checkRecordThread_l(ioHandle);
2683 break;
2684 default:
2685 break;
2686 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002687 }
2688 return thread;
2689}
2690
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002692AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693{
Glenn Kastena1117922012-01-26 10:53:32 -08002694 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002695}
2696
2697// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002698AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699{
2700 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002701 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702}
2703
2704// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002705AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706{
Glenn Kastena1117922012-01-26 10:53:32 -08002707 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708}
2709
Eric Laurent6acd1d42017-01-04 14:23:29 -08002710// checkMmapThread_l() must be called with AudioFlinger::mLock held
2711AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2712{
2713 return mMmapThreads.valueFor(io).get();
2714}
2715
2716
2717// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2718AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2719{
Eric Laurent7459b902017-04-19 18:10:41 -07002720 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002721 if (volumeInterface == nullptr) {
2722 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2723 if (mmapThread != nullptr) {
2724 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002725 MmapPlaybackThread *mmapPlaybackThread =
2726 static_cast<MmapPlaybackThread *>(mmapThread);
2727 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002728 }
2729 }
2730 }
2731 return volumeInterface;
2732}
2733
2734Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2735{
2736 Vector <VolumeInterface *> volumeInterfaces;
2737 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002738 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002739 }
2740 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2741 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002742 MmapPlaybackThread *mmapPlaybackThread =
2743 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2744 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002745 }
2746 }
2747 return volumeInterfaces;
2748}
2749
Glenn Kasteneeecb982016-02-26 10:44:04 -08002750audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751{
Glenn Kasten9d003132016-04-06 14:38:09 -07002752 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002753 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002754 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2755 for (int retry = 0; retry < maxRetries; retry++) {
2756 // The cast allows wraparound from max positive to min negative instead of abort
2757 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2758 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2759 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2760 // allow wrap by skipping 0 and -1 for session ids
2761 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2762 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2763 return (audio_unique_id_t) (base | use);
2764 }
2765 }
2766 // We have no way of recovering from wraparound
2767 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2768 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769}
2770
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002771AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002772{
2773 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2774 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002775 if(thread->isDuplicating()) {
2776 continue;
2777 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002778 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002779 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002780 return thread;
2781 }
2782 }
2783 return NULL;
2784}
2785
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002786audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002787{
2788 PlaybackThread *thread = primaryPlaybackThread_l();
2789
2790 if (thread == NULL) {
2791 return 0;
2792 }
2793
Eric Laurentf1c04f92012-08-28 14:26:53 -07002794 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002795}
2796
Glenn Kastena7335632016-06-09 17:09:53 -07002797AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2798{
2799 size_t minFrameCount = 0;
2800 PlaybackThread *minThread = NULL;
2801 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2802 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2803 if (!thread->isDuplicating()) {
2804 size_t frameCount = thread->frameCountHAL();
2805 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2806 (frameCount == minFrameCount && thread->hasFastMixer() &&
2807 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2808 minFrameCount = frameCount;
2809 minThread = thread;
2810 }
2811 }
2812 }
2813 return minThread;
2814}
2815
Eric Laurenta011e352012-03-29 15:51:43 -07002816sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002817 audio_session_t triggerSession,
2818 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002819 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002820 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002821{
2822 Mutex::Autolock _l(mLock);
2823
2824 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2825 status_t playStatus = NAME_NOT_FOUND;
2826 status_t recStatus = NAME_NOT_FOUND;
2827 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2828 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2829 if (playStatus == NO_ERROR) {
2830 return event;
2831 }
2832 }
2833 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2834 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2835 if (recStatus == NO_ERROR) {
2836 return event;
2837 }
2838 }
2839 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2840 mPendingSyncEvents.add(event);
2841 } else {
2842 ALOGV("createSyncEvent() invalid event %d", event->type());
2843 event.clear();
2844 }
2845 return event;
2846}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002847
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848// ----------------------------------------------------------------------------
2849// Effect management
2850// ----------------------------------------------------------------------------
2851
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002852sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2853 return mEffectsFactoryHal;
2854}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855
Glenn Kastenf587ba52012-01-26 16:25:10 -08002856status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857{
2858 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002859 if (mEffectsFactoryHal.get()) {
2860 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2861 } else {
2862 return -ENODEV;
2863 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864}
2865
Glenn Kastenf587ba52012-01-26 16:25:10 -08002866status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867{
2868 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002869 if (mEffectsFactoryHal.get()) {
2870 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2871 } else {
2872 return -ENODEV;
2873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874}
2875
Glenn Kasten5e92a782012-01-30 07:40:52 -08002876status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002877 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878{
2879 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002880 if (mEffectsFactoryHal.get()) {
2881 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2882 } else {
2883 return -ENODEV;
2884 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885}
2886
2887
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002888sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 effect_descriptor_t *pDesc,
2890 const sp<IEffectClient>& effectClient,
2891 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002892 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002893 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002894 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002895 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 status_t *status,
2897 int *id,
2898 int *enabled)
2899{
2900 status_t lStatus = NO_ERROR;
2901 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903
Eric Laurentb6436272016-12-07 19:24:50 -08002904 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2905 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2906 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2907 ALOGW_IF(pid != -1 && pid != callingPid,
2908 "%s uid %d pid %d tried to pass itself off as pid %d",
2909 __func__, callingUid, callingPid, pid);
2910 pid = callingPid;
2911 }
2912
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002913 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2914 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915
2916 if (pDesc == NULL) {
2917 lStatus = BAD_VALUE;
2918 goto Exit;
2919 }
2920
Eric Laurent84e9a102010-09-23 16:10:16 -07002921 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002922 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002923 lStatus = PERMISSION_DENIED;
2924 goto Exit;
2925 }
2926
Dima Zavinfce7a472011-04-19 22:30:36 -07002927 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002928 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002929 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002930 lStatus = PERMISSION_DENIED;
2931 goto Exit;
2932 }
2933
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002934 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002935 lStatus = NO_INIT;
2936 goto Exit;
2937 }
2938
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002940 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002942 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002944 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 goto Exit;
2946 }
2947 } else {
2948 // if uuid is not specified, look for an available implementation
2949 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002950 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002951 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 lStatus = BAD_VALUE;
2953 goto Exit;
2954 }
2955 uint32_t numEffects = 0;
2956 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002957 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 bool found = false;
2959
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002960 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002962 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963 goto Exit;
2964 }
2965 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002966 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002968 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969 continue;
2970 }
2971 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2972 // If matching type found save effect descriptor. If the session is
2973 // 0 and the effect is not auxiliary, continue enumeration in case
2974 // an auxiliary version of this effect type is available
2975 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002976 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002977 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2979 break;
2980 }
2981 }
2982 }
2983 if (!found) {
2984 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002985 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 goto Exit;
2987 }
2988 // For same effect type, chose auxiliary version over insert version if
2989 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002990 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002992 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 }
2994 }
2995
2996 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002997 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2999 lStatus = INVALID_OPERATION;
3000 goto Exit;
3001 }
3002
Eric Laurent59255e42011-07-27 19:49:51 -07003003 // check recording permission for visualizer
3004 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003005 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003006 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003007 lStatus = PERMISSION_DENIED;
3008 goto Exit;
3009 }
3010
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003012 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003013 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003014 // if the output returned by getOutputForEffect() is removed before we lock the
3015 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3016 // and we will exit safely
3017 io = AudioSystem::getOutputForEffect(&desc);
3018 ALOGV("createEffect got output %d", io);
3019 }
3020
3021 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022
3023 // If output is not specified try to find a matching audio session ID in one of the
3024 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003025 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3026 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003027 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003028 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003029 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3030 // output must be specified by AudioPolicyManager when using session
3031 // AUDIO_SESSION_OUTPUT_STAGE
3032 lStatus = BAD_VALUE;
3033 goto Exit;
3034 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003035 // look for the thread where the specified audio session is present
3036 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3037 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3038 io = mPlaybackThreads.keyAt(i);
3039 break;
3040 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003042 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003043 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3044 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3045 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003046 break;
3047 }
3048 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003049 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003050 if (io == AUDIO_IO_HANDLE_NONE) {
3051 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3052 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3053 io = mMmapThreads.keyAt(i);
3054 break;
3055 }
3056 }
3057 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003058 // If no output thread contains the requested session ID, default to
3059 // first output. The effect chain will be moved to the correct output
3060 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003061 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003062 io = mPlaybackThreads.keyAt(0);
3063 }
Steve Block3856b092011-10-20 11:56:00 +01003064 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003065 }
3066 ThreadBase *thread = checkRecordThread_l(io);
3067 if (thread == NULL) {
3068 thread = checkPlaybackThread_l(io);
3069 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003070 thread = checkMmapThread_l(io);
3071 if (thread == NULL) {
3072 ALOGE("createEffect() unknown output thread");
3073 lStatus = BAD_VALUE;
3074 goto Exit;
3075 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003076 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003077 } else {
3078 // Check if one effect chain was awaiting for an effect to be created on this
3079 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003080 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003081 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003082 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003083 thread->addEffectChain_l(chain);
3084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003086
Eric Laurent021cf962014-05-13 10:18:14 -07003087 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003089 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003090 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003091 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003092 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003093 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003094 // remove local strong reference to Client with mClientLock held
3095 Mutex::Autolock _cl(mClientLock);
3096 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003097 } else {
3098 // handle must be valid here, but check again to be safe.
3099 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003100 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101 }
3102
haobo101735295ff7b0d2017-03-17 17:44:03 +08003103 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3104 // handle must be cleared outside lock.
3105 handle.clear();
3106 }
3107
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003109 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003110 return handle;
3111}
3112
Glenn Kastend848eb42016-03-08 13:42:11 -08003113status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003114 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003115{
Steve Block3856b092011-10-20 11:56:00 +01003116 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003117 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003118 Mutex::Autolock _l(mLock);
3119 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003120 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003121 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003122 }
Eric Laurentde070132010-07-13 04:45:46 -07003123 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3124 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003125 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003126 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 }
Eric Laurentde070132010-07-13 04:45:46 -07003128 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3129 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003130 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003131 return BAD_VALUE;
3132 }
3133
3134 Mutex::Autolock _dl(dstThread->mLock);
3135 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003136 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137}
3138
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003139// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003140status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003141 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003142 AudioFlinger::PlaybackThread *dstThread,
3143 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003144{
Steve Block3856b092011-10-20 11:56:00 +01003145 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003146 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003147
Eric Laurent59255e42011-07-27 19:49:51 -07003148 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003149 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003150 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003151 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003152 return INVALID_OPERATION;
3153 }
3154
Eric Laurent4c415062016-06-17 16:14:16 -07003155 // Check whether the destination thread and all effects in the chain are compatible
3156 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003157 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003158 " destination thread %p is not compatible with effects in the chain",
3159 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003160 return INVALID_OPERATION;
3161 }
3162
Eric Laurent39e94f82010-07-28 01:32:47 -07003163 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003164 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003165 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003166 // removed.
3167 srcThread->removeEffectChain_l(chain);
3168
3169 // transfer all effects one by one so that new effect chain is created on new thread with
3170 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003171 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003172 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003173 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003174 Vector< sp<EffectModule> > removed;
3175 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003176 while (effect != 0) {
3177 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003178 removed.add(effect);
3179 status = dstThread->addEffect_l(effect);
3180 if (status != NO_ERROR) {
3181 break;
3182 }
Eric Laurentec35a142011-10-05 17:42:25 -07003183 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3184 if (effect->state() == EffectModule::ACTIVE ||
3185 effect->state() == EffectModule::STOPPING) {
3186 effect->start();
3187 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003188 // if the move request is not received from audio policy manager, the effect must be
3189 // re-registered with the new strategy and output
3190 if (dstChain == 0) {
3191 dstChain = effect->chain().promote();
3192 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003193 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003194 status = NO_INIT;
3195 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003196 }
3197 strategy = dstChain->strategy();
3198 }
3199 if (reRegister) {
3200 AudioSystem::unregisterEffect(effect->id());
3201 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003202 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003203 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003204 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003205 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003206 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003207 }
Eric Laurentde070132010-07-13 04:45:46 -07003208 effect = chain->getEffectFromId_l(0);
3209 }
3210
Eric Laurent5baf2af2013-09-12 17:37:00 -07003211 if (status != NO_ERROR) {
3212 for (size_t i = 0; i < removed.size(); i++) {
3213 srcThread->addEffect_l(removed[i]);
3214 if (dstChain != 0 && reRegister) {
3215 AudioSystem::unregisterEffect(removed[i]->id());
3216 AudioSystem::registerEffect(&removed[i]->desc(),
3217 srcThread->id(),
3218 strategy,
3219 sessionId,
3220 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003221 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003222 }
3223 }
3224 }
3225
3226 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227}
3228
Eric Laurent5baf2af2013-09-12 17:37:00 -07003229bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003230{
3231 if (mGlobalEffectEnableTime != 0 &&
3232 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3233 return true;
3234 }
3235
3236 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3237 sp<EffectChain> ec =
3238 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003239 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003240 return true;
3241 }
3242 }
3243 return false;
3244}
3245
Eric Laurent5baf2af2013-09-12 17:37:00 -07003246void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003247{
3248 Mutex::Autolock _l(mLock);
3249
3250 mGlobalEffectEnableTime = systemTime();
3251
3252 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3253 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3254 if (t->mType == ThreadBase::OFFLOAD) {
3255 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3256 }
3257 }
3258
3259}
3260
Eric Laurentaaa44472014-09-12 17:41:50 -07003261status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3262{
Eric Laurentd8365c52017-07-16 15:27:05 -07003263 // clear possible suspended state before parking the chain so that it starts in default state
3264 // when attached to a new record thread
3265 chain->setEffectSuspended_l(FX_IID_AEC, false);
3266 chain->setEffectSuspended_l(FX_IID_NS, false);
3267
Glenn Kastend848eb42016-03-08 13:42:11 -08003268 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003269 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003270 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003271 if (index >= 0) {
3272 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3273 return ALREADY_EXISTS;
3274 }
3275 mOrphanEffectChains.add(session, chain);
3276 return NO_ERROR;
3277}
3278
3279sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3280{
3281 sp<EffectChain> chain;
3282 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003283 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003284 if (index >= 0) {
3285 chain = mOrphanEffectChains.valueAt(index);
3286 mOrphanEffectChains.removeItemsAt(index);
3287 }
3288 return chain;
3289}
3290
3291bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3292{
3293 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003294 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003295 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003296 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003297 if (index >= 0) {
3298 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003299 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003300 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003301 mOrphanEffectChains.removeItemsAt(index);
3302 }
3303 return true;
3304 }
3305 return false;
3306}
3307
3308
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309// ----------------------------------------------------------------------------
3310
3311status_t AudioFlinger::onTransact(
3312 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3313{
3314 return BnAudioFlinger::onTransact(code, data, reply, flags);
3315}
3316
Glenn Kasten63238ef2015-03-02 15:50:29 -08003317} // namespace android