blob: 0d6ef46b4c53875162e4a4b55e8a26404042cec8 [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>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/time.h>
28#include <sys/resource.h>
29
Gloria Wang9ee159b2011-02-24 14:51:45 -080030#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/IServiceManager.h>
32#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>
Wei Jia3f273d12015-11-24 09:06:49 -080066#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070067#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
rago3bd1c872016-09-26 12:58:14 -070070//#define BUFLOG_NDEBUG 0
71#include <BufLog.h>
72
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080073#include "TypedLogger.h"
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
John Grossman1c345192012-03-27 14:00:17 -070077// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
Eric Laurentde070132010-07-13 04:45:46 -070089
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Glenn Kastenec1d6b52011-12-12 09:04:45 -080092static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
93static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070094static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070095static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070096
Glenn Kasten58912562012-04-03 10:45:00 -070097
John Grossman4ff14ba2012-02-08 16:37:41 -080098nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700101
Eric Laurent813e2a72013-08-31 12:59:48 -0700102// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
103// we define a minimum time during which a global effect is considered enabled.
104static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
105
Eric Laurentfc235202016-12-20 18:48:17 -0800106Mutex gLock;
107wp<AudioFlinger> gAudioFlinger;
108
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700109// Keep a strong reference to media.log service around forever.
110// The service is within our parent process so it can never die in a way that we could observe.
111// These two variables are const after initialization.
112static sp<IBinder> sMediaLogServiceAsBinder;
113static sp<IMediaLogService> sMediaLogService;
114
115static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
116
117static void sMediaLogInit()
118{
119 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
120 if (sMediaLogServiceAsBinder != 0) {
121 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
122 }
123}
124
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125// ----------------------------------------------------------------------------
126
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700127std::string formatToString(audio_format_t format) {
128 std::string result;
129 FormatConverter::toString(format, result);
130 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800131}
132
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133// ----------------------------------------------------------------------------
134
135AudioFlinger::AudioFlinger()
136 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800137 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800138 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800139 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700140 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800141 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800142 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700143 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800144 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700145 mBtNrecIsOff(false),
146 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700147 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800148 mTotalMemory(0),
149 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700150 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700151 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700152 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700153{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700154 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
155 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
156 // zero ID has a special meaning, so unavailable
157 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
158 }
159
Glenn Kastenae0cff12016-02-24 13:57:49 -0800160 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800161 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800162 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
163 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700164 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800165 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700166
Wei Jia3f273d12015-11-24 09:06:49 -0800167 // reset battery stats.
168 // if the audio service has crashed, battery stats could be left
169 // in bad state, reset the state upon service start.
170 BatteryNotifier::getInstance().noteResetAudio();
171
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700172 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700173 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
174
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800175 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700176}
177
178void AudioFlinger::onFirstRef()
179{
Eric Laurent93575202011-01-18 18:39:02 -0800180 Mutex::Autolock _l(mLock);
181
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800183 char val_str[PROPERTY_VALUE_MAX] = { 0 };
184 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
185 uint32_t int_val;
186 if (1 == sscanf(val_str, "%u", &int_val)) {
187 mStandbyTimeInNsecs = milliseconds(int_val);
188 ALOGI("Using %u mSec as standby time.", int_val);
189 } else {
190 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
191 ALOGI("Using default %u mSec as standby time.",
192 (uint32_t)(mStandbyTimeInNsecs / 1000000));
193 }
194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700195
Eric Laurenta4c5a552012-03-29 10:12:40 -0700196 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800197
198 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700199}
200
201AudioFlinger::~AudioFlinger()
202{
203 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700204 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700205 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700206 }
207 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700208 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700209 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700211
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800212 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
213 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700214 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700216
217 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700218 if (sMediaLogService != 0) {
219 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
220 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
221 mUnregisteredWriters.pop();
222 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700223 }
224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225}
226
Eric Laurentfc235202016-12-20 18:48:17 -0800227//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800228__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800229status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
230 const audio_attributes_t *attr,
231 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700232 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800233 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800234 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800235 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700236 sp<MmapStreamInterface>& interface,
237 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800238{
239 sp<AudioFlinger> af;
240 {
241 Mutex::Autolock _l(gLock);
242 af = gAudioFlinger.promote();
243 }
244 status_t ret = NO_INIT;
245 if (af != 0) {
246 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800247 direction, attr, config, client, deviceId,
248 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800249 }
250 return ret;
251}
252
Eric Laurent6acd1d42017-01-04 14:23:29 -0800253status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
254 const audio_attributes_t *attr,
255 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700256 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800257 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800258 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800259 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700260 sp<MmapStreamInterface>& interface,
261 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800262{
263 status_t ret = initCheck();
264 if (ret != NO_ERROR) {
265 return ret;
266 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800267 audio_session_t actualSessionId = *sessionId;
268 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
269 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
270 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800271 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700272 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800273 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
274 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
275 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
276 fullConfig.sample_rate = config->sample_rate;
277 fullConfig.channel_mask = config->channel_mask;
278 fullConfig.format = config->format;
279 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800280 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200281 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800282 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800283 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
284 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700285 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800286 } else {
287 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800288 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800289 client.clientPid,
290 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800291 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800292 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700293 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800294 }
295 if (ret != NO_ERROR) {
296 return ret;
297 }
298
299 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
300 // audio policy manager and we can retrieve it
301 sp<MmapThread> thread = mMmapThreads.valueFor(io);
302 if (thread != 0) {
303 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800304 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700305 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800306 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800307 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700308 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700309 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700310 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800311 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700312 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800313 ret = NO_INIT;
314 }
315
316 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
317
Eric Laurentfc235202016-12-20 18:48:17 -0800318 return ret;
319}
320
Eric Laurenta4c5a552012-03-29 10:12:40 -0700321static const char * const audio_interfaces[] = {
322 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
323 AUDIO_HARDWARE_MODULE_ID_A2DP,
324 AUDIO_HARDWARE_MODULE_ID_USB,
325};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700326
Phil Burk062e67a2015-02-11 13:40:50 -0800327AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700328 audio_module_handle_t module,
329 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700330{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700331 // if module is 0, the request comes from an old policy manager and we should load
332 // well known modules
333 if (module == 0) {
334 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700335 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700336 loadHwModule_l(audio_interfaces[i]);
337 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700338 // then try to find a module supporting the requested device.
339 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
340 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700341 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
342 uint32_t supportedDevices;
343 if (dev->getSupportedDevices(&supportedDevices) == OK &&
344 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700345 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700346 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700347 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700348 } else {
349 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700350 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
351 if (audioHwDevice != NULL) {
352 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700353 }
354 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355
Dima Zavin799a70e2011-04-18 16:57:27 -0700356 return NULL;
357}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700358
Glenn Kasten0f11b512014-01-31 16:18:54 -0800359void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360{
361 const size_t SIZE = 256;
362 char buffer[SIZE];
363 String8 result;
364
365 result.append("Clients:\n");
366 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800367 sp<Client> client = mClients.valueAt(i).promote();
368 if (client != 0) {
369 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
370 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700373
Eric Laurentd1b28d42013-09-18 18:47:13 -0700374 result.append("Notification Clients:\n");
375 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
376 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
377 result.append(buffer);
378 }
379
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700380 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800381 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700382 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
383 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800384 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700385 result.append(buffer);
386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388}
389
390
Glenn Kasten0f11b512014-01-31 16:18:54 -0800391void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392{
393 const size_t SIZE = 256;
394 char buffer[SIZE];
395 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800396 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397
John Grossman4ff14ba2012-02-08 16:37:41 -0800398 snprintf(buffer, SIZE, "Hardware status: %d\n"
399 "Standby Time mSec: %u\n",
400 hardwareStatus,
401 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402 result.append(buffer);
403 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404}
405
Glenn Kasten0f11b512014-01-31 16:18:54 -0800406void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407{
408 const size_t SIZE = 256;
409 char buffer[SIZE];
410 String8 result;
411 snprintf(buffer, SIZE, "Permission Denial: "
412 "can't dump AudioFlinger from pid=%d, uid=%d\n",
413 IPCThreadState::self()->getCallingPid(),
414 IPCThreadState::self()->getCallingUid());
415 result.append(buffer);
416 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417}
418
Eric Laurent81784c32012-11-19 14:55:58 -0800419bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420{
421 bool locked = false;
422 for (int i = 0; i < kDumpLockRetries; ++i) {
423 if (mutex.tryLock() == NO_ERROR) {
424 locked = true;
425 break;
426 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800427 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428 }
429 return locked;
430}
431
432status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
433{
Glenn Kasten44deb052012-02-05 18:09:08 -0800434 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 dumpPermissionDenial(fd, args);
436 } else {
437 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800438 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 if (!hardwareLocked) {
440 String8 result(kHardwareLockedString);
441 write(fd, result.string(), result.size());
442 } else {
443 mHardwareLock.unlock();
444 }
445
Eric Tan7b651152018-07-13 10:17:19 -0700446 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447
448 // failed to lock - AudioFlinger is probably deadlocked
449 if (!locked) {
450 String8 result(kDeadlockedString);
451 write(fd, result.string(), result.size());
452 }
453
Eric Laurent021cf962014-05-13 10:18:14 -0700454 bool clientLocked = dumpTryLock(mClientLock);
455 if (!clientLocked) {
456 String8 result(kClientLockedString);
457 write(fd, result.string(), result.size());
458 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700459
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700460 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700461 mEffectsFactoryHal->dumpEffects(fd);
462 } else {
463 String8 result(kNoEffectsFactory);
464 write(fd, result.string(), result.size());
465 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700466
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700468 if (clientLocked) {
469 mClientLock.unlock();
470 }
471
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 dumpInternals(fd, args);
473
474 // dump playback threads
475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
476 mPlaybackThreads.valueAt(i)->dump(fd, args);
477 }
478
479 // dump record threads
480 for (size_t i = 0; i < mRecordThreads.size(); i++) {
481 mRecordThreads.valueAt(i)->dump(fd, args);
482 }
483
Eric Laurent6acd1d42017-01-04 14:23:29 -0800484 // dump mmap threads
485 for (size_t i = 0; i < mMmapThreads.size(); i++) {
486 mMmapThreads.valueAt(i)->dump(fd, args);
487 }
488
Eric Laurentaaa44472014-09-12 17:41:50 -0700489 // dump orphan effect chains
490 if (mOrphanEffectChains.size() != 0) {
491 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
492 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
493 mOrphanEffectChains.valueAt(i)->dump(fd, args);
494 }
495 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700496 // dump all hardware devs
497 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700498 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
499 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700501
Mikhail Naganov201369b2018-05-16 16:52:32 -0700502 mPatchPanel.dump(fd);
503
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700504 // dump external setParameters
505 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
506 dprintf(fd, "\n%s setParameters:\n", name);
507 logger.dump(fd, " " /* prefix */);
508 };
509 dumpLogger(mRejectedSetParameterLog, "Rejected");
510 dumpLogger(mAppSetParameterLog, "App");
511 dumpLogger(mSystemSetParameterLog, "System");
512
Andy Hunga8115dc2018-08-24 15:51:59 -0700513 // dump historical threads in the last 10 seconds
514 const std::string threadLog = mThreadLog.dumpToString(
515 "Historical Thread Log ", 0 /* lines */,
516 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
517 write(fd, threadLog.c_str(), threadLog.size());
518
rago3bd1c872016-09-26 12:58:14 -0700519 BUFLOG_RESET;
520
Glenn Kastend65d73c2012-06-22 17:21:07 -0700521 if (locked) {
522 mLock.unlock();
523 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800524
Andy Hung8946a282018-04-19 20:04:56 -0700525#ifdef TEE_SINK
526 // NBAIO_Tee dump is safe to call outside of AF lock.
527 NBAIO_Tee::dumpAll(fd, "_DUMP");
528#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800529 // append a copy of media.log here by forwarding fd to it, but don't attempt
530 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700531 if (sMediaLogServiceAsBinder != 0) {
532 dprintf(fd, "\nmedia.log:\n");
533 Vector<String16> args;
534 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800535 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700536
537 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700538 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700539 bool unreachableMemory = false;
540 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700541 if (arg == String16("-m")) {
542 dumpMem = true;
543 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700544 unreachableMemory = true;
545 }
546 }
547
Andy Hung07b745e2016-05-23 16:21:07 -0700548 if (dumpMem) {
549 dprintf(fd, "\nDumping memory:\n");
550 std::string s = dumpMemoryAddresses(100 /* limit */);
551 write(fd, s.c_str(), s.size());
552 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700553 if (unreachableMemory) {
554 dprintf(fd, "\nDumping unreachable memory:\n");
555 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700556 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700557 write(fd, s.c_str(), s.size());
558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 }
560 return NO_ERROR;
561}
562
Eric Laurent021cf962014-05-13 10:18:14 -0700563sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800564{
Eric Laurent021cf962014-05-13 10:18:14 -0700565 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800566 // If pid is already in the mClients wp<> map, then use that entry
567 // (for which promote() is always != 0), otherwise create a new entry and Client.
568 sp<Client> client = mClients.valueFor(pid).promote();
569 if (client == 0) {
570 client = new Client(this, pid);
571 mClients.add(pid, client);
572 }
573
574 return client;
575}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576
Glenn Kasten9e58b552013-01-18 15:09:48 -0800577sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
578{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700579 // If there is no memory allocated for logs, return a dummy writer that does nothing.
580 // Similarly if we can't contact the media.log service, also return a dummy writer.
581 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800582 return new NBLog::Writer();
583 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700584 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
585 // If allocation fails, consult the vector of previously unregistered writers
586 // and garbage-collect one or more them until an allocation succeeds
587 if (shared == 0) {
588 Mutex::Autolock _l(mUnregisteredWritersLock);
589 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
590 {
591 // Pick the oldest stale writer to garbage-collect
592 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
593 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700594 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700595 // Now the media.log remote reference to IMemory is gone. When our last local
596 // reference to IMemory also drops to zero at end of this block,
597 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
598 }
599 // Re-attempt the allocation
600 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
601 if (shared != 0) {
602 goto success;
603 }
604 }
605 // Even after garbage-collecting all old writers, there is still not enough memory,
606 // so return a dummy writer
607 return new NBLog::Writer();
608 }
609success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800610 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
611 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
612 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700613 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800614 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800615}
616
617void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
618{
Glenn Kasten685ef092013-02-04 08:15:34 -0800619 if (writer == 0) {
620 return;
621 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800622 sp<IMemory> iMemory(writer->getIMemory());
623 if (iMemory == 0) {
624 return;
625 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700626 // Rather than removing the writer immediately, append it to a queue of old writers to
627 // be garbage-collected later. This allows us to continue to view old logs for a while.
628 Mutex::Autolock _l(mUnregisteredWritersLock);
629 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800630}
631
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632// IAudioFlinger interface
633
Eric Laurent21da6472017-11-09 16:29:26 -0800634sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
635 CreateTrackOutput& output,
636 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637{
638 sp<PlaybackThread::Track> track;
639 sp<TrackHandle> trackHandle;
640 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800642 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800643 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644
Eric Laurent21da6472017-11-09 16:29:26 -0800645 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700646 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800647 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700648 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800649 ALOGW_IF(clientUid != callingUid,
650 "%s uid %d tried to pass itself off as %d",
651 __FUNCTION__, callingUid, clientUid);
652 clientUid = callingUid;
653 updatePid = true;
654 }
655 pid_t clientPid = input.clientInfo.clientPid;
656 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700657 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800658 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700659 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800660 __func__, callingUid, callingPid, clientPid);
661 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700662 }
663
Eric Laurent21da6472017-11-09 16:29:26 -0800664 audio_session_t sessionId = input.sessionId;
665 if (sessionId == AUDIO_SESSION_ALLOCATE) {
666 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800667 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
668 lStatus = BAD_VALUE;
669 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800670 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800671
Eric Laurent21da6472017-11-09 16:29:26 -0800672 output.sessionId = sessionId;
673 output.outputId = AUDIO_IO_HANDLE_NONE;
674 output.selectedDeviceId = input.selectedDeviceId;
675
676 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200677 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800678 &output.selectedDeviceId, &portId);
679
680 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
681 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
682 goto Exit;
683 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800684 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
685 // but if someone uses binder directly they could bypass that and cause us to crash
686 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000687 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 lStatus = BAD_VALUE;
689 goto Exit;
690 }
691
Glenn Kasten53b5d092014-02-05 10:00:23 -0800692 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800693 if (!audio_is_output_channel(input.config.channel_mask)) {
694 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800695 lStatus = BAD_VALUE;
696 goto Exit;
697 }
698
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700699 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800700 if (!audio_is_valid_format(input.config.format)) {
701 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700702 lStatus = BAD_VALUE;
703 goto Exit;
704 }
705
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 {
707 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800708 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800710 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 lStatus = BAD_VALUE;
712 goto Exit;
713 }
714
Eric Laurent21da6472017-11-09 16:29:26 -0800715 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716
Glenn Kastene848bd92014-03-13 15:00:32 -0700717 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800718 // check if an effect chain with the same session ID is present on another
719 // output thread and move it here.
720 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
721 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
722 if (mPlaybackThreads.keyAt(i) != output.outputId) {
723 uint32_t sessions = t->hasAudioSession(sessionId);
724 if (sessions & ThreadBase::EFFECT_SESSION) {
725 effectThread = t.get();
726 break;
Eric Laurentde070132010-07-13 04:45:46 -0700727 }
728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 }
Eric Laurent21da6472017-11-09 16:29:26 -0800730 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731
Eric Laurent21da6472017-11-09 16:29:26 -0800732 output.sampleRate = input.config.sample_rate;
733 output.frameCount = input.frameCount;
734 output.notificationFrameCount = input.notificationFrameCount;
735 output.flags = input.flags;
736
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700737 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
738 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800739 &output.frameCount, &output.notificationFrameCount,
740 input.notificationsPerBuffer, input.speed,
741 input.sharedBuffer, sessionId, &output.flags,
742 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800743 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700744 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700745
Eric Laurent21da6472017-11-09 16:29:26 -0800746 output.afFrameCount = thread->frameCount();
747 output.afSampleRate = thread->sampleRate();
748 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800749 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800750
Eric Laurent39e94f82010-07-28 01:32:47 -0700751 // move effect chain to this output thread if an effect on same session was waiting
752 // for a track to be created
753 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700754 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700755 Mutex::Autolock _dl(thread->mLock);
756 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800757 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700758 }
Eric Laurenta011e352012-03-29 15:51:43 -0700759
760 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700761 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800762 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700763 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700764 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700765 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700766 } else {
767 mPendingSyncEvents[i]->cancel();
768 }
Eric Laurenta011e352012-03-29 15:51:43 -0700769 mPendingSyncEvents.removeAt(i);
770 i--;
771 }
772 }
773 }
Glenn Kastene198c362013-08-13 09:13:36 -0700774
Eric Laurent21da6472017-11-09 16:29:26 -0800775 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700776 }
Glenn Kastene198c362013-08-13 09:13:36 -0700777
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700778 if (lStatus != NO_ERROR) {
779 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700780 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700781 // Don't hold mClientLock when releasing the reference on the track as the
782 // destructor will acquire it.
783 {
784 Mutex::Autolock _cl(mClientLock);
785 client.clear();
786 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700788 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789 }
790
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700791 // return handle to client
792 trackHandle = new TrackHandle(track);
793
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800795 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700796 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800797 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700798 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799 return trackHandle;
800}
801
Glenn Kasten2c073da2016-02-26 09:14:08 -0800802uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803{
804 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800805 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800807 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 return 0;
809 }
810 return thread->sampleRate();
811}
812
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800813audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814{
815 Mutex::Autolock _l(mLock);
816 PlaybackThread *thread = checkPlaybackThread_l(output);
817 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000818 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800819 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 }
821 return thread->format();
822}
823
Glenn Kasten2c073da2016-02-26 09:14:08 -0800824size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825{
826 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800827 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800829 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 return 0;
831 }
Glenn Kasten58912562012-04-03 10:45:00 -0700832 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
833 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 return thread->frameCount();
835}
836
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700837size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
838{
839 Mutex::Autolock _l(mLock);
840 ThreadBase *thread = checkThread_l(ioHandle);
841 if (thread == NULL) {
842 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
843 return 0;
844 }
845 return thread->frameCountHAL();
846}
847
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800848uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849{
850 Mutex::Autolock _l(mLock);
851 PlaybackThread *thread = checkPlaybackThread_l(output);
852 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800853 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 return 0;
855 }
856 return thread->latency();
857}
858
859status_t AudioFlinger::setMasterVolume(float value)
860{
Eric Laurenta1884f92011-08-23 08:25:03 -0700861 status_t ret = initCheck();
862 if (ret != NO_ERROR) {
863 return ret;
864 }
865
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 // check calling permissions
867 if (!settingsAllowed()) {
868 return PERMISSION_DENIED;
869 }
870
Eric Laurenta4c5a552012-03-29 10:12:40 -0700871 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700872 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700873
John Grossmanee578c02012-07-23 17:05:46 -0700874 // Set master volume in the HALs which support it.
875 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
876 AutoMutex lock(mHardwareLock);
877 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800878
John Grossmanee578c02012-07-23 17:05:46 -0700879 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
880 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700881 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800882 }
John Grossmanee578c02012-07-23 17:05:46 -0700883 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885
John Grossmanee578c02012-07-23 17:05:46 -0700886 // Now set the master volume in each playback thread. Playback threads
887 // assigned to HALs which do not have master volume support will apply
888 // master volume during the mix operation. Threads with HALs which do
889 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700890 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
891 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
892 continue;
893 }
John Grossmanee578c02012-07-23 17:05:46 -0700894 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700895 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896
897 return NO_ERROR;
898}
899
Glenn Kastenf78aee72012-01-04 11:00:47 -0800900status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901{
Eric Laurenta1884f92011-08-23 08:25:03 -0700902 status_t ret = initCheck();
903 if (ret != NO_ERROR) {
904 return ret;
905 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906
907 // check calling permissions
908 if (!settingsAllowed()) {
909 return PERMISSION_DENIED;
910 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800911 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000912 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 return BAD_VALUE;
914 }
915
916 { // scope for the lock
917 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700918 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700920 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 mHardwareStatus = AUDIO_HW_IDLE;
922 }
923
924 if (NO_ERROR == ret) {
925 Mutex::Autolock _l(mLock);
926 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800927 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700928 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 }
930
931 return ret;
932}
933
934status_t AudioFlinger::setMicMute(bool state)
935{
Eric Laurenta1884f92011-08-23 08:25:03 -0700936 status_t ret = initCheck();
937 if (ret != NO_ERROR) {
938 return ret;
939 }
940
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941 // check calling permissions
942 if (!settingsAllowed()) {
943 return PERMISSION_DENIED;
944 }
945
946 AutoMutex lock(mHardwareLock);
947 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700948 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700949 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
950 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700951 if (result != NO_ERROR) {
952 ret = result;
953 }
954 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 mHardwareStatus = AUDIO_HW_IDLE;
956 return ret;
957}
958
959bool AudioFlinger::getMicMute() const
960{
Eric Laurenta1884f92011-08-23 08:25:03 -0700961 status_t ret = initCheck();
962 if (ret != NO_ERROR) {
963 return false;
964 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800965 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700966 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800967 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700968 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800969 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700970 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
971 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800972 if (result == NO_ERROR) {
973 mute = mute && state;
974 }
975 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800977
978 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979}
980
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800981void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
982{
983 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
984
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800985 AutoMutex lock(mLock);
986 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -0700987 mRecordThreads[i]->setRecordSilenced(uid, silenced);
988 }
989 for (size_t i = 0; i < mMmapThreads.size(); i++) {
990 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800991 }
992}
993
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994status_t AudioFlinger::setMasterMute(bool muted)
995{
John Grossmand8f178d2012-07-20 14:51:35 -0700996 status_t ret = initCheck();
997 if (ret != NO_ERROR) {
998 return ret;
999 }
1000
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 // check calling permissions
1002 if (!settingsAllowed()) {
1003 return PERMISSION_DENIED;
1004 }
1005
John Grossmanee578c02012-07-23 17:05:46 -07001006 Mutex::Autolock _l(mLock);
1007 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001008
John Grossmanee578c02012-07-23 17:05:46 -07001009 // Set master mute in the HALs which support it.
1010 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1011 AutoMutex lock(mHardwareLock);
1012 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001013
John Grossmanee578c02012-07-23 17:05:46 -07001014 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1015 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001016 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001017 }
John Grossmanee578c02012-07-23 17:05:46 -07001018 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001019 }
1020
John Grossmanee578c02012-07-23 17:05:46 -07001021 // Now set the master mute in each playback thread. Playback threads
1022 // assigned to HALs which do not have master mute support will apply master
1023 // mute during the mix operation. Threads with HALs which do support master
1024 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001025 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1026 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1027 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001028 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029
1030 return NO_ERROR;
1031}
1032
1033float AudioFlinger::masterVolume() const
1034{
Glenn Kasten98067102011-12-13 11:47:54 -08001035 Mutex::Autolock _l(mLock);
1036 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037}
1038
1039bool AudioFlinger::masterMute() const
1040{
Glenn Kasten98067102011-12-13 11:47:54 -08001041 Mutex::Autolock _l(mLock);
1042 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043}
1044
John Grossman4ff14ba2012-02-08 16:37:41 -08001045float AudioFlinger::masterVolume_l() const
1046{
John Grossman4ff14ba2012-02-08 16:37:41 -08001047 return mMasterVolume;
1048}
1049
John Grossmand8f178d2012-07-20 14:51:35 -07001050bool AudioFlinger::masterMute_l() const
1051{
John Grossmanee578c02012-07-23 17:05:46 -07001052 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001053}
1054
Eric Laurent223fd5c2014-11-11 13:43:36 -08001055status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1056{
1057 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001058 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001059 return BAD_VALUE;
1060 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001061 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1062 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1063 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001064 return PERMISSION_DENIED;
1065 }
1066
1067 return NO_ERROR;
1068}
1069
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001070status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1071 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072{
1073 // check calling permissions
1074 if (!settingsAllowed()) {
1075 return PERMISSION_DENIED;
1076 }
1077
Eric Laurent223fd5c2014-11-11 13:43:36 -08001078 status_t status = checkStreamType(stream);
1079 if (status != NO_ERROR) {
1080 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 }
Eric Laurent98e38192018-02-15 18:31:53 -08001082 if (output == AUDIO_IO_HANDLE_NONE) {
1083 return BAD_VALUE;
1084 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001085 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086
1087 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001088 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1089 if (volumeInterface == NULL) {
1090 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 }
Eric Laurent98e38192018-02-15 18:31:53 -08001092 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093
1094 return NO_ERROR;
1095}
1096
Glenn Kastenfff6d712012-01-12 16:38:12 -08001097status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098{
1099 // check calling permissions
1100 if (!settingsAllowed()) {
1101 return PERMISSION_DENIED;
1102 }
1103
Eric Laurent223fd5c2014-11-11 13:43:36 -08001104 status_t status = checkStreamType(stream);
1105 if (status != NO_ERROR) {
1106 return status;
1107 }
1108 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1109
1110 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001111 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 return BAD_VALUE;
1113 }
1114
Eric Laurent93575202011-01-18 18:39:02 -08001115 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001117 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1118 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1119 volumeInterfaces[i]->setStreamMute(stream, muted);
1120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121
1122 return NO_ERROR;
1123}
1124
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001125float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001127 status_t status = checkStreamType(stream);
1128 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 return 0.0f;
1130 }
Eric Laurent98e38192018-02-15 18:31:53 -08001131 if (output == AUDIO_IO_HANDLE_NONE) {
1132 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 }
1134
Eric Laurent98e38192018-02-15 18:31:53 -08001135 AutoMutex lock(mLock);
1136 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1137 if (volumeInterface == NULL) {
1138 return 0.0f;
1139 }
1140
1141 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142}
1143
Glenn Kastenfff6d712012-01-12 16:38:12 -08001144bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001146 status_t status = checkStreamType(stream);
1147 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 return true;
1149 }
1150
Glenn Kasten6637baa2012-01-09 09:40:36 -08001151 AutoMutex lock(mLock);
1152 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153}
1154
Eric Laurent054d9d32015-04-24 08:48:48 -07001155
1156void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1157{
1158 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1159 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1160 }
1161}
1162
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001163// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1164void AudioFlinger::forwardParametersToDownstreamPatches_l(
1165 audio_io_handle_t upStream, const String8& keyValuePairs,
1166 std::function<bool(const sp<PlaybackThread>&)> useThread)
1167{
1168 std::vector<PatchPanel::SoftwarePatch> swPatches;
1169 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1170 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1171 __func__, swPatches.size(), upStream);
1172 for (const auto& swPatch : swPatches) {
1173 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1174 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1175 downStream->setParameters(keyValuePairs);
1176 }
1177 }
1178}
1179
Eric Laurentf1047e82018-04-16 19:18:20 -07001180// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1181// Some keys are used for audio routing and audio path configuration and should be reserved for use
1182// by audio policy and audio flinger for functional, privacy and security reasons.
1183void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1184{
1185 static const String8 kReservedParameters[] = {
1186 String8(AudioParameter::keyRouting),
1187 String8(AudioParameter::keySamplingRate),
1188 String8(AudioParameter::keyFormat),
1189 String8(AudioParameter::keyChannels),
1190 String8(AudioParameter::keyFrameCount),
1191 String8(AudioParameter::keyInputSource),
1192 String8(AudioParameter::keyMonoOutput),
1193 String8(AudioParameter::keyStreamConnect),
1194 String8(AudioParameter::keyStreamDisconnect),
1195 String8(AudioParameter::keyStreamSupportedFormats),
1196 String8(AudioParameter::keyStreamSupportedChannels),
1197 String8(AudioParameter::keyStreamSupportedSamplingRates),
1198 };
1199
Andy Hung4ef19fa2018-05-15 19:35:29 -07001200 if (isAudioServerUid(callingUid)) {
1201 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001202 }
1203
1204 AudioParameter param = AudioParameter(keyValuePairs);
1205 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001206 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001207 for (auto& key : kReservedParameters) {
1208 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001209 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001210 param.remove(key);
1211 }
1212 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001213 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1214 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001215 keyValuePairs = param.toString();
1216}
1217
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001218void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1219 size_t rejectedKVPSize, const String8& rejectedKVPs,
1220 uid_t callingUid) {
1221 auto prefix = String8::format("UID %5d", callingUid);
1222 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1223 if (rejectedKVPSize != 0) {
1224 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1225 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1226 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1227 } else {
1228 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1229 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1230 }
1231}
1232
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001233status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234{
Eric Laurentf1047e82018-04-16 19:18:20 -07001235 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1236 ioHandle, keyValuePairs.string(),
1237 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001238
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 // check calling permissions
1240 if (!settingsAllowed()) {
1241 return PERMISSION_DENIED;
1242 }
1243
Eric Laurentf1047e82018-04-16 19:18:20 -07001244 String8 filteredKeyValuePairs = keyValuePairs;
1245 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1246
1247 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1248
Glenn Kasten142f5192014-03-25 17:44:59 -07001249 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1250 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001251 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001252 // result will remain NO_INIT if no audio device is present
1253 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001254 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001255 AutoMutex lock(mHardwareLock);
1256 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1257 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001258 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001259 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001260 // return success if at least one audio device accepts the parameters as not all
1261 // HALs are requested to support all parameters. If no audio device supports the
1262 // requested parameters, the last error is reported.
1263 if (final_result != NO_ERROR) {
1264 final_result = result;
1265 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001266 }
1267 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001268 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001269 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001270 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001271 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001272 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1273 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001274 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001275 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001276 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001277 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001278 }
1279 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001280 String8 screenState;
1281 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001282 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001283 if (isOff != (AudioFlinger::mScreenState & 1)) {
1284 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001285 }
1286 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001287 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288 }
1289
1290 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1291 // and the thread is exited once the lock is released
1292 sp<ThreadBase> thread;
1293 {
1294 Mutex::Autolock _l(mLock);
1295 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001296 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001298 if (thread == 0) {
1299 thread = checkMmapThread_l(ioHandle);
1300 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001301 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001302 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001303 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001304 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001305 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1306 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001307 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001308 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309 }
1310 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001311 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001312 status_t result = thread->setParameters(filteredKeyValuePairs);
1313 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1314 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315 }
1316 return BAD_VALUE;
1317}
1318
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001319String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001321 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1322 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001323
Eric Laurenta4c5a552012-03-29 10:12:40 -07001324 Mutex::Autolock _l(mLock);
1325
Glenn Kasten142f5192014-03-25 17:44:59 -07001326 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001327 String8 out_s8;
1328
Dima Zavin799a70e2011-04-18 16:57:27 -07001329 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001330 String8 s;
1331 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001332 {
1333 AutoMutex lock(mHardwareLock);
1334 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001335 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1336 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001337 mHardwareStatus = AUDIO_HW_IDLE;
1338 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001339 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001340 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001341 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342 }
1343
Eric Laurent6acd1d42017-01-04 14:23:29 -08001344 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1345 if (thread == NULL) {
1346 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1347 if (thread == NULL) {
1348 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1349 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001350 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001351 }
1352 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001354 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355}
1356
Glenn Kastendd8104c2012-07-02 12:42:44 -07001357size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1358 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359{
Eric Laurenta1884f92011-08-23 08:25:03 -07001360 status_t ret = initCheck();
1361 if (ret != NO_ERROR) {
1362 return 0;
1363 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001364 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001365 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001366 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001367 return 0;
1368 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001369
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001370 AutoMutex lock(mHardwareLock);
1371 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001372 audio_config_t config, proposed;
1373 memset(&proposed, 0, sizeof(proposed));
1374 proposed.sample_rate = sampleRate;
1375 proposed.channel_mask = channelMask;
1376 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001377
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001378 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001379 size_t frames;
1380 for (;;) {
1381 // Note: config is currently a const parameter for get_input_buffer_size()
1382 // but we use a copy from proposed in case config changes from the call.
1383 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001384 status_t result = dev->getInputBufferSize(&config, &frames);
1385 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001386 break; // hal success, config is the result
1387 }
1388 // change one parameter of the configuration each iteration to a more "common" value
1389 // to see if the device will support it.
1390 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1391 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1392 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1393 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1394 } else {
1395 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1396 "format %#x, channelMask 0x%X",
1397 sampleRate, format, channelMask);
1398 break; // retries failed, break out of loop with frames == 0.
1399 }
1400 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001401 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001402 if (frames > 0 && config.sample_rate != sampleRate) {
1403 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1404 }
1405 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406}
1407
Glenn Kasten5f972c02014-01-13 09:59:31 -08001408uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 Mutex::Autolock _l(mLock);
1411
1412 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1413 if (recordThread != NULL) {
1414 return recordThread->getInputFramesLost();
1415 }
1416 return 0;
1417}
1418
1419status_t AudioFlinger::setVoiceVolume(float value)
1420{
Eric Laurenta1884f92011-08-23 08:25:03 -07001421 status_t ret = initCheck();
1422 if (ret != NO_ERROR) {
1423 return ret;
1424 }
1425
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426 // check calling permissions
1427 if (!settingsAllowed()) {
1428 return PERMISSION_DENIED;
1429 }
1430
1431 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001432 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001433 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001434 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001435 mHardwareStatus = AUDIO_HW_IDLE;
1436
1437 return ret;
1438}
1439
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001440status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001441 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443 Mutex::Autolock _l(mLock);
1444
1445 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1446 if (playbackThread != NULL) {
1447 return playbackThread->getRenderPosition(halFrames, dspFrames);
1448 }
1449
1450 return BAD_VALUE;
1451}
1452
1453void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1454{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001456 if (client == 0) {
1457 return;
1458 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001459 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001460 {
1461 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001462 if (mNotificationClients.indexOfKey(pid) < 0) {
1463 sp<NotificationClient> notificationClient = new NotificationClient(this,
1464 client,
1465 pid);
1466 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467
Eric Laurent021cf962014-05-13 10:18:14 -07001468 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469
Marco Nelissen06b46062014-11-14 07:58:25 -08001470 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001471 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001472 }
1473 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474
Eric Laurent021cf962014-05-13 10:18:14 -07001475 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001476 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001477 // the config change is always sent from playback or record threads to avoid deadlock
1478 // with AudioSystem::gLock
1479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001480 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001483 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001484 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 }
1486}
1487
1488void AudioFlinger::removeNotificationClient(pid_t pid)
1489{
1490 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001491 {
1492 Mutex::Autolock _cl(mClientLock);
1493 mNotificationClients.removeItem(pid);
1494 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001495
Steve Block3856b092011-10-20 11:56:00 +01001496 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001497 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001498 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001499 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001500 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001501 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001502 if (ref->mPid == pid) {
1503 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001504 mAudioSessionRefs.removeAt(i);
1505 delete ref;
1506 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001507 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001508 } else {
1509 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001510 }
1511 }
1512 if (removed) {
1513 purgeStaleEffects_l();
1514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515}
1516
Eric Laurent73e26b62015-04-27 16:55:58 -07001517void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001518 const sp<AudioIoDescriptor>& ioDesc,
1519 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520{
Eric Laurent021cf962014-05-13 10:18:14 -07001521 Mutex::Autolock _l(mClientLock);
1522 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001524 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1525 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 }
1528}
1529
Eric Laurent021cf962014-05-13 10:18:14 -07001530// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531void AudioFlinger::removeClient_l(pid_t pid)
1532{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001533 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001534 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 mClients.removeItem(pid);
1536}
1537
Eric Laurent717e1282012-06-29 16:36:52 -07001538// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001539sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1540 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001541{
1542 sp<PlaybackThread> thread;
1543
1544 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1545 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1546 ALOG_ASSERT(thread == 0);
1547 thread = mPlaybackThreads.valueAt(i);
1548 }
1549 }
1550
1551 return thread;
1552}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555
1556// ----------------------------------------------------------------------------
1557
1558AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1559 : RefBase(),
1560 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001561 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562{
Andy Hung6f248bb2018-01-23 14:04:37 -08001563 mMemoryDealer = new MemoryDealer(
1564 audioFlinger->getClientSharedHeapSize(),
1565 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566}
1567
Eric Laurent021cf962014-05-13 10:18:14 -07001568// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569AudioFlinger::Client::~Client()
1570{
1571 mAudioFlinger->removeClient_l(mPid);
1572}
1573
Glenn Kasten435dbe62012-01-30 10:15:48 -08001574sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575{
1576 return mMemoryDealer;
1577}
1578
1579// ----------------------------------------------------------------------------
1580
1581AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1582 const sp<IAudioFlingerClient>& client,
1583 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001584 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585{
1586}
1587
1588AudioFlinger::NotificationClient::~NotificationClient()
1589{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590}
1591
Glenn Kasten0f11b512014-01-31 16:18:54 -08001592void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593{
1594 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001595 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596}
1597
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001598// ----------------------------------------------------------------------------
1599AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1600 : mPendingRequests(false) {}
1601
1602
1603void AudioFlinger::MediaLogNotifier::requestMerge() {
1604 AutoMutex _l(mMutex);
1605 mPendingRequests = true;
1606 mCond.signal();
1607}
1608
1609bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001610 // Should already have been checked, but just in case
1611 if (sMediaLogService == 0) {
1612 return false;
1613 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001614 // Wait until there are pending requests
1615 {
1616 AutoMutex _l(mMutex);
1617 mPendingRequests = false; // to ignore past requests
1618 while (!mPendingRequests) {
1619 mCond.wait(mMutex);
1620 // TODO may also need an exitPending check
1621 }
1622 mPendingRequests = false;
1623 }
1624 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001625 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001626 usleep(kPostTriggerSleepPeriod);
1627 return true;
1628}
1629
1630void AudioFlinger::requestLogMerge() {
1631 mMediaLogNotifier->requestMerge();
1632}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633
1634// ----------------------------------------------------------------------------
1635
Eric Laurentf14db3c2017-12-08 14:20:36 -08001636sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1637 CreateRecordOutput& output,
1638 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639{
1640 sp<RecordThread::RecordTrack> recordTrack;
1641 sp<RecordHandle> recordHandle;
1642 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001644 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001645 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646
Eric Laurentf14db3c2017-12-08 14:20:36 -08001647 output.cblk.clear();
1648 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001649 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001650
Eric Laurentf14db3c2017-12-08 14:20:36 -08001651 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001652 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001653 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001654 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001655 ALOGW_IF(clientUid != callingUid,
1656 "%s uid %d tried to pass itself off as %d",
1657 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001658 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001659 updatePid = true;
1660 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001661 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001662 if (updatePid) {
1663 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001664 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001665 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001666 __func__, callingUid, callingPid, clientPid);
1667 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001668 }
1669
Andy Hung6770c6f2015-04-07 13:43:36 -07001670 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001671 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1672 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001673 lStatus = BAD_VALUE;
1674 goto Exit;
1675 }
1676
Glenn Kasten53b5d092014-02-05 10:00:23 -08001677 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001678 if (!audio_is_input_channel(input.config.channel_mask)) {
1679 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001680 lStatus = BAD_VALUE;
1681 goto Exit;
1682 }
1683
Eric Laurentf14db3c2017-12-08 14:20:36 -08001684 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1685 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1686 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1687 lStatus = BAD_VALUE;
1688 goto Exit;
1689 }
1690
1691 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001692 output.selectedDeviceId = input.selectedDeviceId;
1693 output.flags = input.flags;
1694
1695 client = registerPid(clientPid);
1696
1697 // Not a conventional loop, but a retry loop for at most two iterations total.
1698 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1699 // Exits loop via break on no error of got exit on error
1700 // The sp<> references will be dropped when re-entering scope.
1701 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1702 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001703 // release previously opened input if retrying.
1704 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1705 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001706 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001707 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001708 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001709 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001710 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001711 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1712 sessionId,
1713 // FIXME compare to AudioTrack
1714 clientPid,
1715 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001716 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001717 &input.config,
1718 output.flags, &output.selectedDeviceId, &portId);
1719
Glenn Kasten05997e22014-03-13 15:08:33 -07001720 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001722 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001724 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725 lStatus = BAD_VALUE;
1726 goto Exit;
1727 }
1728
Eric Laurentf14db3c2017-12-08 14:20:36 -08001729 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730
Eric Laurentf14db3c2017-12-08 14:20:36 -08001731 output.sampleRate = input.config.sample_rate;
1732 output.frameCount = input.frameCount;
1733 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001734
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001735 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001736 input.config.format, input.config.channel_mask,
1737 &output.frameCount, sessionId,
1738 &output.notificationFrameCount,
1739 clientUid, &output.flags,
1740 input.clientInfo.clientTid,
1741 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001742 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001743
Eric Laurentf14db3c2017-12-08 14:20:36 -08001744 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1745 // audio policy manager without FAST constraint
1746 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001747 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001748 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001749
1750 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001751 goto Exit;
1752 }
1753
1754 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1755 // session and move it to this thread.
1756 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1757 if (chain != 0) {
1758 Mutex::Autolock _l(thread->mLock);
1759 thread->addEffectChain_l(chain);
1760 }
1761 break;
1762 }
1763 // End of retry loop.
1764 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765 }
Glenn Kastene198c362013-08-13 09:13:36 -07001766
Eric Laurentf14db3c2017-12-08 14:20:36 -08001767 output.cblk = recordTrack->getCblk();
1768 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001769 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001770
1771 // return handle to client
1772 recordHandle = new RecordHandle(recordTrack);
1773
1774Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001775 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001776 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001777 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001778 // Don't hold mClientLock when releasing the reference on the track as the
1779 // destructor will acquire it.
1780 {
1781 Mutex::Autolock _cl(mClientLock);
1782 client.clear();
1783 }
Eric Laurent896c9672017-12-08 14:08:45 -08001784 recordTrack.clear();
1785 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001786 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001787 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 }
1789
Glenn Kasten9156ef32013-08-06 15:39:08 -07001790 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 return recordHandle;
1792}
1793
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001794
1795
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796// ----------------------------------------------------------------------------
1797
Eric Laurenta4c5a552012-03-29 10:12:40 -07001798audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1799{
Eric Laurent44622db2014-08-01 19:00:33 -07001800 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001801 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001802 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001803 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001804 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001805 }
1806 Mutex::Autolock _l(mLock);
1807 return loadHwModule_l(name);
1808}
1809
1810// loadHwModule_l() must be called with AudioFlinger::mLock held
1811audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1812{
1813 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1814 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1815 ALOGW("loadHwModule() module %s already loaded", name);
1816 return mAudioHwDevs.keyAt(i);
1817 }
1818 }
1819
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001820 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001821
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001822 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001823 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001824 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001825 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001826 }
1827
1828 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001829 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001830 mHardwareStatus = AUDIO_HW_IDLE;
1831 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001832 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001833 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001834 }
1835
John Grossmanee578c02012-07-23 17:05:46 -07001836 // Check and cache this HAL's level of support for master mute and master
1837 // volume. If this is the first HAL opened, and it supports the get
1838 // methods, use the initial values provided by the HAL as the current
1839 // master mute and volume settings.
1840
1841 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1842 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001843 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001844
1845 if (0 == mAudioHwDevs.size()) {
1846 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001847 float mv;
1848 if (OK == dev->getMasterVolume(&mv)) {
1849 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001850 }
1851
1852 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001853 bool mm;
1854 if (OK == dev->getMasterMute(&mm)) {
1855 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001856 }
1857 }
1858
Eric Laurenta4c5a552012-03-29 10:12:40 -07001859 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001860 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001861 flags = static_cast<AudioHwDevice::Flags>(flags |
1862 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1863 }
1864
1865 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001866 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001867 flags = static_cast<AudioHwDevice::Flags>(flags |
1868 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1869 }
1870
Eric Laurenta4c5a552012-03-29 10:12:40 -07001871 mHardwareStatus = AUDIO_HW_IDLE;
1872 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07001873 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07001874 // An MSD module is inserted before hardware modules in order to mix encoded streams.
1875 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
1876 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001877
Glenn Kastena13cde92016-03-28 15:26:02 -07001878 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001879 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001880
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001881 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001882
1883 return handle;
1884
1885}
1886
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001887// ----------------------------------------------------------------------------
1888
Glenn Kasten3b16c762012-11-14 08:44:39 -08001889uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001890{
1891 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001892 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001893 return thread != NULL ? thread->sampleRate() : 0;
1894}
1895
Glenn Kastene33054e2012-11-14 12:54:39 -08001896size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001897{
1898 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001899 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001900 return thread != NULL ? thread->frameCountHAL() : 0;
1901}
1902
1903// ----------------------------------------------------------------------------
1904
Andy Hung6f248bb2018-01-23 14:04:37 -08001905status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001906{
1907 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001908 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001909 return PERMISSION_DENIED;
1910 }
1911 Mutex::Autolock _l(mLock);
1912 if (mIsDeviceTypeKnown) {
1913 return INVALID_OPERATION;
1914 }
1915 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001916 mTotalMemory = totalMemory;
1917 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1918 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1919 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1920 // though actual setting is determined through device configuration.
1921 constexpr int64_t GB = 1024 * 1024 * 1024;
1922 mClientSharedHeapSize =
1923 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1924 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1925 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1926 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1927 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001928 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001929
1930 // TODO: Cache the client shared heap size in a persistent property.
1931 // It's possible that a native process or Java service or app accesses audioserver
1932 // after it is registered by system server, but before AudioService updates
1933 // the memory info. This would occur immediately after boot or an audioserver
1934 // crash and restore. Before update from AudioService, the client would get the
1935 // minimum heap size.
1936
1937 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1938 (isLowRamDevice ? "true" : "false"),
1939 (long long)mTotalMemory,
1940 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001941 return NO_ERROR;
1942}
1943
Andy Hung6f248bb2018-01-23 14:04:37 -08001944size_t AudioFlinger::getClientSharedHeapSize() const
1945{
1946 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1947 if (heapSizeInBytes != 0) { // read-only property overrides all.
1948 return heapSizeInBytes;
1949 }
1950 return mClientSharedHeapSize;
1951}
1952
Mikhail Naganovdea53042018-04-26 13:10:21 -07001953status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1954{
1955 ALOGV(__func__);
1956
1957 audio_module_handle_t module;
1958 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1959 module = config->ext.device.hw_module;
1960 } else {
1961 module = config->ext.mix.hw_module;
1962 }
1963
1964 Mutex::Autolock _l(mLock);
1965 ssize_t index = mAudioHwDevs.indexOfKey(module);
1966 if (index < 0) {
1967 ALOGW("%s() bad hw module %d", __func__, module);
1968 return BAD_VALUE;
1969 }
1970
1971 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
1972 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
1973}
1974
Eric Laurent93c3d412014-08-01 14:48:35 -07001975audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1976{
1977 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001978
1979 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1980 if (index >= 0) {
1981 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1982 mHwAvSyncIds.valueAt(index), sessionId);
1983 return mHwAvSyncIds.valueAt(index);
1984 }
1985
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001986 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001987 if (dev == NULL) {
1988 return AUDIO_HW_SYNC_INVALID;
1989 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001990 String8 reply;
1991 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001992 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001993 param = AudioParameter(reply);
1994 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001995
1996 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001997 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001998 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1999 return AUDIO_HW_SYNC_INVALID;
2000 }
2001
2002 // allow only one session for a given HW A/V sync ID.
2003 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2004 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2005 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2006 value, mHwAvSyncIds.keyAt(i));
2007 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002008 break;
2009 }
2010 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002011
2012 mHwAvSyncIds.add(sessionId, value);
2013
2014 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2015 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2016 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002017 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002018 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002019 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002020 String8 keyValuePairs = param.toString();
2021 thread->setParameters(keyValuePairs);
2022 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2023 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002024 break;
2025 }
2026 }
2027
2028 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2029 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002030}
2031
Eric Laurent72e3f392015-05-20 14:43:50 -07002032status_t AudioFlinger::systemReady()
2033{
2034 Mutex::Autolock _l(mLock);
2035 ALOGI("%s", __FUNCTION__);
2036 if (mSystemReady) {
2037 ALOGW("%s called twice", __FUNCTION__);
2038 return NO_ERROR;
2039 }
2040 mSystemReady = true;
2041 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2042 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2043 thread->systemReady();
2044 }
2045 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2046 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2047 thread->systemReady();
2048 }
2049 return NO_ERROR;
2050}
2051
jiabin46a76fa2018-01-05 10:18:21 -08002052status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2053{
jiabin9ff780e2018-03-19 18:19:52 -07002054 AutoMutex lock(mHardwareLock);
2055 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2056 status_t status = dev->getMicrophones(microphones);
2057 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002058}
2059
Eric Laurentfa90e842014-10-17 18:12:31 -07002060// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2061void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2062{
2063 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2064 if (index >= 0) {
2065 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2066 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2067 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002068 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002069 String8 keyValuePairs = param.toString();
2070 thread->setParameters(keyValuePairs);
2071 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2072 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002073 }
2074}
2075
2076
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002077// ----------------------------------------------------------------------------
2078
Eric Laurent83b88082014-06-20 18:31:16 -07002079
Eric Laurent6acd1d42017-01-04 14:23:29 -08002080sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002081 audio_io_handle_t *output,
2082 audio_config_t *config,
2083 audio_devices_t devices,
2084 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002085 audio_output_flags_t flags)
2086{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002087 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002088 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002089 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002090 }
2091
Eric Laurentcf2c0212014-07-25 16:20:43 -07002092 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002093 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2094 } else {
2095 // Audio Policy does not currently request a specific output handle.
2096 // If this is ever needed, see openInput_l() for example code.
2097 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2098 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002099 }
Eric Laurent83b88082014-06-20 18:31:16 -07002100
2101 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2102
Eric Laurent83b88082014-06-20 18:31:16 -07002103 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002104 // This if statement allows overriding the audio policy settings
2105 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2106 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2107 // Check only for Normal Mixing mode
2108 if (kEnableExtendedPrecision) {
2109 // Specify format (uncomment one below to choose)
2110 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2111 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2112 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2113 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002114 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002115 }
2116 if (kEnableExtendedChannels) {
2117 // Specify channel mask (uncomment one below to choose)
2118 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2119 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2120 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2121 }
Eric Laurent83b88082014-06-20 18:31:16 -07002122 }
2123
Phil Burk062e67a2015-02-11 13:40:50 -08002124 AudioStreamOut *outputStream = NULL;
2125 status_t status = outHwDev->openOutputStream(
2126 &outputStream,
2127 *output,
2128 devices,
2129 flags,
2130 config,
2131 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002132
2133 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002134
Phil Burk062e67a2015-02-11 13:40:50 -08002135 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002136 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2137 sp<MmapPlaybackThread> thread =
2138 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2139 devices, AUDIO_DEVICE_NONE, mSystemReady);
2140 mMmapThreads.add(*output, thread);
2141 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2142 *output, thread.get());
2143 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002144 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002145 sp<PlaybackThread> thread;
2146 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2147 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2148 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2149 *output, thread.get());
2150 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2151 || !isValidPcmSinkFormat(config->format)
2152 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2153 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2154 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2155 *output, thread.get());
2156 } else {
2157 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2158 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2159 *output, thread.get());
2160 }
2161 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002162 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002163 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002164 }
Eric Laurent83b88082014-06-20 18:31:16 -07002165 }
2166
2167 return 0;
2168}
2169
Eric Laurentcf2c0212014-07-25 16:20:43 -07002170status_t AudioFlinger::openOutput(audio_module_handle_t module,
2171 audio_io_handle_t *output,
2172 audio_config_t *config,
2173 audio_devices_t *devices,
2174 const String8& address,
2175 uint32_t *latencyMs,
2176 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002178 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2179 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002180 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002181 (devices != NULL) ? *devices : 0,
2182 config->sample_rate,
2183 config->format,
2184 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002185 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002187 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002188 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002190
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 Mutex::Autolock _l(mLock);
2192
Eric Laurent6acd1d42017-01-04 14:23:29 -08002193 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002194 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002195 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2196 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2197 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198
Eric Laurent6acd1d42017-01-04 14:23:29 -08002199 // notify client processes of the new output creation
2200 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002201
Eric Laurent6acd1d42017-01-04 14:23:29 -08002202 // the first primary output opened designates the primary hw device
2203 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002204 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002205 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002206
Eric Laurent6acd1d42017-01-04 14:23:29 -08002207 AutoMutex lock(mHardwareLock);
2208 mHardwareStatus = AUDIO_HW_SET_MODE;
2209 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2210 mHardwareStatus = AUDIO_HW_IDLE;
2211 }
2212 } else {
2213 MmapThread *mmapThread = (MmapThread *)thread.get();
2214 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002215 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002216 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 }
2218
Eric Laurentcf2c0212014-07-25 16:20:43 -07002219 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220}
2221
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002222audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2223 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224{
2225 Mutex::Autolock _l(mLock);
2226 MixerThread *thread1 = checkMixerThread_l(output1);
2227 MixerThread *thread2 = checkMixerThread_l(output2);
2228
2229 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002230 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2231 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002232 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 }
2234
Glenn Kasteneeecb982016-02-26 10:44:04 -08002235 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002236 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 thread->addOutputTrack(thread2);
2238 mPlaybackThreads.add(id, thread);
2239 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002240 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 return id;
2242}
2243
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002244status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245{
Glenn Kastend96c5722012-04-25 13:44:49 -07002246 return closeOutput_nonvirtual(output);
2247}
2248
2249status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2250{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 // keep strong reference on the playback thread so that
2252 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002253 sp<PlaybackThread> playbackThread;
2254 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 {
2256 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002257 playbackThread = checkPlaybackThread_l(output);
2258 if (playbackThread != NULL) {
2259 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260
Andy Hungdc099c22018-09-18 13:46:39 -07002261 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002262
Eric Laurent6acd1d42017-01-04 14:23:29 -08002263 if (playbackThread->type() == ThreadBase::MIXER) {
2264 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2265 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2266 DuplicatingThread *dupThread =
2267 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2268 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002270 }
2271 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272
2273
Eric Laurent6acd1d42017-01-04 14:23:29 -08002274 mPlaybackThreads.removeItem(output);
2275 // save all effects to the default thread
2276 if (mPlaybackThreads.size()) {
2277 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2278 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002279 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002280 Mutex::Autolock _dl(dstThread->mLock);
2281 Mutex::Autolock _sl(playbackThread->mLock);
2282 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2283 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002284 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2285 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 }
2288 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002289 } else {
2290 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2291 if (mmapThread == 0) {
2292 return BAD_VALUE;
2293 }
Andy Hungdc099c22018-09-18 13:46:39 -07002294 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002295 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002296 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002298 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2299 ioDesc->mIoHandle = output;
2300 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002301 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002303 // The thread entity (active unit of execution) is no longer running here,
2304 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305
Eric Laurent6acd1d42017-01-04 14:23:29 -08002306 if (playbackThread != 0) {
2307 playbackThread->exit();
2308 if (!playbackThread->isDuplicating()) {
2309 closeOutputFinish(playbackThread);
2310 }
2311 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002312 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002313 mmapThread->exit();
2314 AudioStreamOut *out = mmapThread->clearOutput();
2315 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2316 // from now on thread->mOutput is NULL
2317 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 }
2319 return NO_ERROR;
2320}
2321
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002322void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002323{
2324 AudioStreamOut *out = thread->clearOutput();
2325 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2326 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002327 delete out;
2328}
2329
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002330void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002331{
2332 mPlaybackThreads.removeItem(thread->mId);
2333 thread->exit();
2334 closeOutputFinish(thread);
2335}
2336
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002337status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338{
2339 Mutex::Autolock _l(mLock);
2340 PlaybackThread *thread = checkPlaybackThread_l(output);
2341
2342 if (thread == NULL) {
2343 return BAD_VALUE;
2344 }
2345
Steve Block3856b092011-10-20 11:56:00 +01002346 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 thread->suspend();
2348
2349 return NO_ERROR;
2350}
2351
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002352status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353{
2354 Mutex::Autolock _l(mLock);
2355 PlaybackThread *thread = checkPlaybackThread_l(output);
2356
2357 if (thread == NULL) {
2358 return BAD_VALUE;
2359 }
2360
Steve Block3856b092011-10-20 11:56:00 +01002361 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002362
2363 thread->restore();
2364
2365 return NO_ERROR;
2366}
2367
Eric Laurentcf2c0212014-07-25 16:20:43 -07002368status_t AudioFlinger::openInput(audio_module_handle_t module,
2369 audio_io_handle_t *input,
2370 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002371 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002372 const String8& address,
2373 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002374 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375{
Eric Laurent83b88082014-06-20 18:31:16 -07002376 Mutex::Autolock _l(mLock);
2377
Glenn Kastene7d66712015-03-05 13:46:52 -08002378 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002379 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002380 }
2381
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002382 sp<ThreadBase> thread = openInput_l(
2383 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002384
2385 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002386 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002387 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002388 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002389 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002390 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002391}
Dima Zavin799a70e2011-04-18 16:57:27 -07002392
Eric Laurent6acd1d42017-01-04 14:23:29 -08002393sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002394 audio_io_handle_t *input,
2395 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002396 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002397 const String8& address,
2398 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002399 audio_input_flags_t flags,
2400 audio_devices_t outputDevice,
2401 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002402{
Glenn Kastene7d66712015-03-05 13:46:52 -08002403 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002404 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002405 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002406 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002407 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002408
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002409 // Some flags are specific to framework and must not leak to the HAL.
2410 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2411
Glenn Kasteneeecb982016-02-26 10:44:04 -08002412 // Audio Policy can request a specific handle for hardware hotword.
2413 // The goal here is not to re-open an already opened input.
2414 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002415 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002416 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2417 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2418 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2419 return 0;
2420 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2421 // This should not happen in a transient state with current design.
2422 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2423 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002424 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002425
Eric Laurentcf2c0212014-07-25 16:20:43 -07002426 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002427 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002428 sp<StreamInHalInterface> inStream;
2429 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002430 *input, devices, &halconfig, flags, address.string(), source,
2431 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002432 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2433 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002434 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002435 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002436 halconfig.sample_rate,
2437 halconfig.format,
2438 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002439 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002440 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002442 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002443 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002444 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002445 audio_is_linear_pcm(config->format) &&
2446 audio_is_linear_pcm(halconfig.format) &&
2447 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002448 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2449 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002450 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002451 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002452 inStream.clear();
2453 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002454 *input, devices, &halconfig, flags, address.string(), source,
2455 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002456 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457 }
2458
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002459 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002460 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002461 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2462 sp<MmapCaptureThread> thread =
2463 new MmapCaptureThread(this, *input,
2464 inHwDev, inputStream,
2465 primaryOutputDevice_l(), devices, mSystemReady);
2466 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002467 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2468 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002469 return thread;
2470 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002471 // Start record thread
2472 // RecordThread requires both input and output device indication to forward to audio
2473 // pre processing modules
2474 sp<RecordThread> thread = new RecordThread(this,
2475 inputStream,
2476 *input,
2477 primaryOutputDevice_l(),
2478 devices,
2479 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002480 );
2481 mRecordThreads.add(*input, thread);
2482 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2483 return thread;
2484 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 }
2486
Eric Laurentcf2c0212014-07-25 16:20:43 -07002487 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488 return 0;
2489}
2490
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002491status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492{
Glenn Kastend96c5722012-04-25 13:44:49 -07002493 return closeInput_nonvirtual(input);
2494}
2495
2496status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2497{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 // keep strong reference on the record thread so that
2499 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002500 sp<RecordThread> recordThread;
2501 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 {
2503 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002504 recordThread = checkRecordThread_l(input);
2505 if (recordThread != 0) {
2506 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507
Andy Hungdc099c22018-09-18 13:46:39 -07002508 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002509
Eric Laurent6acd1d42017-01-04 14:23:29 -08002510 // If we still have effect chains, it means that a client still holds a handle
2511 // on at least one effect. We must either move the chain to an existing thread with the
2512 // same session ID or put it aside in case a new record thread is opened for a
2513 // new capture on the same session
2514 sp<EffectChain> chain;
2515 {
2516 Mutex::Autolock _sl(recordThread->mLock);
2517 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2518 // Note: maximum one chain per record thread
2519 if (effectChains.size() != 0) {
2520 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002521 }
2522 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002523 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002524 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002525 // This should only happen in case of overlap between one thread tear down and the
2526 // creation of its replacement
2527 size_t i;
2528 for (i = 0; i < mRecordThreads.size(); i++) {
2529 sp<RecordThread> t = mRecordThreads.valueAt(i);
2530 if (t == recordThread) {
2531 continue;
2532 }
2533 if (t->hasAudioSession(chain->sessionId()) != 0) {
2534 Mutex::Autolock _l(t->mLock);
2535 ALOGV("closeInput() found thread %d for effect session %d",
2536 t->id(), chain->sessionId());
2537 t->addEffectChain_l(chain);
2538 break;
2539 }
2540 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002541 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002542 if (i == mRecordThreads.size()) {
2543 putOrphanEffectChain_l(chain);
2544 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002545 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002546 mRecordThreads.removeItem(input);
2547 } else {
2548 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2549 if (mmapThread == 0) {
2550 return BAD_VALUE;
2551 }
Andy Hungdc099c22018-09-18 13:46:39 -07002552 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002553 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002554 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002555 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2556 ioDesc->mIoHandle = input;
2557 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 }
Eric Laurent83b88082014-06-20 18:31:16 -07002559 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2560 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002561 if (recordThread != 0) {
2562 closeInputFinish(recordThread);
2563 } else if (mmapThread != 0) {
2564 mmapThread->exit();
2565 AudioStreamIn *in = mmapThread->clearInput();
2566 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2567 // from now on thread->mInput is NULL
2568 delete in;
2569 }
Eric Laurent83b88082014-06-20 18:31:16 -07002570 return NO_ERROR;
2571}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002573void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002574{
2575 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002576 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002577 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002578 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002579 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002580}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002582void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002583{
2584 mRecordThreads.removeItem(thread->mId);
2585 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586}
2587
Glenn Kastend2304db2014-02-03 07:40:31 -08002588status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589{
2590 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002591 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592
2593 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2594 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002595 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002596 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002597 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2598 mMmapThreads[i]->invalidateTracks(stream);
2599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 return NO_ERROR;
2601}
2602
2603
Glenn Kasteneeecb982016-02-26 10:44:04 -08002604audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605{
Glenn Kasten9d003132016-04-06 14:38:09 -07002606 // This is a binder API, so a malicious client could pass in a bad parameter.
2607 // Check for that before calling the internal API nextUniqueId().
2608 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2609 ALOGE("newAudioUniqueId invalid use %d", use);
2610 return AUDIO_UNIQUE_ID_ALLOCATE;
2611 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002612 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613}
2614
Glenn Kastend848eb42016-03-08 13:42:11 -08002615void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002616{
2617 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002618 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002619 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002620 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2621 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002622 caller = pid;
2623 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002624
Eric Laurent021cf962014-05-13 10:18:14 -07002625 {
2626 Mutex::Autolock _cl(mClientLock);
2627 // Ignore requests received from processes not known as notification client. The request
2628 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2629 // called from a different pid leaving a stale session reference. Also we don't know how
2630 // to clear this reference if the client process dies.
2631 if (mNotificationClients.indexOfKey(caller) < 0) {
2632 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2633 return;
2634 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002635 }
2636
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002637 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002638 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002639 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002640 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2641 ref->mCnt++;
2642 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002643 return;
2644 }
2645 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002646 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2647 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002648}
2649
Glenn Kastend848eb42016-03-08 13:42:11 -08002650void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002651{
2652 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002653 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002654 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002655 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2656 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002657 caller = pid;
2658 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002659 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002660 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002661 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002662 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2663 ref->mCnt--;
2664 ALOGV(" decremented refcount to %d", ref->mCnt);
2665 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002666 mAudioSessionRefs.removeAt(i);
2667 delete ref;
2668 purgeStaleEffects_l();
2669 }
2670 return;
2671 }
2672 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002673 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002674 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002675 ALOGW_IF(!isAudioServerUid(callerUid),
2676 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002677}
2678
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002679bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2680{
2681 size_t num = mAudioSessionRefs.size();
2682 for (size_t i = 0; i < num; i++) {
2683 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2684 if (ref->mSessionid == audioSession) {
2685 return true;
2686 }
2687 }
2688 return false;
2689}
2690
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002691void AudioFlinger::purgeStaleEffects_l() {
2692
Steve Block3856b092011-10-20 11:56:00 +01002693 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002694
2695 Vector< sp<EffectChain> > chains;
2696
2697 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2698 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002699 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002700 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2701 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002702 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2703 chains.push(ec);
2704 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002705 }
2706 }
2707 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2708 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002709 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002710 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2711 sp<EffectChain> ec = t->mEffectChains[j];
2712 chains.push(ec);
2713 }
2714 }
2715
2716 for (size_t i = 0; i < chains.size(); i++) {
2717 sp<EffectChain> ec = chains[i];
2718 int sessionid = ec->sessionId();
2719 sp<ThreadBase> t = ec->mThread.promote();
2720 if (t == 0) {
2721 continue;
2722 }
2723 size_t numsessionrefs = mAudioSessionRefs.size();
2724 bool found = false;
2725 for (size_t k = 0; k < numsessionrefs; k++) {
2726 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002727 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002728 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002729 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002730 found = true;
2731 break;
2732 }
2733 }
2734 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002735 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002736 // remove all effects from the chain
2737 while (ec->mEffects.size()) {
2738 sp<EffectModule> effect = ec->mEffects[0];
2739 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002740 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002741 if (effect->purgeHandles()) {
2742 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002743 }
2744 AudioSystem::unregisterEffect(effect->id());
2745 }
2746 }
2747 }
2748 return;
2749}
2750
Andy Hungdc099c22018-09-18 13:46:39 -07002751// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2752void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2753{
2754 audio_utils::FdToString fdToString;
2755 const int fd = fdToString.fd();
2756 if (fd >= 0) {
2757 thread->dump(fd, {} /* args */);
2758 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2759 }
2760}
2761
Glenn Kasteneeecb982016-02-26 10:44:04 -08002762// checkThread_l() must be called with AudioFlinger::mLock held
2763AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2764{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002765 ThreadBase *thread = checkMmapThread_l(ioHandle);
2766 if (thread == 0) {
2767 switch (audio_unique_id_get_use(ioHandle)) {
2768 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2769 thread = checkPlaybackThread_l(ioHandle);
2770 break;
2771 case AUDIO_UNIQUE_ID_USE_INPUT:
2772 thread = checkRecordThread_l(ioHandle);
2773 break;
2774 default:
2775 break;
2776 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002777 }
2778 return thread;
2779}
2780
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002782AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783{
Glenn Kastena1117922012-01-26 10:53:32 -08002784 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785}
2786
2787// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002788AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789{
2790 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002791 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792}
2793
2794// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002795AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796{
Glenn Kastena1117922012-01-26 10:53:32 -08002797 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798}
2799
Eric Laurent6acd1d42017-01-04 14:23:29 -08002800// checkMmapThread_l() must be called with AudioFlinger::mLock held
2801AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2802{
2803 return mMmapThreads.valueFor(io).get();
2804}
2805
2806
2807// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2808AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2809{
Eric Laurent7459b902017-04-19 18:10:41 -07002810 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002811 if (volumeInterface == nullptr) {
2812 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2813 if (mmapThread != nullptr) {
2814 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002815 MmapPlaybackThread *mmapPlaybackThread =
2816 static_cast<MmapPlaybackThread *>(mmapThread);
2817 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002818 }
2819 }
2820 }
2821 return volumeInterface;
2822}
2823
2824Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2825{
2826 Vector <VolumeInterface *> volumeInterfaces;
2827 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002828 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002829 }
2830 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2831 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002832 MmapPlaybackThread *mmapPlaybackThread =
2833 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2834 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002835 }
2836 }
2837 return volumeInterfaces;
2838}
2839
Glenn Kasteneeecb982016-02-26 10:44:04 -08002840audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841{
Glenn Kasten9d003132016-04-06 14:38:09 -07002842 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002843 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002844 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2845 for (int retry = 0; retry < maxRetries; retry++) {
2846 // The cast allows wraparound from max positive to min negative instead of abort
2847 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2848 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2849 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2850 // allow wrap by skipping 0 and -1 for session ids
2851 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2852 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2853 return (audio_unique_id_t) (base | use);
2854 }
2855 }
2856 // We have no way of recovering from wraparound
2857 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2858 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859}
2860
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002861AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002862{
2863 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2864 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002865 if(thread->isDuplicating()) {
2866 continue;
2867 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002868 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002869 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002870 return thread;
2871 }
2872 }
2873 return NULL;
2874}
2875
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002876audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002877{
2878 PlaybackThread *thread = primaryPlaybackThread_l();
2879
2880 if (thread == NULL) {
2881 return 0;
2882 }
2883
Eric Laurentf1c04f92012-08-28 14:26:53 -07002884 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002885}
2886
Glenn Kastena7335632016-06-09 17:09:53 -07002887AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2888{
2889 size_t minFrameCount = 0;
2890 PlaybackThread *minThread = NULL;
2891 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2892 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2893 if (!thread->isDuplicating()) {
2894 size_t frameCount = thread->frameCountHAL();
2895 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2896 (frameCount == minFrameCount && thread->hasFastMixer() &&
2897 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2898 minFrameCount = frameCount;
2899 minThread = thread;
2900 }
2901 }
2902 }
2903 return minThread;
2904}
2905
Eric Laurenta011e352012-03-29 15:51:43 -07002906sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002907 audio_session_t triggerSession,
2908 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002909 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002910 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002911{
2912 Mutex::Autolock _l(mLock);
2913
2914 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2915 status_t playStatus = NAME_NOT_FOUND;
2916 status_t recStatus = NAME_NOT_FOUND;
2917 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2918 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2919 if (playStatus == NO_ERROR) {
2920 return event;
2921 }
2922 }
2923 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2924 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2925 if (recStatus == NO_ERROR) {
2926 return event;
2927 }
2928 }
2929 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2930 mPendingSyncEvents.add(event);
2931 } else {
2932 ALOGV("createSyncEvent() invalid event %d", event->type());
2933 event.clear();
2934 }
2935 return event;
2936}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002937
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938// ----------------------------------------------------------------------------
2939// Effect management
2940// ----------------------------------------------------------------------------
2941
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002942sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2943 return mEffectsFactoryHal;
2944}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945
Glenn Kastenf587ba52012-01-26 16:25:10 -08002946status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947{
2948 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002949 if (mEffectsFactoryHal.get()) {
2950 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2951 } else {
2952 return -ENODEV;
2953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954}
2955
Glenn Kastenf587ba52012-01-26 16:25:10 -08002956status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002957{
2958 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002959 if (mEffectsFactoryHal.get()) {
2960 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2961 } else {
2962 return -ENODEV;
2963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964}
2965
Glenn Kasten5e92a782012-01-30 07:40:52 -08002966status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002967 const effect_uuid_t *pTypeUuid,
2968 uint32_t preferredTypeFlag,
2969 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002971 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
2972 return BAD_VALUE;
2973 }
2974
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002976
2977 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002978 return -ENODEV;
2979 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002981 status_t status = NO_ERROR;
2982 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
2983 // If uuid is specified, request effect descriptor from that.
2984 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2985 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
2986 // If uuid is not specified, look for an available implementation
2987 // of the required type instead.
2988
2989 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
2990 effect_descriptor_t desc;
2991 desc.flags = 0; // prevent compiler warning
2992
2993 uint32_t numEffects = 0;
2994 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
2995 if (status < 0) {
2996 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
2997 return status;
2998 }
2999
3000 bool found = false;
3001 for (uint32_t i = 0; i < numEffects; i++) {
3002 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3003 if (status < 0) {
3004 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3005 continue;
3006 }
3007 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3008 // If matching type found save effect descriptor.
3009 found = true;
3010 *descriptor = desc;
3011
3012 // If there's no preferred flag or this descriptor matches the preferred
3013 // flag, success! If this descriptor doesn't match the preferred
3014 // flag, continue enumeration in case a better matching version of this
3015 // effect type is available. Note that this means if no effect with a
3016 // correct flag is found, the descriptor returned will correspond to the
3017 // last effect that at least had a matching type uuid (if any).
3018 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3019 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3020 break;
3021 }
3022 }
3023 }
3024
3025 if (!found) {
3026 status = NAME_NOT_FOUND;
3027 ALOGW("getEffectDescriptor(): Effect not found by type.");
3028 }
3029 } else {
3030 status = BAD_VALUE;
3031 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3032 }
3033 return status;
3034}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003036sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 effect_descriptor_t *pDesc,
3038 const sp<IEffectClient>& effectClient,
3039 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003040 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003041 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003042 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003043 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 status_t *status,
3045 int *id,
3046 int *enabled)
3047{
3048 status_t lStatus = NO_ERROR;
3049 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051
Eric Laurentb6436272016-12-07 19:24:50 -08003052 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003053 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003054 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3055 ALOGW_IF(pid != -1 && pid != callingPid,
3056 "%s uid %d pid %d tried to pass itself off as pid %d",
3057 __func__, callingUid, callingPid, pid);
3058 pid = callingPid;
3059 }
3060
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003061 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3062 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063
3064 if (pDesc == NULL) {
3065 lStatus = BAD_VALUE;
3066 goto Exit;
3067 }
3068
Eric Laurent84e9a102010-09-23 16:10:16 -07003069 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003070 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003071 lStatus = PERMISSION_DENIED;
3072 goto Exit;
3073 }
3074
Dima Zavinfce7a472011-04-19 22:30:36 -07003075 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003076 // that can only be created by audio policy manager
3077 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003078 lStatus = PERMISSION_DENIED;
3079 goto Exit;
3080 }
3081
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003082 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003083 lStatus = NO_INIT;
3084 goto Exit;
3085 }
3086
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003088 // Get the full effect descriptor from the uuid/type.
3089 // If the session is the output mix, prefer an auxiliary effect,
3090 // otherwise no preference.
3091 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3092 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3093 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3094 if (lStatus < 0) {
3095 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3096 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 }
3098
3099 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003100 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3102 lStatus = INVALID_OPERATION;
3103 goto Exit;
3104 }
3105
Eric Laurent59255e42011-07-27 19:49:51 -07003106 // check recording permission for visualizer
3107 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003108 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003109 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003110 lStatus = PERMISSION_DENIED;
3111 goto Exit;
3112 }
3113
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003115 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003116 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003117 // if the output returned by getOutputForEffect() is removed before we lock the
3118 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3119 // and we will exit safely
3120 io = AudioSystem::getOutputForEffect(&desc);
3121 ALOGV("createEffect got output %d", io);
3122 }
3123
3124 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125
3126 // If output is not specified try to find a matching audio session ID in one of the
3127 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003128 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3129 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003130 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003131 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003132 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3133 // output must be specified by AudioPolicyManager when using session
3134 // AUDIO_SESSION_OUTPUT_STAGE
3135 lStatus = BAD_VALUE;
3136 goto Exit;
3137 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003138 // look for the thread where the specified audio session is present
3139 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3140 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3141 io = mPlaybackThreads.keyAt(i);
3142 break;
3143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003145 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003146 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3147 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3148 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003149 break;
3150 }
3151 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003152 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003153 if (io == AUDIO_IO_HANDLE_NONE) {
3154 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3155 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3156 io = mMmapThreads.keyAt(i);
3157 break;
3158 }
3159 }
3160 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003161 // If no output thread contains the requested session ID, default to
3162 // first output. The effect chain will be moved to the correct output
3163 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003164 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003165 io = mPlaybackThreads.keyAt(0);
3166 }
Steve Block3856b092011-10-20 11:56:00 +01003167 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003168 }
3169 ThreadBase *thread = checkRecordThread_l(io);
3170 if (thread == NULL) {
3171 thread = checkPlaybackThread_l(io);
3172 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003173 thread = checkMmapThread_l(io);
3174 if (thread == NULL) {
3175 ALOGE("createEffect() unknown output thread");
3176 lStatus = BAD_VALUE;
3177 goto Exit;
3178 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003179 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003180 } else {
3181 // Check if one effect chain was awaiting for an effect to be created on this
3182 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003183 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003184 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003185 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003186 thread->addEffectChain_l(chain);
3187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003189
Eric Laurent021cf962014-05-13 10:18:14 -07003190 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003192 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003193 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003194 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003195 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003196 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003197 // remove local strong reference to Client with mClientLock held
3198 Mutex::Autolock _cl(mClientLock);
3199 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003200 } else {
3201 // handle must be valid here, but check again to be safe.
3202 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204 }
3205
haobo101735295ff7b0d2017-03-17 17:44:03 +08003206 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3207 // handle must be cleared outside lock.
3208 handle.clear();
3209 }
3210
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003212 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 return handle;
3214}
3215
Glenn Kastend848eb42016-03-08 13:42:11 -08003216status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003217 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003218{
Steve Block3856b092011-10-20 11:56:00 +01003219 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003220 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003221 Mutex::Autolock _l(mLock);
3222 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003223 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003224 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 }
Eric Laurentde070132010-07-13 04:45:46 -07003226 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3227 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003228 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003229 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 }
Eric Laurentde070132010-07-13 04:45:46 -07003231 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3232 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003233 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003234 return BAD_VALUE;
3235 }
3236
3237 Mutex::Autolock _dl(dstThread->mLock);
3238 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003239 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240}
3241
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003242// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003243status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003244 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003245 AudioFlinger::PlaybackThread *dstThread,
3246 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003247{
Steve Block3856b092011-10-20 11:56:00 +01003248 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003249 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003250
Eric Laurent59255e42011-07-27 19:49:51 -07003251 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003252 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003253 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003254 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003255 return INVALID_OPERATION;
3256 }
3257
Eric Laurent4c415062016-06-17 16:14:16 -07003258 // Check whether the destination thread and all effects in the chain are compatible
3259 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003260 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003261 " destination thread %p is not compatible with effects in the chain",
3262 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003263 return INVALID_OPERATION;
3264 }
3265
Eric Laurent39e94f82010-07-28 01:32:47 -07003266 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003267 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003268 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003269 // removed.
3270 srcThread->removeEffectChain_l(chain);
3271
3272 // transfer all effects one by one so that new effect chain is created on new thread with
3273 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003274 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003275 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003276 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003277 Vector< sp<EffectModule> > removed;
3278 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003279 while (effect != 0) {
3280 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003281 removed.add(effect);
3282 status = dstThread->addEffect_l(effect);
3283 if (status != NO_ERROR) {
3284 break;
3285 }
Eric Laurentec35a142011-10-05 17:42:25 -07003286 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3287 if (effect->state() == EffectModule::ACTIVE ||
3288 effect->state() == EffectModule::STOPPING) {
3289 effect->start();
3290 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003291 // if the move request is not received from audio policy manager, the effect must be
3292 // re-registered with the new strategy and output
3293 if (dstChain == 0) {
3294 dstChain = effect->chain().promote();
3295 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003296 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003297 status = NO_INIT;
3298 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003299 }
3300 strategy = dstChain->strategy();
3301 }
3302 if (reRegister) {
3303 AudioSystem::unregisterEffect(effect->id());
3304 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003305 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003306 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003307 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003308 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003309 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003310 }
Eric Laurentde070132010-07-13 04:45:46 -07003311 effect = chain->getEffectFromId_l(0);
3312 }
3313
Eric Laurent5baf2af2013-09-12 17:37:00 -07003314 if (status != NO_ERROR) {
3315 for (size_t i = 0; i < removed.size(); i++) {
3316 srcThread->addEffect_l(removed[i]);
3317 if (dstChain != 0 && reRegister) {
3318 AudioSystem::unregisterEffect(removed[i]->id());
3319 AudioSystem::registerEffect(&removed[i]->desc(),
3320 srcThread->id(),
3321 strategy,
3322 sessionId,
3323 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003324 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003325 }
3326 }
3327 }
3328
3329 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330}
3331
Eric Laurent5baf2af2013-09-12 17:37:00 -07003332bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003333{
3334 if (mGlobalEffectEnableTime != 0 &&
3335 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3336 return true;
3337 }
3338
3339 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3340 sp<EffectChain> ec =
3341 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003342 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003343 return true;
3344 }
3345 }
3346 return false;
3347}
3348
Eric Laurent5baf2af2013-09-12 17:37:00 -07003349void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003350{
3351 Mutex::Autolock _l(mLock);
3352
3353 mGlobalEffectEnableTime = systemTime();
3354
3355 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3356 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3357 if (t->mType == ThreadBase::OFFLOAD) {
3358 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3359 }
3360 }
3361
3362}
3363
Eric Laurentaaa44472014-09-12 17:41:50 -07003364status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3365{
Eric Laurentd8365c52017-07-16 15:27:05 -07003366 // clear possible suspended state before parking the chain so that it starts in default state
3367 // when attached to a new record thread
3368 chain->setEffectSuspended_l(FX_IID_AEC, false);
3369 chain->setEffectSuspended_l(FX_IID_NS, false);
3370
Glenn Kastend848eb42016-03-08 13:42:11 -08003371 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003372 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003373 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003374 if (index >= 0) {
3375 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3376 return ALREADY_EXISTS;
3377 }
3378 mOrphanEffectChains.add(session, chain);
3379 return NO_ERROR;
3380}
3381
3382sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3383{
3384 sp<EffectChain> chain;
3385 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003386 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003387 if (index >= 0) {
3388 chain = mOrphanEffectChains.valueAt(index);
3389 mOrphanEffectChains.removeItemsAt(index);
3390 }
3391 return chain;
3392}
3393
3394bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3395{
3396 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003397 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003398 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003399 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003400 if (index >= 0) {
3401 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003402 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003403 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003404 mOrphanEffectChains.removeItemsAt(index);
3405 }
3406 return true;
3407 }
3408 return false;
3409}
3410
3411
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412// ----------------------------------------------------------------------------
3413
3414status_t AudioFlinger::onTransact(
3415 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3416{
3417 return BnAudioFlinger::onTransact(code, data, reply, flags);
3418}
3419
Glenn Kasten63238ef2015-03-02 15:50:29 -08003420} // namespace android