blob: b8307ce1b30d61c1a7c0eae63043f1ea95376bba [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
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100900status_t AudioFlinger::setMasterBalance(float balance)
901{
902 status_t ret = initCheck();
903 if (ret != NO_ERROR) {
904 return ret;
905 }
906
907 // check calling permissions
908 if (!settingsAllowed()) {
909 return PERMISSION_DENIED;
910 }
911
912 // check range
913 if (isnan(balance) || fabs(balance) > 1.f) {
914 return BAD_VALUE;
915 }
916
917 Mutex::Autolock _l(mLock);
918
919 // short cut.
920 if (mMasterBalance == balance) return NO_ERROR;
921
922 mMasterBalance = balance;
923
924 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
925 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
926 continue;
927 }
928 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
929 }
930
931 return NO_ERROR;
932}
933
Glenn Kastenf78aee72012-01-04 11:00:47 -0800934status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935{
Eric Laurenta1884f92011-08-23 08:25:03 -0700936 status_t ret = initCheck();
937 if (ret != NO_ERROR) {
938 return ret;
939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940
941 // check calling permissions
942 if (!settingsAllowed()) {
943 return PERMISSION_DENIED;
944 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800945 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000946 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 return BAD_VALUE;
948 }
949
950 { // scope for the lock
951 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700952 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700954 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 mHardwareStatus = AUDIO_HW_IDLE;
956 }
957
958 if (NO_ERROR == ret) {
959 Mutex::Autolock _l(mLock);
960 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800961 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700962 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 }
964
965 return ret;
966}
967
968status_t AudioFlinger::setMicMute(bool state)
969{
Eric Laurenta1884f92011-08-23 08:25:03 -0700970 status_t ret = initCheck();
971 if (ret != NO_ERROR) {
972 return ret;
973 }
974
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 // check calling permissions
976 if (!settingsAllowed()) {
977 return PERMISSION_DENIED;
978 }
979
980 AutoMutex lock(mHardwareLock);
981 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700982 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700983 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
984 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700985 if (result != NO_ERROR) {
986 ret = result;
987 }
988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 mHardwareStatus = AUDIO_HW_IDLE;
990 return ret;
991}
992
993bool AudioFlinger::getMicMute() const
994{
Eric Laurenta1884f92011-08-23 08:25:03 -0700995 status_t ret = initCheck();
996 if (ret != NO_ERROR) {
997 return false;
998 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800999 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001000 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001001 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001003 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001004 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1005 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001006 if (result == NO_ERROR) {
1007 mute = mute && state;
1008 }
1009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001011
1012 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013}
1014
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001015void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1016{
1017 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1018
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001019 AutoMutex lock(mLock);
1020 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001021 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1022 }
1023 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1024 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001025 }
1026}
1027
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028status_t AudioFlinger::setMasterMute(bool muted)
1029{
John Grossmand8f178d2012-07-20 14:51:35 -07001030 status_t ret = initCheck();
1031 if (ret != NO_ERROR) {
1032 return ret;
1033 }
1034
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 // check calling permissions
1036 if (!settingsAllowed()) {
1037 return PERMISSION_DENIED;
1038 }
1039
John Grossmanee578c02012-07-23 17:05:46 -07001040 Mutex::Autolock _l(mLock);
1041 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001042
John Grossmanee578c02012-07-23 17:05:46 -07001043 // Set master mute in the HALs which support it.
1044 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1045 AutoMutex lock(mHardwareLock);
1046 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001047
John Grossmanee578c02012-07-23 17:05:46 -07001048 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1049 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001050 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001051 }
John Grossmanee578c02012-07-23 17:05:46 -07001052 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001053 }
1054
John Grossmanee578c02012-07-23 17:05:46 -07001055 // Now set the master mute in each playback thread. Playback threads
1056 // assigned to HALs which do not have master mute support will apply master
1057 // mute during the mix operation. Threads with HALs which do support master
1058 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001059 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1060 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1061 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063
1064 return NO_ERROR;
1065}
1066
1067float AudioFlinger::masterVolume() const
1068{
Glenn Kasten98067102011-12-13 11:47:54 -08001069 Mutex::Autolock _l(mLock);
1070 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071}
1072
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001073status_t AudioFlinger::getMasterBalance(float *balance) const
1074{
1075 Mutex::Autolock _l(mLock);
1076 *balance = getMasterBalance_l();
1077 return NO_ERROR; // if called through binder, may return a transactional error
1078}
1079
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080bool AudioFlinger::masterMute() const
1081{
Glenn Kasten98067102011-12-13 11:47:54 -08001082 Mutex::Autolock _l(mLock);
1083 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084}
1085
John Grossman4ff14ba2012-02-08 16:37:41 -08001086float AudioFlinger::masterVolume_l() const
1087{
John Grossman4ff14ba2012-02-08 16:37:41 -08001088 return mMasterVolume;
1089}
1090
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001091float AudioFlinger::getMasterBalance_l() const
1092{
1093 return mMasterBalance;
1094}
1095
John Grossmand8f178d2012-07-20 14:51:35 -07001096bool AudioFlinger::masterMute_l() const
1097{
John Grossmanee578c02012-07-23 17:05:46 -07001098 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001099}
1100
Eric Laurent223fd5c2014-11-11 13:43:36 -08001101status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1102{
1103 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001104 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001105 return BAD_VALUE;
1106 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001107 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1108 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1109 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001110 return PERMISSION_DENIED;
1111 }
1112
1113 return NO_ERROR;
1114}
1115
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001116status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1117 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118{
1119 // check calling permissions
1120 if (!settingsAllowed()) {
1121 return PERMISSION_DENIED;
1122 }
1123
Eric Laurent223fd5c2014-11-11 13:43:36 -08001124 status_t status = checkStreamType(stream);
1125 if (status != NO_ERROR) {
1126 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 }
Eric Laurent98e38192018-02-15 18:31:53 -08001128 if (output == AUDIO_IO_HANDLE_NONE) {
1129 return BAD_VALUE;
1130 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001131 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132
1133 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001134 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1135 if (volumeInterface == NULL) {
1136 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 }
Eric Laurent98e38192018-02-15 18:31:53 -08001138 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139
1140 return NO_ERROR;
1141}
1142
Glenn Kastenfff6d712012-01-12 16:38:12 -08001143status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144{
1145 // check calling permissions
1146 if (!settingsAllowed()) {
1147 return PERMISSION_DENIED;
1148 }
1149
Eric Laurent223fd5c2014-11-11 13:43:36 -08001150 status_t status = checkStreamType(stream);
1151 if (status != NO_ERROR) {
1152 return status;
1153 }
1154 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1155
1156 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001157 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 return BAD_VALUE;
1159 }
1160
Eric Laurent93575202011-01-18 18:39:02 -08001161 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001163 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1164 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1165 volumeInterfaces[i]->setStreamMute(stream, muted);
1166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167
1168 return NO_ERROR;
1169}
1170
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001171float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001173 status_t status = checkStreamType(stream);
1174 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 return 0.0f;
1176 }
Eric Laurent98e38192018-02-15 18:31:53 -08001177 if (output == AUDIO_IO_HANDLE_NONE) {
1178 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 }
1180
Eric Laurent98e38192018-02-15 18:31:53 -08001181 AutoMutex lock(mLock);
1182 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1183 if (volumeInterface == NULL) {
1184 return 0.0f;
1185 }
1186
1187 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188}
1189
Glenn Kastenfff6d712012-01-12 16:38:12 -08001190bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001192 status_t status = checkStreamType(stream);
1193 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 return true;
1195 }
1196
Glenn Kasten6637baa2012-01-09 09:40:36 -08001197 AutoMutex lock(mLock);
1198 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199}
1200
Eric Laurent054d9d32015-04-24 08:48:48 -07001201
1202void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1203{
1204 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1205 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1206 }
1207}
1208
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001209// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1210void AudioFlinger::forwardParametersToDownstreamPatches_l(
1211 audio_io_handle_t upStream, const String8& keyValuePairs,
1212 std::function<bool(const sp<PlaybackThread>&)> useThread)
1213{
1214 std::vector<PatchPanel::SoftwarePatch> swPatches;
1215 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1216 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1217 __func__, swPatches.size(), upStream);
1218 for (const auto& swPatch : swPatches) {
1219 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1220 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1221 downStream->setParameters(keyValuePairs);
1222 }
1223 }
1224}
1225
Eric Laurentf1047e82018-04-16 19:18:20 -07001226// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1227// Some keys are used for audio routing and audio path configuration and should be reserved for use
1228// by audio policy and audio flinger for functional, privacy and security reasons.
1229void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1230{
1231 static const String8 kReservedParameters[] = {
1232 String8(AudioParameter::keyRouting),
1233 String8(AudioParameter::keySamplingRate),
1234 String8(AudioParameter::keyFormat),
1235 String8(AudioParameter::keyChannels),
1236 String8(AudioParameter::keyFrameCount),
1237 String8(AudioParameter::keyInputSource),
1238 String8(AudioParameter::keyMonoOutput),
1239 String8(AudioParameter::keyStreamConnect),
1240 String8(AudioParameter::keyStreamDisconnect),
1241 String8(AudioParameter::keyStreamSupportedFormats),
1242 String8(AudioParameter::keyStreamSupportedChannels),
1243 String8(AudioParameter::keyStreamSupportedSamplingRates),
1244 };
1245
Andy Hung4ef19fa2018-05-15 19:35:29 -07001246 if (isAudioServerUid(callingUid)) {
1247 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001248 }
1249
1250 AudioParameter param = AudioParameter(keyValuePairs);
1251 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001252 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001253 for (auto& key : kReservedParameters) {
1254 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001255 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001256 param.remove(key);
1257 }
1258 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001259 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1260 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001261 keyValuePairs = param.toString();
1262}
1263
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001264void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1265 size_t rejectedKVPSize, const String8& rejectedKVPs,
1266 uid_t callingUid) {
1267 auto prefix = String8::format("UID %5d", callingUid);
1268 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1269 if (rejectedKVPSize != 0) {
1270 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1271 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1272 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1273 } else {
1274 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1275 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1276 }
1277}
1278
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001279status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280{
Eric Laurentf1047e82018-04-16 19:18:20 -07001281 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1282 ioHandle, keyValuePairs.string(),
1283 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001284
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 // check calling permissions
1286 if (!settingsAllowed()) {
1287 return PERMISSION_DENIED;
1288 }
1289
Eric Laurentf1047e82018-04-16 19:18:20 -07001290 String8 filteredKeyValuePairs = keyValuePairs;
1291 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1292
1293 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1294
Glenn Kasten142f5192014-03-25 17:44:59 -07001295 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1296 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001297 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001298 // result will remain NO_INIT if no audio device is present
1299 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001300 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001301 AutoMutex lock(mHardwareLock);
1302 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1303 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001304 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001305 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001306 // return success if at least one audio device accepts the parameters as not all
1307 // HALs are requested to support all parameters. If no audio device supports the
1308 // requested parameters, the last error is reported.
1309 if (final_result != NO_ERROR) {
1310 final_result = result;
1311 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001312 }
1313 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001314 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001315 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001316 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001317 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001318 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1319 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001320 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001321 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001322 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001323 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001324 }
1325 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001326 String8 screenState;
1327 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001328 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001329 if (isOff != (AudioFlinger::mScreenState & 1)) {
1330 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001331 }
1332 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001333 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334 }
1335
1336 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1337 // and the thread is exited once the lock is released
1338 sp<ThreadBase> thread;
1339 {
1340 Mutex::Autolock _l(mLock);
1341 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001342 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001343 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001344 if (thread == 0) {
1345 thread = checkMmapThread_l(ioHandle);
1346 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001347 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001348 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001349 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001350 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001351 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1352 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001353 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355 }
1356 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001357 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001358 status_t result = thread->setParameters(filteredKeyValuePairs);
1359 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1360 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361 }
1362 return BAD_VALUE;
1363}
1364
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001365String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001367 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1368 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369
Eric Laurenta4c5a552012-03-29 10:12:40 -07001370 Mutex::Autolock _l(mLock);
1371
Glenn Kasten142f5192014-03-25 17:44:59 -07001372 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001373 String8 out_s8;
1374
Dima Zavin799a70e2011-04-18 16:57:27 -07001375 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001376 String8 s;
1377 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001378 {
1379 AutoMutex lock(mHardwareLock);
1380 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001381 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1382 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001383 mHardwareStatus = AUDIO_HW_IDLE;
1384 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001385 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001386 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001387 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001388 }
1389
Eric Laurent6acd1d42017-01-04 14:23:29 -08001390 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1391 if (thread == NULL) {
1392 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1393 if (thread == NULL) {
1394 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1395 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001396 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001397 }
1398 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001400 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001401}
1402
Glenn Kastendd8104c2012-07-02 12:42:44 -07001403size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1404 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405{
Eric Laurenta1884f92011-08-23 08:25:03 -07001406 status_t ret = initCheck();
1407 if (ret != NO_ERROR) {
1408 return 0;
1409 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001410 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001411 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001412 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001413 return 0;
1414 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001415
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001416 AutoMutex lock(mHardwareLock);
1417 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001418 audio_config_t config, proposed;
1419 memset(&proposed, 0, sizeof(proposed));
1420 proposed.sample_rate = sampleRate;
1421 proposed.channel_mask = channelMask;
1422 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001423
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001424 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001425 size_t frames;
1426 for (;;) {
1427 // Note: config is currently a const parameter for get_input_buffer_size()
1428 // but we use a copy from proposed in case config changes from the call.
1429 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001430 status_t result = dev->getInputBufferSize(&config, &frames);
1431 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001432 break; // hal success, config is the result
1433 }
1434 // change one parameter of the configuration each iteration to a more "common" value
1435 // to see if the device will support it.
1436 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1437 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1438 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1439 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1440 } else {
1441 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1442 "format %#x, channelMask 0x%X",
1443 sampleRate, format, channelMask);
1444 break; // retries failed, break out of loop with frames == 0.
1445 }
1446 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001447 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001448 if (frames > 0 && config.sample_rate != sampleRate) {
1449 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1450 }
1451 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452}
1453
Glenn Kasten5f972c02014-01-13 09:59:31 -08001454uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 Mutex::Autolock _l(mLock);
1457
1458 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1459 if (recordThread != NULL) {
1460 return recordThread->getInputFramesLost();
1461 }
1462 return 0;
1463}
1464
1465status_t AudioFlinger::setVoiceVolume(float value)
1466{
Eric Laurenta1884f92011-08-23 08:25:03 -07001467 status_t ret = initCheck();
1468 if (ret != NO_ERROR) {
1469 return ret;
1470 }
1471
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 // check calling permissions
1473 if (!settingsAllowed()) {
1474 return PERMISSION_DENIED;
1475 }
1476
1477 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001478 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001479 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001480 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 mHardwareStatus = AUDIO_HW_IDLE;
1482
1483 return ret;
1484}
1485
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001486status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001487 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 Mutex::Autolock _l(mLock);
1490
1491 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1492 if (playbackThread != NULL) {
1493 return playbackThread->getRenderPosition(halFrames, dspFrames);
1494 }
1495
1496 return BAD_VALUE;
1497}
1498
1499void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1500{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001502 if (client == 0) {
1503 return;
1504 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001505 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001506 {
1507 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001508 if (mNotificationClients.indexOfKey(pid) < 0) {
1509 sp<NotificationClient> notificationClient = new NotificationClient(this,
1510 client,
1511 pid);
1512 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513
Eric Laurent021cf962014-05-13 10:18:14 -07001514 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515
Marco Nelissen06b46062014-11-14 07:58:25 -08001516 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001517 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001518 }
1519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520
Eric Laurent021cf962014-05-13 10:18:14 -07001521 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001522 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001523 // the config change is always sent from playback or record threads to avoid deadlock
1524 // with AudioSystem::gLock
1525 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001526 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001529 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001530 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 }
1532}
1533
1534void AudioFlinger::removeNotificationClient(pid_t pid)
1535{
1536 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001537 {
1538 Mutex::Autolock _cl(mClientLock);
1539 mNotificationClients.removeItem(pid);
1540 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001541
Steve Block3856b092011-10-20 11:56:00 +01001542 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001543 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001544 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001545 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001546 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001547 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001548 if (ref->mPid == pid) {
1549 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001550 mAudioSessionRefs.removeAt(i);
1551 delete ref;
1552 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001553 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001554 } else {
1555 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001556 }
1557 }
1558 if (removed) {
1559 purgeStaleEffects_l();
1560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561}
1562
Eric Laurent73e26b62015-04-27 16:55:58 -07001563void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001564 const sp<AudioIoDescriptor>& ioDesc,
1565 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566{
Eric Laurent021cf962014-05-13 10:18:14 -07001567 Mutex::Autolock _l(mClientLock);
1568 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001570 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1571 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 }
1574}
1575
Eric Laurent021cf962014-05-13 10:18:14 -07001576// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577void AudioFlinger::removeClient_l(pid_t pid)
1578{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001579 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001580 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 mClients.removeItem(pid);
1582}
1583
Eric Laurent717e1282012-06-29 16:36:52 -07001584// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001585sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1586 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001587{
1588 sp<PlaybackThread> thread;
1589
1590 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1591 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1592 ALOG_ASSERT(thread == 0);
1593 thread = mPlaybackThreads.valueAt(i);
1594 }
1595 }
1596
1597 return thread;
1598}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601
1602// ----------------------------------------------------------------------------
1603
1604AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1605 : RefBase(),
1606 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001607 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608{
Andy Hung6f248bb2018-01-23 14:04:37 -08001609 mMemoryDealer = new MemoryDealer(
1610 audioFlinger->getClientSharedHeapSize(),
1611 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612}
1613
Eric Laurent021cf962014-05-13 10:18:14 -07001614// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615AudioFlinger::Client::~Client()
1616{
1617 mAudioFlinger->removeClient_l(mPid);
1618}
1619
Glenn Kasten435dbe62012-01-30 10:15:48 -08001620sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621{
1622 return mMemoryDealer;
1623}
1624
1625// ----------------------------------------------------------------------------
1626
1627AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1628 const sp<IAudioFlingerClient>& client,
1629 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001630 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631{
1632}
1633
1634AudioFlinger::NotificationClient::~NotificationClient()
1635{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636}
1637
Glenn Kasten0f11b512014-01-31 16:18:54 -08001638void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639{
1640 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001641 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642}
1643
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001644// ----------------------------------------------------------------------------
1645AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1646 : mPendingRequests(false) {}
1647
1648
1649void AudioFlinger::MediaLogNotifier::requestMerge() {
1650 AutoMutex _l(mMutex);
1651 mPendingRequests = true;
1652 mCond.signal();
1653}
1654
1655bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001656 // Should already have been checked, but just in case
1657 if (sMediaLogService == 0) {
1658 return false;
1659 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001660 // Wait until there are pending requests
1661 {
1662 AutoMutex _l(mMutex);
1663 mPendingRequests = false; // to ignore past requests
1664 while (!mPendingRequests) {
1665 mCond.wait(mMutex);
1666 // TODO may also need an exitPending check
1667 }
1668 mPendingRequests = false;
1669 }
1670 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001671 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001672 usleep(kPostTriggerSleepPeriod);
1673 return true;
1674}
1675
1676void AudioFlinger::requestLogMerge() {
1677 mMediaLogNotifier->requestMerge();
1678}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679
1680// ----------------------------------------------------------------------------
1681
Eric Laurentf14db3c2017-12-08 14:20:36 -08001682sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1683 CreateRecordOutput& output,
1684 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685{
1686 sp<RecordThread::RecordTrack> recordTrack;
1687 sp<RecordHandle> recordHandle;
1688 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001690 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001691 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692
Eric Laurentf14db3c2017-12-08 14:20:36 -08001693 output.cblk.clear();
1694 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001695 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001696
Eric Laurentf14db3c2017-12-08 14:20:36 -08001697 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001698 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001699 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001700 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001701 ALOGW_IF(clientUid != callingUid,
1702 "%s uid %d tried to pass itself off as %d",
1703 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001704 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001705 updatePid = true;
1706 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001707 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001708 if (updatePid) {
1709 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001710 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001711 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001712 __func__, callingUid, callingPid, clientPid);
1713 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001714 }
1715
Andy Hung6770c6f2015-04-07 13:43:36 -07001716 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001717 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1718 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001719 lStatus = BAD_VALUE;
1720 goto Exit;
1721 }
1722
Glenn Kasten53b5d092014-02-05 10:00:23 -08001723 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001724 if (!audio_is_input_channel(input.config.channel_mask)) {
1725 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001726 lStatus = BAD_VALUE;
1727 goto Exit;
1728 }
1729
Eric Laurentf14db3c2017-12-08 14:20:36 -08001730 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1731 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1732 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1733 lStatus = BAD_VALUE;
1734 goto Exit;
1735 }
1736
1737 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001738 output.selectedDeviceId = input.selectedDeviceId;
1739 output.flags = input.flags;
1740
1741 client = registerPid(clientPid);
1742
1743 // Not a conventional loop, but a retry loop for at most two iterations total.
1744 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1745 // Exits loop via break on no error of got exit on error
1746 // The sp<> references will be dropped when re-entering scope.
1747 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1748 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001749 // release previously opened input if retrying.
1750 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1751 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001752 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001753 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001754 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001755 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001756 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001757 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1758 sessionId,
1759 // FIXME compare to AudioTrack
1760 clientPid,
1761 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001762 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001763 &input.config,
1764 output.flags, &output.selectedDeviceId, &portId);
1765
Glenn Kasten05997e22014-03-13 15:08:33 -07001766 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001768 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001770 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 lStatus = BAD_VALUE;
1772 goto Exit;
1773 }
1774
Eric Laurentf14db3c2017-12-08 14:20:36 -08001775 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776
Eric Laurentf14db3c2017-12-08 14:20:36 -08001777 output.sampleRate = input.config.sample_rate;
1778 output.frameCount = input.frameCount;
1779 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001780
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001781 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001782 input.config.format, input.config.channel_mask,
1783 &output.frameCount, sessionId,
1784 &output.notificationFrameCount,
1785 clientUid, &output.flags,
1786 input.clientInfo.clientTid,
1787 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001788 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001789
Eric Laurentf14db3c2017-12-08 14:20:36 -08001790 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1791 // audio policy manager without FAST constraint
1792 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001793 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001794 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001795
1796 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001797 goto Exit;
1798 }
1799
1800 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1801 // session and move it to this thread.
1802 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1803 if (chain != 0) {
1804 Mutex::Autolock _l(thread->mLock);
1805 thread->addEffectChain_l(chain);
1806 }
1807 break;
1808 }
1809 // End of retry loop.
1810 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811 }
Glenn Kastene198c362013-08-13 09:13:36 -07001812
Eric Laurentf14db3c2017-12-08 14:20:36 -08001813 output.cblk = recordTrack->getCblk();
1814 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001815 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001816
1817 // return handle to client
1818 recordHandle = new RecordHandle(recordTrack);
1819
1820Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001821 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001822 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001823 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001824 // Don't hold mClientLock when releasing the reference on the track as the
1825 // destructor will acquire it.
1826 {
1827 Mutex::Autolock _cl(mClientLock);
1828 client.clear();
1829 }
Eric Laurent896c9672017-12-08 14:08:45 -08001830 recordTrack.clear();
1831 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001832 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001833 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 }
1835
Glenn Kasten9156ef32013-08-06 15:39:08 -07001836 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 return recordHandle;
1838}
1839
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001840
1841
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842// ----------------------------------------------------------------------------
1843
Eric Laurenta4c5a552012-03-29 10:12:40 -07001844audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1845{
Eric Laurent44622db2014-08-01 19:00:33 -07001846 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001847 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001848 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001849 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001850 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001851 }
1852 Mutex::Autolock _l(mLock);
1853 return loadHwModule_l(name);
1854}
1855
1856// loadHwModule_l() must be called with AudioFlinger::mLock held
1857audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1858{
1859 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1860 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1861 ALOGW("loadHwModule() module %s already loaded", name);
1862 return mAudioHwDevs.keyAt(i);
1863 }
1864 }
1865
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001866 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001867
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001868 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001869 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001870 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001871 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001872 }
1873
1874 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001875 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001876 mHardwareStatus = AUDIO_HW_IDLE;
1877 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001878 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001879 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001880 }
1881
John Grossmanee578c02012-07-23 17:05:46 -07001882 // Check and cache this HAL's level of support for master mute and master
1883 // volume. If this is the first HAL opened, and it supports the get
1884 // methods, use the initial values provided by the HAL as the current
1885 // master mute and volume settings.
1886
1887 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1888 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001889 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001890
1891 if (0 == mAudioHwDevs.size()) {
1892 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001893 float mv;
1894 if (OK == dev->getMasterVolume(&mv)) {
1895 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001896 }
1897
1898 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001899 bool mm;
1900 if (OK == dev->getMasterMute(&mm)) {
1901 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001902 }
1903 }
1904
Eric Laurenta4c5a552012-03-29 10:12:40 -07001905 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001906 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001907 flags = static_cast<AudioHwDevice::Flags>(flags |
1908 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1909 }
1910
1911 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001912 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001913 flags = static_cast<AudioHwDevice::Flags>(flags |
1914 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1915 }
1916
Eric Laurenta4c5a552012-03-29 10:12:40 -07001917 mHardwareStatus = AUDIO_HW_IDLE;
1918 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07001919 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07001920 // An MSD module is inserted before hardware modules in order to mix encoded streams.
1921 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
1922 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001923
Glenn Kastena13cde92016-03-28 15:26:02 -07001924 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001925 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001926
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001927 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001928
1929 return handle;
1930
1931}
1932
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001933// ----------------------------------------------------------------------------
1934
Glenn Kasten3b16c762012-11-14 08:44:39 -08001935uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001936{
1937 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001938 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001939 return thread != NULL ? thread->sampleRate() : 0;
1940}
1941
Glenn Kastene33054e2012-11-14 12:54:39 -08001942size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001943{
1944 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001945 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001946 return thread != NULL ? thread->frameCountHAL() : 0;
1947}
1948
1949// ----------------------------------------------------------------------------
1950
Andy Hung6f248bb2018-01-23 14:04:37 -08001951status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001952{
1953 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001954 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001955 return PERMISSION_DENIED;
1956 }
1957 Mutex::Autolock _l(mLock);
1958 if (mIsDeviceTypeKnown) {
1959 return INVALID_OPERATION;
1960 }
1961 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001962 mTotalMemory = totalMemory;
1963 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1964 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1965 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1966 // though actual setting is determined through device configuration.
1967 constexpr int64_t GB = 1024 * 1024 * 1024;
1968 mClientSharedHeapSize =
1969 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1970 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1971 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1972 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1973 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001974 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001975
1976 // TODO: Cache the client shared heap size in a persistent property.
1977 // It's possible that a native process or Java service or app accesses audioserver
1978 // after it is registered by system server, but before AudioService updates
1979 // the memory info. This would occur immediately after boot or an audioserver
1980 // crash and restore. Before update from AudioService, the client would get the
1981 // minimum heap size.
1982
1983 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1984 (isLowRamDevice ? "true" : "false"),
1985 (long long)mTotalMemory,
1986 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001987 return NO_ERROR;
1988}
1989
Andy Hung6f248bb2018-01-23 14:04:37 -08001990size_t AudioFlinger::getClientSharedHeapSize() const
1991{
1992 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1993 if (heapSizeInBytes != 0) { // read-only property overrides all.
1994 return heapSizeInBytes;
1995 }
1996 return mClientSharedHeapSize;
1997}
1998
Mikhail Naganovdea53042018-04-26 13:10:21 -07001999status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2000{
2001 ALOGV(__func__);
2002
2003 audio_module_handle_t module;
2004 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2005 module = config->ext.device.hw_module;
2006 } else {
2007 module = config->ext.mix.hw_module;
2008 }
2009
2010 Mutex::Autolock _l(mLock);
2011 ssize_t index = mAudioHwDevs.indexOfKey(module);
2012 if (index < 0) {
2013 ALOGW("%s() bad hw module %d", __func__, module);
2014 return BAD_VALUE;
2015 }
2016
2017 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2018 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2019}
2020
Eric Laurent93c3d412014-08-01 14:48:35 -07002021audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2022{
2023 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002024
2025 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2026 if (index >= 0) {
2027 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2028 mHwAvSyncIds.valueAt(index), sessionId);
2029 return mHwAvSyncIds.valueAt(index);
2030 }
2031
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002032 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002033 if (dev == NULL) {
2034 return AUDIO_HW_SYNC_INVALID;
2035 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002036 String8 reply;
2037 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002038 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002039 param = AudioParameter(reply);
2040 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002041
2042 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002043 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002044 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2045 return AUDIO_HW_SYNC_INVALID;
2046 }
2047
2048 // allow only one session for a given HW A/V sync ID.
2049 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2050 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2051 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2052 value, mHwAvSyncIds.keyAt(i));
2053 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002054 break;
2055 }
2056 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002057
2058 mHwAvSyncIds.add(sessionId, value);
2059
2060 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2061 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2062 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002063 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002064 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002065 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002066 String8 keyValuePairs = param.toString();
2067 thread->setParameters(keyValuePairs);
2068 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2069 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002070 break;
2071 }
2072 }
2073
2074 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2075 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002076}
2077
Eric Laurent72e3f392015-05-20 14:43:50 -07002078status_t AudioFlinger::systemReady()
2079{
2080 Mutex::Autolock _l(mLock);
2081 ALOGI("%s", __FUNCTION__);
2082 if (mSystemReady) {
2083 ALOGW("%s called twice", __FUNCTION__);
2084 return NO_ERROR;
2085 }
2086 mSystemReady = true;
2087 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2088 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2089 thread->systemReady();
2090 }
2091 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2092 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2093 thread->systemReady();
2094 }
2095 return NO_ERROR;
2096}
2097
jiabin46a76fa2018-01-05 10:18:21 -08002098status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2099{
jiabin9ff780e2018-03-19 18:19:52 -07002100 AutoMutex lock(mHardwareLock);
2101 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2102 status_t status = dev->getMicrophones(microphones);
2103 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002104}
2105
Eric Laurentfa90e842014-10-17 18:12:31 -07002106// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2107void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2108{
2109 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2110 if (index >= 0) {
2111 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2112 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2113 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002114 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002115 String8 keyValuePairs = param.toString();
2116 thread->setParameters(keyValuePairs);
2117 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2118 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002119 }
2120}
2121
2122
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002123// ----------------------------------------------------------------------------
2124
Eric Laurent83b88082014-06-20 18:31:16 -07002125
Eric Laurent6acd1d42017-01-04 14:23:29 -08002126sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002127 audio_io_handle_t *output,
2128 audio_config_t *config,
2129 audio_devices_t devices,
2130 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002131 audio_output_flags_t flags)
2132{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002133 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002134 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002135 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002136 }
2137
Eric Laurentcf2c0212014-07-25 16:20:43 -07002138 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002139 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2140 } else {
2141 // Audio Policy does not currently request a specific output handle.
2142 // If this is ever needed, see openInput_l() for example code.
2143 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2144 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002145 }
Eric Laurent83b88082014-06-20 18:31:16 -07002146
2147 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2148
Eric Laurent83b88082014-06-20 18:31:16 -07002149 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002150 // This if statement allows overriding the audio policy settings
2151 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2152 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2153 // Check only for Normal Mixing mode
2154 if (kEnableExtendedPrecision) {
2155 // Specify format (uncomment one below to choose)
2156 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2157 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2158 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2159 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002160 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002161 }
2162 if (kEnableExtendedChannels) {
2163 // Specify channel mask (uncomment one below to choose)
2164 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2165 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2166 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2167 }
Eric Laurent83b88082014-06-20 18:31:16 -07002168 }
2169
Phil Burk062e67a2015-02-11 13:40:50 -08002170 AudioStreamOut *outputStream = NULL;
2171 status_t status = outHwDev->openOutputStream(
2172 &outputStream,
2173 *output,
2174 devices,
2175 flags,
2176 config,
2177 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002178
2179 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002180
Phil Burk062e67a2015-02-11 13:40:50 -08002181 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002182 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2183 sp<MmapPlaybackThread> thread =
2184 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2185 devices, AUDIO_DEVICE_NONE, mSystemReady);
2186 mMmapThreads.add(*output, thread);
2187 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2188 *output, thread.get());
2189 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002190 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002191 sp<PlaybackThread> thread;
2192 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2193 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2194 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2195 *output, thread.get());
2196 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2197 || !isValidPcmSinkFormat(config->format)
2198 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2199 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2200 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2201 *output, thread.get());
2202 } else {
2203 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2204 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2205 *output, thread.get());
2206 }
2207 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002208 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002209 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002210 }
Eric Laurent83b88082014-06-20 18:31:16 -07002211 }
2212
2213 return 0;
2214}
2215
Eric Laurentcf2c0212014-07-25 16:20:43 -07002216status_t AudioFlinger::openOutput(audio_module_handle_t module,
2217 audio_io_handle_t *output,
2218 audio_config_t *config,
2219 audio_devices_t *devices,
2220 const String8& address,
2221 uint32_t *latencyMs,
2222 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002224 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2225 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002226 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002227 (devices != NULL) ? *devices : 0,
2228 config->sample_rate,
2229 config->format,
2230 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002231 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002233 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002234 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002236
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 Mutex::Autolock _l(mLock);
2238
Eric Laurent6acd1d42017-01-04 14:23:29 -08002239 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002240 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002241 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2242 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2243 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245 // notify client processes of the new output creation
2246 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002247
Eric Laurent6acd1d42017-01-04 14:23:29 -08002248 // the first primary output opened designates the primary hw device
2249 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002250 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002251 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002252
Eric Laurent6acd1d42017-01-04 14:23:29 -08002253 AutoMutex lock(mHardwareLock);
2254 mHardwareStatus = AUDIO_HW_SET_MODE;
2255 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2256 mHardwareStatus = AUDIO_HW_IDLE;
2257 }
2258 } else {
2259 MmapThread *mmapThread = (MmapThread *)thread.get();
2260 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002261 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002262 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 }
2264
Eric Laurentcf2c0212014-07-25 16:20:43 -07002265 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266}
2267
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002268audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2269 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270{
2271 Mutex::Autolock _l(mLock);
2272 MixerThread *thread1 = checkMixerThread_l(output1);
2273 MixerThread *thread2 = checkMixerThread_l(output2);
2274
2275 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002276 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2277 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002278 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 }
2280
Glenn Kasteneeecb982016-02-26 10:44:04 -08002281 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002282 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283 thread->addOutputTrack(thread2);
2284 mPlaybackThreads.add(id, thread);
2285 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002286 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 return id;
2288}
2289
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002290status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291{
Glenn Kastend96c5722012-04-25 13:44:49 -07002292 return closeOutput_nonvirtual(output);
2293}
2294
2295status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2296{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 // keep strong reference on the playback thread so that
2298 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002299 sp<PlaybackThread> playbackThread;
2300 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301 {
2302 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002303 playbackThread = checkPlaybackThread_l(output);
2304 if (playbackThread != NULL) {
2305 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306
Andy Hungdc099c22018-09-18 13:46:39 -07002307 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002308
Eric Laurent6acd1d42017-01-04 14:23:29 -08002309 if (playbackThread->type() == ThreadBase::MIXER) {
2310 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2311 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2312 DuplicatingThread *dupThread =
2313 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2314 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2315 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002316 }
2317 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002318
2319
Eric Laurent6acd1d42017-01-04 14:23:29 -08002320 mPlaybackThreads.removeItem(output);
2321 // save all effects to the default thread
2322 if (mPlaybackThreads.size()) {
2323 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2324 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002325 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002326 Mutex::Autolock _dl(dstThread->mLock);
2327 Mutex::Autolock _sl(playbackThread->mLock);
2328 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2329 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002330 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2331 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 }
2334 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002335 } else {
2336 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2337 if (mmapThread == 0) {
2338 return BAD_VALUE;
2339 }
Andy Hungdc099c22018-09-18 13:46:39 -07002340 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002341 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002342 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002344 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2345 ioDesc->mIoHandle = output;
2346 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002347 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002349 // The thread entity (active unit of execution) is no longer running here,
2350 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351
Eric Laurent6acd1d42017-01-04 14:23:29 -08002352 if (playbackThread != 0) {
2353 playbackThread->exit();
2354 if (!playbackThread->isDuplicating()) {
2355 closeOutputFinish(playbackThread);
2356 }
2357 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002358 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002359 mmapThread->exit();
2360 AudioStreamOut *out = mmapThread->clearOutput();
2361 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2362 // from now on thread->mOutput is NULL
2363 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 }
2365 return NO_ERROR;
2366}
2367
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002368void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002369{
2370 AudioStreamOut *out = thread->clearOutput();
2371 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2372 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002373 delete out;
2374}
2375
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002376void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002377{
2378 mPlaybackThreads.removeItem(thread->mId);
2379 thread->exit();
2380 closeOutputFinish(thread);
2381}
2382
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002383status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384{
2385 Mutex::Autolock _l(mLock);
2386 PlaybackThread *thread = checkPlaybackThread_l(output);
2387
2388 if (thread == NULL) {
2389 return BAD_VALUE;
2390 }
2391
Steve Block3856b092011-10-20 11:56:00 +01002392 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 thread->suspend();
2394
2395 return NO_ERROR;
2396}
2397
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002398status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399{
2400 Mutex::Autolock _l(mLock);
2401 PlaybackThread *thread = checkPlaybackThread_l(output);
2402
2403 if (thread == NULL) {
2404 return BAD_VALUE;
2405 }
2406
Steve Block3856b092011-10-20 11:56:00 +01002407 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408
2409 thread->restore();
2410
2411 return NO_ERROR;
2412}
2413
Eric Laurentcf2c0212014-07-25 16:20:43 -07002414status_t AudioFlinger::openInput(audio_module_handle_t module,
2415 audio_io_handle_t *input,
2416 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002417 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002418 const String8& address,
2419 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002420 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421{
Eric Laurent83b88082014-06-20 18:31:16 -07002422 Mutex::Autolock _l(mLock);
2423
Glenn Kastene7d66712015-03-05 13:46:52 -08002424 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002425 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002426 }
2427
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002428 sp<ThreadBase> thread = openInput_l(
2429 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002430
2431 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002432 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002433 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002434 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002436 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002437}
Dima Zavin799a70e2011-04-18 16:57:27 -07002438
Eric Laurent6acd1d42017-01-04 14:23:29 -08002439sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002440 audio_io_handle_t *input,
2441 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002442 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002443 const String8& address,
2444 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002445 audio_input_flags_t flags,
2446 audio_devices_t outputDevice,
2447 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002448{
Glenn Kastene7d66712015-03-05 13:46:52 -08002449 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002450 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002451 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002452 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002453 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002454
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002455 // Some flags are specific to framework and must not leak to the HAL.
2456 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2457
Glenn Kasteneeecb982016-02-26 10:44:04 -08002458 // Audio Policy can request a specific handle for hardware hotword.
2459 // The goal here is not to re-open an already opened input.
2460 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002461 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002462 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2463 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2464 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2465 return 0;
2466 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2467 // This should not happen in a transient state with current design.
2468 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2469 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002470 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002471
Eric Laurentcf2c0212014-07-25 16:20:43 -07002472 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002473 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002474 sp<StreamInHalInterface> inStream;
2475 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002476 *input, devices, &halconfig, flags, address.string(), source,
2477 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002478 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2479 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002480 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002481 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002482 halconfig.sample_rate,
2483 halconfig.format,
2484 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002485 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002486 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002488 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002489 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002490 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002491 audio_is_linear_pcm(config->format) &&
2492 audio_is_linear_pcm(halconfig.format) &&
2493 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002494 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2495 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002496 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002497 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002498 inStream.clear();
2499 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002500 *input, devices, &halconfig, flags, address.string(), source,
2501 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002502 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 }
2504
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002505 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002506 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002507 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2508 sp<MmapCaptureThread> thread =
2509 new MmapCaptureThread(this, *input,
2510 inHwDev, inputStream,
2511 primaryOutputDevice_l(), devices, mSystemReady);
2512 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002513 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2514 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002515 return thread;
2516 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002517 // Start record thread
2518 // RecordThread requires both input and output device indication to forward to audio
2519 // pre processing modules
2520 sp<RecordThread> thread = new RecordThread(this,
2521 inputStream,
2522 *input,
2523 primaryOutputDevice_l(),
2524 devices,
2525 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002526 );
2527 mRecordThreads.add(*input, thread);
2528 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2529 return thread;
2530 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 }
2532
Eric Laurentcf2c0212014-07-25 16:20:43 -07002533 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 return 0;
2535}
2536
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002537status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538{
Glenn Kastend96c5722012-04-25 13:44:49 -07002539 return closeInput_nonvirtual(input);
2540}
2541
2542status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2543{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 // keep strong reference on the record thread so that
2545 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002546 sp<RecordThread> recordThread;
2547 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 {
2549 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002550 recordThread = checkRecordThread_l(input);
2551 if (recordThread != 0) {
2552 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553
Andy Hungdc099c22018-09-18 13:46:39 -07002554 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002555
Eric Laurent6acd1d42017-01-04 14:23:29 -08002556 // If we still have effect chains, it means that a client still holds a handle
2557 // on at least one effect. We must either move the chain to an existing thread with the
2558 // same session ID or put it aside in case a new record thread is opened for a
2559 // new capture on the same session
2560 sp<EffectChain> chain;
2561 {
2562 Mutex::Autolock _sl(recordThread->mLock);
2563 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2564 // Note: maximum one chain per record thread
2565 if (effectChains.size() != 0) {
2566 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002567 }
2568 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002569 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002570 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002571 // This should only happen in case of overlap between one thread tear down and the
2572 // creation of its replacement
2573 size_t i;
2574 for (i = 0; i < mRecordThreads.size(); i++) {
2575 sp<RecordThread> t = mRecordThreads.valueAt(i);
2576 if (t == recordThread) {
2577 continue;
2578 }
2579 if (t->hasAudioSession(chain->sessionId()) != 0) {
2580 Mutex::Autolock _l(t->mLock);
2581 ALOGV("closeInput() found thread %d for effect session %d",
2582 t->id(), chain->sessionId());
2583 t->addEffectChain_l(chain);
2584 break;
2585 }
2586 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002587 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002588 if (i == mRecordThreads.size()) {
2589 putOrphanEffectChain_l(chain);
2590 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002591 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002592 mRecordThreads.removeItem(input);
2593 } else {
2594 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2595 if (mmapThread == 0) {
2596 return BAD_VALUE;
2597 }
Andy Hungdc099c22018-09-18 13:46:39 -07002598 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002599 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002600 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002601 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2602 ioDesc->mIoHandle = input;
2603 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 }
Eric Laurent83b88082014-06-20 18:31:16 -07002605 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2606 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002607 if (recordThread != 0) {
2608 closeInputFinish(recordThread);
2609 } else if (mmapThread != 0) {
2610 mmapThread->exit();
2611 AudioStreamIn *in = mmapThread->clearInput();
2612 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2613 // from now on thread->mInput is NULL
2614 delete in;
2615 }
Eric Laurent83b88082014-06-20 18:31:16 -07002616 return NO_ERROR;
2617}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002619void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002620{
2621 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002622 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002623 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002624 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002625 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002626}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002628void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002629{
2630 mRecordThreads.removeItem(thread->mId);
2631 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632}
2633
Glenn Kastend2304db2014-02-03 07:40:31 -08002634status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635{
2636 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002637 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638
2639 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2640 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002641 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002642 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002643 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2644 mMmapThreads[i]->invalidateTracks(stream);
2645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 return NO_ERROR;
2647}
2648
2649
Glenn Kasteneeecb982016-02-26 10:44:04 -08002650audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651{
Glenn Kasten9d003132016-04-06 14:38:09 -07002652 // This is a binder API, so a malicious client could pass in a bad parameter.
2653 // Check for that before calling the internal API nextUniqueId().
2654 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2655 ALOGE("newAudioUniqueId invalid use %d", use);
2656 return AUDIO_UNIQUE_ID_ALLOCATE;
2657 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002658 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659}
2660
Glenn Kastend848eb42016-03-08 13:42:11 -08002661void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002662{
2663 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002664 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002665 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002666 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2667 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002668 caller = pid;
2669 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002670
Eric Laurent021cf962014-05-13 10:18:14 -07002671 {
2672 Mutex::Autolock _cl(mClientLock);
2673 // Ignore requests received from processes not known as notification client. The request
2674 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2675 // called from a different pid leaving a stale session reference. Also we don't know how
2676 // to clear this reference if the client process dies.
2677 if (mNotificationClients.indexOfKey(caller) < 0) {
2678 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2679 return;
2680 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002681 }
2682
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002683 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002684 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002685 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002686 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2687 ref->mCnt++;
2688 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002689 return;
2690 }
2691 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002692 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2693 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002694}
2695
Glenn Kastend848eb42016-03-08 13:42:11 -08002696void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002697{
2698 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002699 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002700 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002701 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2702 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002703 caller = pid;
2704 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002705 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002706 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002707 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002708 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2709 ref->mCnt--;
2710 ALOGV(" decremented refcount to %d", ref->mCnt);
2711 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002712 mAudioSessionRefs.removeAt(i);
2713 delete ref;
2714 purgeStaleEffects_l();
2715 }
2716 return;
2717 }
2718 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002719 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002720 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002721 ALOGW_IF(!isAudioServerUid(callerUid),
2722 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002723}
2724
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002725bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2726{
2727 size_t num = mAudioSessionRefs.size();
2728 for (size_t i = 0; i < num; i++) {
2729 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2730 if (ref->mSessionid == audioSession) {
2731 return true;
2732 }
2733 }
2734 return false;
2735}
2736
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002737void AudioFlinger::purgeStaleEffects_l() {
2738
Steve Block3856b092011-10-20 11:56:00 +01002739 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002740
2741 Vector< sp<EffectChain> > chains;
2742
2743 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2744 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002745 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002746 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2747 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002748 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2749 chains.push(ec);
2750 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002751 }
2752 }
2753 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2754 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002755 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002756 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2757 sp<EffectChain> ec = t->mEffectChains[j];
2758 chains.push(ec);
2759 }
2760 }
2761
2762 for (size_t i = 0; i < chains.size(); i++) {
2763 sp<EffectChain> ec = chains[i];
2764 int sessionid = ec->sessionId();
2765 sp<ThreadBase> t = ec->mThread.promote();
2766 if (t == 0) {
2767 continue;
2768 }
2769 size_t numsessionrefs = mAudioSessionRefs.size();
2770 bool found = false;
2771 for (size_t k = 0; k < numsessionrefs; k++) {
2772 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002773 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002774 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002775 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002776 found = true;
2777 break;
2778 }
2779 }
2780 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002781 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002782 // remove all effects from the chain
2783 while (ec->mEffects.size()) {
2784 sp<EffectModule> effect = ec->mEffects[0];
2785 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002786 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002787 if (effect->purgeHandles()) {
2788 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002789 }
2790 AudioSystem::unregisterEffect(effect->id());
2791 }
2792 }
2793 }
2794 return;
2795}
2796
Andy Hungdc099c22018-09-18 13:46:39 -07002797// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2798void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2799{
2800 audio_utils::FdToString fdToString;
2801 const int fd = fdToString.fd();
2802 if (fd >= 0) {
2803 thread->dump(fd, {} /* args */);
2804 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2805 }
2806}
2807
Glenn Kasteneeecb982016-02-26 10:44:04 -08002808// checkThread_l() must be called with AudioFlinger::mLock held
2809AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2810{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002811 ThreadBase *thread = checkMmapThread_l(ioHandle);
2812 if (thread == 0) {
2813 switch (audio_unique_id_get_use(ioHandle)) {
2814 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2815 thread = checkPlaybackThread_l(ioHandle);
2816 break;
2817 case AUDIO_UNIQUE_ID_USE_INPUT:
2818 thread = checkRecordThread_l(ioHandle);
2819 break;
2820 default:
2821 break;
2822 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002823 }
2824 return thread;
2825}
2826
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002828AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829{
Glenn Kastena1117922012-01-26 10:53:32 -08002830 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831}
2832
2833// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002834AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835{
2836 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002837 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838}
2839
2840// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002841AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842{
Glenn Kastena1117922012-01-26 10:53:32 -08002843 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844}
2845
Eric Laurent6acd1d42017-01-04 14:23:29 -08002846// checkMmapThread_l() must be called with AudioFlinger::mLock held
2847AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2848{
2849 return mMmapThreads.valueFor(io).get();
2850}
2851
2852
2853// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2854AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2855{
Eric Laurent7459b902017-04-19 18:10:41 -07002856 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002857 if (volumeInterface == nullptr) {
2858 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2859 if (mmapThread != nullptr) {
2860 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002861 MmapPlaybackThread *mmapPlaybackThread =
2862 static_cast<MmapPlaybackThread *>(mmapThread);
2863 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002864 }
2865 }
2866 }
2867 return volumeInterface;
2868}
2869
2870Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2871{
2872 Vector <VolumeInterface *> volumeInterfaces;
2873 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002874 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002875 }
2876 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2877 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002878 MmapPlaybackThread *mmapPlaybackThread =
2879 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2880 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002881 }
2882 }
2883 return volumeInterfaces;
2884}
2885
Glenn Kasteneeecb982016-02-26 10:44:04 -08002886audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002887{
Glenn Kasten9d003132016-04-06 14:38:09 -07002888 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002889 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002890 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2891 for (int retry = 0; retry < maxRetries; retry++) {
2892 // The cast allows wraparound from max positive to min negative instead of abort
2893 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2894 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2895 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2896 // allow wrap by skipping 0 and -1 for session ids
2897 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2898 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2899 return (audio_unique_id_t) (base | use);
2900 }
2901 }
2902 // We have no way of recovering from wraparound
2903 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2904 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905}
2906
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002907AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002908{
2909 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2910 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002911 if(thread->isDuplicating()) {
2912 continue;
2913 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002914 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002915 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002916 return thread;
2917 }
2918 }
2919 return NULL;
2920}
2921
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002922audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002923{
2924 PlaybackThread *thread = primaryPlaybackThread_l();
2925
2926 if (thread == NULL) {
2927 return 0;
2928 }
2929
Eric Laurentf1c04f92012-08-28 14:26:53 -07002930 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002931}
2932
Glenn Kastena7335632016-06-09 17:09:53 -07002933AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2934{
2935 size_t minFrameCount = 0;
2936 PlaybackThread *minThread = NULL;
2937 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2938 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2939 if (!thread->isDuplicating()) {
2940 size_t frameCount = thread->frameCountHAL();
2941 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2942 (frameCount == minFrameCount && thread->hasFastMixer() &&
2943 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2944 minFrameCount = frameCount;
2945 minThread = thread;
2946 }
2947 }
2948 }
2949 return minThread;
2950}
2951
Eric Laurenta011e352012-03-29 15:51:43 -07002952sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002953 audio_session_t triggerSession,
2954 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002955 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002956 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002957{
2958 Mutex::Autolock _l(mLock);
2959
2960 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2961 status_t playStatus = NAME_NOT_FOUND;
2962 status_t recStatus = NAME_NOT_FOUND;
2963 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2964 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2965 if (playStatus == NO_ERROR) {
2966 return event;
2967 }
2968 }
2969 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2970 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2971 if (recStatus == NO_ERROR) {
2972 return event;
2973 }
2974 }
2975 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2976 mPendingSyncEvents.add(event);
2977 } else {
2978 ALOGV("createSyncEvent() invalid event %d", event->type());
2979 event.clear();
2980 }
2981 return event;
2982}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002983
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984// ----------------------------------------------------------------------------
2985// Effect management
2986// ----------------------------------------------------------------------------
2987
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002988sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2989 return mEffectsFactoryHal;
2990}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991
Glenn Kastenf587ba52012-01-26 16:25:10 -08002992status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993{
2994 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002995 if (mEffectsFactoryHal.get()) {
2996 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2997 } else {
2998 return -ENODEV;
2999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000}
3001
Glenn Kastenf587ba52012-01-26 16:25:10 -08003002status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003{
3004 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003005 if (mEffectsFactoryHal.get()) {
3006 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3007 } else {
3008 return -ENODEV;
3009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010}
3011
Glenn Kasten5e92a782012-01-30 07:40:52 -08003012status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003013 const effect_uuid_t *pTypeUuid,
3014 uint32_t preferredTypeFlag,
3015 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003017 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3018 return BAD_VALUE;
3019 }
3020
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003022
3023 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003024 return -ENODEV;
3025 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003027 status_t status = NO_ERROR;
3028 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3029 // If uuid is specified, request effect descriptor from that.
3030 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3031 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3032 // If uuid is not specified, look for an available implementation
3033 // of the required type instead.
3034
3035 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3036 effect_descriptor_t desc;
3037 desc.flags = 0; // prevent compiler warning
3038
3039 uint32_t numEffects = 0;
3040 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3041 if (status < 0) {
3042 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3043 return status;
3044 }
3045
3046 bool found = false;
3047 for (uint32_t i = 0; i < numEffects; i++) {
3048 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3049 if (status < 0) {
3050 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3051 continue;
3052 }
3053 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3054 // If matching type found save effect descriptor.
3055 found = true;
3056 *descriptor = desc;
3057
3058 // If there's no preferred flag or this descriptor matches the preferred
3059 // flag, success! If this descriptor doesn't match the preferred
3060 // flag, continue enumeration in case a better matching version of this
3061 // effect type is available. Note that this means if no effect with a
3062 // correct flag is found, the descriptor returned will correspond to the
3063 // last effect that at least had a matching type uuid (if any).
3064 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3065 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3066 break;
3067 }
3068 }
3069 }
3070
3071 if (!found) {
3072 status = NAME_NOT_FOUND;
3073 ALOGW("getEffectDescriptor(): Effect not found by type.");
3074 }
3075 } else {
3076 status = BAD_VALUE;
3077 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3078 }
3079 return status;
3080}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003082sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 effect_descriptor_t *pDesc,
3084 const sp<IEffectClient>& effectClient,
3085 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003086 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003087 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003088 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003089 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 status_t *status,
3091 int *id,
3092 int *enabled)
3093{
3094 status_t lStatus = NO_ERROR;
3095 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097
Eric Laurentb6436272016-12-07 19:24:50 -08003098 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003099 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003100 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3101 ALOGW_IF(pid != -1 && pid != callingPid,
3102 "%s uid %d pid %d tried to pass itself off as pid %d",
3103 __func__, callingUid, callingPid, pid);
3104 pid = callingPid;
3105 }
3106
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003107 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3108 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109
3110 if (pDesc == NULL) {
3111 lStatus = BAD_VALUE;
3112 goto Exit;
3113 }
3114
Eric Laurent84e9a102010-09-23 16:10:16 -07003115 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003116 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003117 lStatus = PERMISSION_DENIED;
3118 goto Exit;
3119 }
3120
Dima Zavinfce7a472011-04-19 22:30:36 -07003121 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003122 // that can only be created by audio policy manager
3123 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003124 lStatus = PERMISSION_DENIED;
3125 goto Exit;
3126 }
3127
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003128 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003129 lStatus = NO_INIT;
3130 goto Exit;
3131 }
3132
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003134 // Get the full effect descriptor from the uuid/type.
3135 // If the session is the output mix, prefer an auxiliary effect,
3136 // otherwise no preference.
3137 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3138 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3139 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3140 if (lStatus < 0) {
3141 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3142 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 }
3144
3145 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003146 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3148 lStatus = INVALID_OPERATION;
3149 goto Exit;
3150 }
3151
Eric Laurent59255e42011-07-27 19:49:51 -07003152 // check recording permission for visualizer
3153 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003154 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003155 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003156 lStatus = PERMISSION_DENIED;
3157 goto Exit;
3158 }
3159
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003161 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003162 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003163 // if the output returned by getOutputForEffect() is removed before we lock the
3164 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3165 // and we will exit safely
3166 io = AudioSystem::getOutputForEffect(&desc);
3167 ALOGV("createEffect got output %d", io);
3168 }
3169
3170 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171
3172 // If output is not specified try to find a matching audio session ID in one of the
3173 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003174 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3175 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003176 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003177 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003178 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3179 // output must be specified by AudioPolicyManager when using session
3180 // AUDIO_SESSION_OUTPUT_STAGE
3181 lStatus = BAD_VALUE;
3182 goto Exit;
3183 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003184 // look for the thread where the specified audio session is present
3185 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3186 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3187 io = mPlaybackThreads.keyAt(i);
3188 break;
3189 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003191 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003192 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3193 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3194 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003195 break;
3196 }
3197 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003198 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003199 if (io == AUDIO_IO_HANDLE_NONE) {
3200 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3201 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3202 io = mMmapThreads.keyAt(i);
3203 break;
3204 }
3205 }
3206 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003207 // If no output thread contains the requested session ID, default to
3208 // first output. The effect chain will be moved to the correct output
3209 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003210 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003211 io = mPlaybackThreads.keyAt(0);
3212 }
Steve Block3856b092011-10-20 11:56:00 +01003213 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003214 }
3215 ThreadBase *thread = checkRecordThread_l(io);
3216 if (thread == NULL) {
3217 thread = checkPlaybackThread_l(io);
3218 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003219 thread = checkMmapThread_l(io);
3220 if (thread == NULL) {
3221 ALOGE("createEffect() unknown output thread");
3222 lStatus = BAD_VALUE;
3223 goto Exit;
3224 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003225 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003226 } else {
3227 // Check if one effect chain was awaiting for an effect to be created on this
3228 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003229 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003230 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003231 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003232 thread->addEffectChain_l(chain);
3233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003235
Eric Laurent021cf962014-05-13 10:18:14 -07003236 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003238 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003239 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003240 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003241 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003242 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003243 // remove local strong reference to Client with mClientLock held
3244 Mutex::Autolock _cl(mClientLock);
3245 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003246 } else {
3247 // handle must be valid here, but check again to be safe.
3248 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 }
3251
haobo101735295ff7b0d2017-03-17 17:44:03 +08003252 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3253 // handle must be cleared outside lock.
3254 handle.clear();
3255 }
3256
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003258 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 return handle;
3260}
3261
Glenn Kastend848eb42016-03-08 13:42:11 -08003262status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003263 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003264{
Steve Block3856b092011-10-20 11:56:00 +01003265 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003266 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003267 Mutex::Autolock _l(mLock);
3268 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003269 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003270 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 }
Eric Laurentde070132010-07-13 04:45:46 -07003272 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3273 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003274 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003275 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 }
Eric Laurentde070132010-07-13 04:45:46 -07003277 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3278 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003279 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003280 return BAD_VALUE;
3281 }
3282
3283 Mutex::Autolock _dl(dstThread->mLock);
3284 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003285 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286}
3287
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003288// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003289status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003290 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003291 AudioFlinger::PlaybackThread *dstThread,
3292 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003293{
Steve Block3856b092011-10-20 11:56:00 +01003294 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003295 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003296
Eric Laurent59255e42011-07-27 19:49:51 -07003297 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003298 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003299 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003300 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003301 return INVALID_OPERATION;
3302 }
3303
Eric Laurent4c415062016-06-17 16:14:16 -07003304 // Check whether the destination thread and all effects in the chain are compatible
3305 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003306 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003307 " destination thread %p is not compatible with effects in the chain",
3308 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003309 return INVALID_OPERATION;
3310 }
3311
Eric Laurent39e94f82010-07-28 01:32:47 -07003312 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003313 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003314 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003315 // removed.
3316 srcThread->removeEffectChain_l(chain);
3317
3318 // transfer all effects one by one so that new effect chain is created on new thread with
3319 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003320 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003321 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003322 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003323 Vector< sp<EffectModule> > removed;
3324 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003325 while (effect != 0) {
3326 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003327 removed.add(effect);
3328 status = dstThread->addEffect_l(effect);
3329 if (status != NO_ERROR) {
3330 break;
3331 }
Eric Laurentec35a142011-10-05 17:42:25 -07003332 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3333 if (effect->state() == EffectModule::ACTIVE ||
3334 effect->state() == EffectModule::STOPPING) {
3335 effect->start();
3336 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003337 // if the move request is not received from audio policy manager, the effect must be
3338 // re-registered with the new strategy and output
3339 if (dstChain == 0) {
3340 dstChain = effect->chain().promote();
3341 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003342 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003343 status = NO_INIT;
3344 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003345 }
3346 strategy = dstChain->strategy();
3347 }
3348 if (reRegister) {
3349 AudioSystem::unregisterEffect(effect->id());
3350 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003351 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003352 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003353 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003354 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003355 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003356 }
Eric Laurentde070132010-07-13 04:45:46 -07003357 effect = chain->getEffectFromId_l(0);
3358 }
3359
Eric Laurent5baf2af2013-09-12 17:37:00 -07003360 if (status != NO_ERROR) {
3361 for (size_t i = 0; i < removed.size(); i++) {
3362 srcThread->addEffect_l(removed[i]);
3363 if (dstChain != 0 && reRegister) {
3364 AudioSystem::unregisterEffect(removed[i]->id());
3365 AudioSystem::registerEffect(&removed[i]->desc(),
3366 srcThread->id(),
3367 strategy,
3368 sessionId,
3369 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003370 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003371 }
3372 }
3373 }
3374
3375 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376}
3377
Eric Laurent5baf2af2013-09-12 17:37:00 -07003378bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003379{
3380 if (mGlobalEffectEnableTime != 0 &&
3381 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3382 return true;
3383 }
3384
3385 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3386 sp<EffectChain> ec =
3387 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003388 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003389 return true;
3390 }
3391 }
3392 return false;
3393}
3394
Eric Laurent5baf2af2013-09-12 17:37:00 -07003395void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003396{
3397 Mutex::Autolock _l(mLock);
3398
3399 mGlobalEffectEnableTime = systemTime();
3400
3401 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3402 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3403 if (t->mType == ThreadBase::OFFLOAD) {
3404 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3405 }
3406 }
3407
3408}
3409
Eric Laurentaaa44472014-09-12 17:41:50 -07003410status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3411{
Eric Laurentd8365c52017-07-16 15:27:05 -07003412 // clear possible suspended state before parking the chain so that it starts in default state
3413 // when attached to a new record thread
3414 chain->setEffectSuspended_l(FX_IID_AEC, false);
3415 chain->setEffectSuspended_l(FX_IID_NS, false);
3416
Glenn Kastend848eb42016-03-08 13:42:11 -08003417 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003418 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003419 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003420 if (index >= 0) {
3421 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3422 return ALREADY_EXISTS;
3423 }
3424 mOrphanEffectChains.add(session, chain);
3425 return NO_ERROR;
3426}
3427
3428sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3429{
3430 sp<EffectChain> chain;
3431 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003432 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003433 if (index >= 0) {
3434 chain = mOrphanEffectChains.valueAt(index);
3435 mOrphanEffectChains.removeItemsAt(index);
3436 }
3437 return chain;
3438}
3439
3440bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3441{
3442 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003443 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003444 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003445 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003446 if (index >= 0) {
3447 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003448 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003449 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003450 mOrphanEffectChains.removeItemsAt(index);
3451 }
3452 return true;
3453 }
3454 return false;
3455}
3456
3457
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458// ----------------------------------------------------------------------------
3459
3460status_t AudioFlinger::onTransact(
3461 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3462{
3463 return BnAudioFlinger::onTransact(code, data, reply, flags);
3464}
3465
Glenn Kasten63238ef2015-03-02 15:50:29 -08003466} // namespace android