blob: 9234364248c241ab3310404fb06a8fcef38a6cb4 [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"
Eric Tan7b651152018-07-13 10:17:19 -070023#include <algorithm> // std::any_of
Glenn Kastenda6ef132013-01-10 12:31:01 -080024#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include <math.h>
26#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070027#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/time.h>
29#include <sys/resource.h>
30
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070036#include <media/audiohal/DeviceHalInterface.h>
37#include <media/audiohal/DevicesFactoryHalInterface.h>
38#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070039#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070041#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <utils/String16.h>
43#include <utils/threads.h>
44
Steven Morelandf0c02ce2018-02-23 14:53:55 -080045#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/properties.h>
47
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070051#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Andy Hung6770c6f2015-04-07 13:43:36 -070053#include <media/AudioResamplerPublic.h>
54
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_visualizer.h>
56#include <system/audio_effects/effect_ns.h>
57#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070067#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070069#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070070#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080071
rago3bd1c872016-09-26 12:58:14 -070072//#define BUFLOG_NDEBUG 0
73#include <BufLog.h>
74
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080075#include "TypedLogger.h"
76
Mathias Agopian65ab4712010-07-14 17:59:35 -070077// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
John Grossman1c345192012-03-27 14:00:17 -070079// Note: the following macro is used for extremely verbose logging message. In
80// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
81// 0; but one side effect of this is to turn all LOGV's as well. Some messages
82// are so verbose that we want to suppress them even when we have ALOG_ASSERT
83// turned on. Do not uncomment the #def below unless you really know what you
84// are doing and want to see all of the extremely verbose messages.
85//#define VERY_VERY_VERBOSE_LOGGING
86#ifdef VERY_VERY_VERBOSE_LOGGING
87#define ALOGVV ALOGV
88#else
89#define ALOGVV(a...) do { } while(0)
90#endif
Eric Laurentde070132010-07-13 04:45:46 -070091
Mathias Agopian65ab4712010-07-14 17:59:35 -070092namespace android {
93
Glenn Kastenec1d6b52011-12-12 09:04:45 -080094static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
95static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070096static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070097static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070098
Glenn Kasten58912562012-04-03 10:45:00 -070099
John Grossman4ff14ba2012-02-08 16:37:41 -0800100nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700103
Eric Laurent813e2a72013-08-31 12:59:48 -0700104// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
105// we define a minimum time during which a global effect is considered enabled.
106static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
107
Eric Laurentfc235202016-12-20 18:48:17 -0800108Mutex gLock;
109wp<AudioFlinger> gAudioFlinger;
110
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700111// Keep a strong reference to media.log service around forever.
112// The service is within our parent process so it can never die in a way that we could observe.
113// These two variables are const after initialization.
114static sp<IBinder> sMediaLogServiceAsBinder;
115static sp<IMediaLogService> sMediaLogService;
116
117static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
118
119static void sMediaLogInit()
120{
121 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
122 if (sMediaLogServiceAsBinder != 0) {
123 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
124 }
125}
126
Mathias Agopian65ab4712010-07-14 17:59:35 -0700127// ----------------------------------------------------------------------------
128
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700129std::string formatToString(audio_format_t format) {
130 std::string result;
131 FormatConverter::toString(format, result);
132 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800133}
134
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135// ----------------------------------------------------------------------------
136
137AudioFlinger::AudioFlinger()
138 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800139 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800140 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800141 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700142 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800143 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800144 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700145 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800146 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700147 mBtNrecIsOff(false),
148 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700149 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800150 mTotalMemory(0),
151 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700152 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700153 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700154 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700156 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
157 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
158 // zero ID has a special meaning, so unavailable
159 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
160 }
161
Glenn Kastenae0cff12016-02-24 13:57:49 -0800162 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800163 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800164 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
165 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700166 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800167 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700168
Wei Jia3f273d12015-11-24 09:06:49 -0800169 // reset battery stats.
170 // if the audio service has crashed, battery stats could be left
171 // in bad state, reset the state upon service start.
172 BatteryNotifier::getInstance().noteResetAudio();
173
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700174 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700175 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
176
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800177 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700178}
179
180void AudioFlinger::onFirstRef()
181{
Eric Laurent93575202011-01-18 18:39:02 -0800182 Mutex::Autolock _l(mLock);
183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800185 char val_str[PROPERTY_VALUE_MAX] = { 0 };
186 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
187 uint32_t int_val;
188 if (1 == sscanf(val_str, "%u", &int_val)) {
189 mStandbyTimeInNsecs = milliseconds(int_val);
190 ALOGI("Using %u mSec as standby time.", int_val);
191 } else {
192 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
193 ALOGI("Using default %u mSec as standby time.",
194 (uint32_t)(mStandbyTimeInNsecs / 1000000));
195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
Eric Laurenta4c5a552012-03-29 10:12:40 -0700198 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800199
200 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201}
202
203AudioFlinger::~AudioFlinger()
204{
205 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700206 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700207 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208 }
209 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700210 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700211 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700213
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800214 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
215 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700216 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700218
219 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700220 if (sMediaLogService != 0) {
221 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
222 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
223 mUnregisteredWriters.pop();
224 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700225 }
226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227}
228
Eric Laurentfc235202016-12-20 18:48:17 -0800229//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800230__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800231status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
232 const audio_attributes_t *attr,
233 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700234 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800235 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800236 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800237 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700238 sp<MmapStreamInterface>& interface,
239 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800240{
241 sp<AudioFlinger> af;
242 {
243 Mutex::Autolock _l(gLock);
244 af = gAudioFlinger.promote();
245 }
246 status_t ret = NO_INIT;
247 if (af != 0) {
248 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800249 direction, attr, config, client, deviceId,
250 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800251 }
252 return ret;
253}
254
Eric Laurent6acd1d42017-01-04 14:23:29 -0800255status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
256 const audio_attributes_t *attr,
257 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700258 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800259 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800260 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800261 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700262 sp<MmapStreamInterface>& interface,
263 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800264{
265 status_t ret = initCheck();
266 if (ret != NO_ERROR) {
267 return ret;
268 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800269 audio_session_t actualSessionId = *sessionId;
270 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
271 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
272 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800273 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700274 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800275 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
276 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
277 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
278 fullConfig.sample_rate = config->sample_rate;
279 fullConfig.channel_mask = config->channel_mask;
280 fullConfig.format = config->format;
281 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800282 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200283 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800284 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800285 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
286 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700287 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800288 } else {
289 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800290 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800291 client.clientPid,
292 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800293 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800294 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700295 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800296 }
297 if (ret != NO_ERROR) {
298 return ret;
299 }
300
301 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
302 // audio policy manager and we can retrieve it
303 sp<MmapThread> thread = mMmapThreads.valueFor(io);
304 if (thread != 0) {
305 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800306 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700307 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800308 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800309 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700310 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700311 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700312 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800313 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700314 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800315 ret = NO_INIT;
316 }
317
318 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
319
Eric Laurentfc235202016-12-20 18:48:17 -0800320 return ret;
321}
322
Eric Laurenta4c5a552012-03-29 10:12:40 -0700323static const char * const audio_interfaces[] = {
324 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
325 AUDIO_HARDWARE_MODULE_ID_A2DP,
326 AUDIO_HARDWARE_MODULE_ID_USB,
327};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700328
Phil Burk062e67a2015-02-11 13:40:50 -0800329AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700330 audio_module_handle_t module,
331 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700332{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700333 // if module is 0, the request comes from an old policy manager and we should load
334 // well known modules
335 if (module == 0) {
336 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700337 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700338 loadHwModule_l(audio_interfaces[i]);
339 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700340 // then try to find a module supporting the requested device.
341 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
342 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700343 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
344 uint32_t supportedDevices;
345 if (dev->getSupportedDevices(&supportedDevices) == OK &&
346 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700347 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700348 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700349 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700350 } else {
351 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700352 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
353 if (audioHwDevice != NULL) {
354 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355 }
356 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700357
Dima Zavin799a70e2011-04-18 16:57:27 -0700358 return NULL;
359}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360
Glenn Kasten0f11b512014-01-31 16:18:54 -0800361void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362{
363 const size_t SIZE = 256;
364 char buffer[SIZE];
365 String8 result;
366
367 result.append("Clients:\n");
368 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800369 sp<Client> client = mClients.valueAt(i).promote();
370 if (client != 0) {
371 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
372 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 }
374 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700375
Eric Laurentd1b28d42013-09-18 18:47:13 -0700376 result.append("Notification Clients:\n");
377 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
378 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
379 result.append(buffer);
380 }
381
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700382 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800383 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700384 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
385 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800386 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700387 result.append(buffer);
388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700389 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390}
391
392
Glenn Kasten0f11b512014-01-31 16:18:54 -0800393void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700394{
395 const size_t SIZE = 256;
396 char buffer[SIZE];
397 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800398 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399
John Grossman4ff14ba2012-02-08 16:37:41 -0800400 snprintf(buffer, SIZE, "Hardware status: %d\n"
401 "Standby Time mSec: %u\n",
402 hardwareStatus,
403 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 result.append(buffer);
405 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406}
407
Glenn Kasten0f11b512014-01-31 16:18:54 -0800408void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
412 String8 result;
413 snprintf(buffer, SIZE, "Permission Denial: "
414 "can't dump AudioFlinger from pid=%d, uid=%d\n",
415 IPCThreadState::self()->getCallingPid(),
416 IPCThreadState::self()->getCallingUid());
417 result.append(buffer);
418 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419}
420
Eric Laurent81784c32012-11-19 14:55:58 -0800421bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422{
423 bool locked = false;
424 for (int i = 0; i < kDumpLockRetries; ++i) {
425 if (mutex.tryLock() == NO_ERROR) {
426 locked = true;
427 break;
428 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800429 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700430 }
431 return locked;
432}
433
434status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
435{
Glenn Kasten44deb052012-02-05 18:09:08 -0800436 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 dumpPermissionDenial(fd, args);
438 } else {
Eric Tan7b651152018-07-13 10:17:19 -0700439 // XXX This is sort of hacky for now.
440 const bool formatJson = std::any_of(args.begin(), args.end(),
441 [](const String16 &arg) { return arg == String16("--json"); });
442 if (formatJson) {
443 // XXX consider buffering if the string happens to be too long.
444 dprintf(fd, "%s", getJsonString().c_str());
445 return NO_ERROR;
446 }
447
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800449 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 if (!hardwareLocked) {
451 String8 result(kHardwareLockedString);
452 write(fd, result.string(), result.size());
453 } else {
454 mHardwareLock.unlock();
455 }
456
Eric Tan7b651152018-07-13 10:17:19 -0700457 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458
459 // failed to lock - AudioFlinger is probably deadlocked
460 if (!locked) {
461 String8 result(kDeadlockedString);
462 write(fd, result.string(), result.size());
463 }
464
Eric Laurent021cf962014-05-13 10:18:14 -0700465 bool clientLocked = dumpTryLock(mClientLock);
466 if (!clientLocked) {
467 String8 result(kClientLockedString);
468 write(fd, result.string(), result.size());
469 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700470
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700471 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700472 mEffectsFactoryHal->dumpEffects(fd);
473 } else {
474 String8 result(kNoEffectsFactory);
475 write(fd, result.string(), result.size());
476 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700477
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700479 if (clientLocked) {
480 mClientLock.unlock();
481 }
482
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 dumpInternals(fd, args);
484
485 // dump playback threads
486 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
487 mPlaybackThreads.valueAt(i)->dump(fd, args);
488 }
489
490 // dump record threads
491 for (size_t i = 0; i < mRecordThreads.size(); i++) {
492 mRecordThreads.valueAt(i)->dump(fd, args);
493 }
494
Eric Laurent6acd1d42017-01-04 14:23:29 -0800495 // dump mmap threads
496 for (size_t i = 0; i < mMmapThreads.size(); i++) {
497 mMmapThreads.valueAt(i)->dump(fd, args);
498 }
499
Eric Laurentaaa44472014-09-12 17:41:50 -0700500 // dump orphan effect chains
501 if (mOrphanEffectChains.size() != 0) {
502 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
503 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
504 mOrphanEffectChains.valueAt(i)->dump(fd, args);
505 }
506 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700507 // dump all hardware devs
508 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700509 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
510 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700512
Mikhail Naganov201369b2018-05-16 16:52:32 -0700513 mPatchPanel.dump(fd);
514
rago3bd1c872016-09-26 12:58:14 -0700515 BUFLOG_RESET;
516
Glenn Kastend65d73c2012-06-22 17:21:07 -0700517 if (locked) {
518 mLock.unlock();
519 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800520
Andy Hung8946a282018-04-19 20:04:56 -0700521#ifdef TEE_SINK
522 // NBAIO_Tee dump is safe to call outside of AF lock.
523 NBAIO_Tee::dumpAll(fd, "_DUMP");
524#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800525 // append a copy of media.log here by forwarding fd to it, but don't attempt
526 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700527 if (sMediaLogServiceAsBinder != 0) {
528 dprintf(fd, "\nmedia.log:\n");
529 Vector<String16> args;
530 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800531 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700532
533 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700534 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700535 bool unreachableMemory = false;
536 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700537 if (arg == String16("-m")) {
538 dumpMem = true;
539 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700540 unreachableMemory = true;
541 }
542 }
543
Andy Hung07b745e2016-05-23 16:21:07 -0700544 if (dumpMem) {
545 dprintf(fd, "\nDumping memory:\n");
546 std::string s = dumpMemoryAddresses(100 /* limit */);
547 write(fd, s.c_str(), s.size());
548 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700549 if (unreachableMemory) {
550 dprintf(fd, "\nDumping unreachable memory:\n");
551 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700552 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700553 write(fd, s.c_str(), s.size());
554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 }
556 return NO_ERROR;
557}
558
Eric Tan7b651152018-07-13 10:17:19 -0700559std::string AudioFlinger::getJsonString()
560{
561 std::string jsonStr = "{\n";
562 const bool locked = dumpTryLock(mLock);
563
564 // failed to lock - AudioFlinger is probably deadlocked
565 if (!locked) {
566 jsonStr += " \"deadlock_message\": ";
567 jsonStr += kDeadlockedString;
568 jsonStr += ",\n";
569 }
570 // FIXME risky to access data structures without a lock held?
571
572 jsonStr += " \"Playback_Threads\": [\n";
573 // dump playback threads
574 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
575 if (i != 0) {
576 jsonStr += ",\n";
577 }
578 jsonStr += mPlaybackThreads.valueAt(i)->getJsonString();
579 }
580 jsonStr += "\n ]\n}\n";
581
582 if (locked) {
583 mLock.unlock();
584 }
585
586 return jsonStr;
587}
588
Eric Laurent021cf962014-05-13 10:18:14 -0700589sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800590{
Eric Laurent021cf962014-05-13 10:18:14 -0700591 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800592 // If pid is already in the mClients wp<> map, then use that entry
593 // (for which promote() is always != 0), otherwise create a new entry and Client.
594 sp<Client> client = mClients.valueFor(pid).promote();
595 if (client == 0) {
596 client = new Client(this, pid);
597 mClients.add(pid, client);
598 }
599
600 return client;
601}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602
Glenn Kasten9e58b552013-01-18 15:09:48 -0800603sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
604{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700605 // If there is no memory allocated for logs, return a dummy writer that does nothing.
606 // Similarly if we can't contact the media.log service, also return a dummy writer.
607 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800608 return new NBLog::Writer();
609 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700610 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
611 // If allocation fails, consult the vector of previously unregistered writers
612 // and garbage-collect one or more them until an allocation succeeds
613 if (shared == 0) {
614 Mutex::Autolock _l(mUnregisteredWritersLock);
615 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
616 {
617 // Pick the oldest stale writer to garbage-collect
618 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
619 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700620 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700621 // Now the media.log remote reference to IMemory is gone. When our last local
622 // reference to IMemory also drops to zero at end of this block,
623 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
624 }
625 // Re-attempt the allocation
626 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
627 if (shared != 0) {
628 goto success;
629 }
630 }
631 // Even after garbage-collecting all old writers, there is still not enough memory,
632 // so return a dummy writer
633 return new NBLog::Writer();
634 }
635success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800636 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
637 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
638 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700639 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800640 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800641}
642
643void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
644{
Glenn Kasten685ef092013-02-04 08:15:34 -0800645 if (writer == 0) {
646 return;
647 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800648 sp<IMemory> iMemory(writer->getIMemory());
649 if (iMemory == 0) {
650 return;
651 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700652 // Rather than removing the writer immediately, append it to a queue of old writers to
653 // be garbage-collected later. This allows us to continue to view old logs for a while.
654 Mutex::Autolock _l(mUnregisteredWritersLock);
655 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800656}
657
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658// IAudioFlinger interface
659
Eric Laurent21da6472017-11-09 16:29:26 -0800660sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
661 CreateTrackOutput& output,
662 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663{
664 sp<PlaybackThread::Track> track;
665 sp<TrackHandle> trackHandle;
666 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800668 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800669 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670
Eric Laurent21da6472017-11-09 16:29:26 -0800671 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700672 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800673 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700674 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800675 ALOGW_IF(clientUid != callingUid,
676 "%s uid %d tried to pass itself off as %d",
677 __FUNCTION__, callingUid, clientUid);
678 clientUid = callingUid;
679 updatePid = true;
680 }
681 pid_t clientPid = input.clientInfo.clientPid;
682 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700683 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800684 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700685 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800686 __func__, callingUid, callingPid, clientPid);
687 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700688 }
689
Eric Laurent21da6472017-11-09 16:29:26 -0800690 audio_session_t sessionId = input.sessionId;
691 if (sessionId == AUDIO_SESSION_ALLOCATE) {
692 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800693 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
694 lStatus = BAD_VALUE;
695 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800696 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800697
Eric Laurent21da6472017-11-09 16:29:26 -0800698 output.sessionId = sessionId;
699 output.outputId = AUDIO_IO_HANDLE_NONE;
700 output.selectedDeviceId = input.selectedDeviceId;
701
702 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200703 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800704 &output.selectedDeviceId, &portId);
705
706 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
707 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
708 goto Exit;
709 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800710 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
711 // but if someone uses binder directly they could bypass that and cause us to crash
712 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000713 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714 lStatus = BAD_VALUE;
715 goto Exit;
716 }
717
Glenn Kasten53b5d092014-02-05 10:00:23 -0800718 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800719 if (!audio_is_output_channel(input.config.channel_mask)) {
720 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800721 lStatus = BAD_VALUE;
722 goto Exit;
723 }
724
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700725 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800726 if (!audio_is_valid_format(input.config.format)) {
727 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700728 lStatus = BAD_VALUE;
729 goto Exit;
730 }
731
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 {
733 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800734 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800736 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 lStatus = BAD_VALUE;
738 goto Exit;
739 }
740
Eric Laurent21da6472017-11-09 16:29:26 -0800741 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742
Glenn Kastene848bd92014-03-13 15:00:32 -0700743 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800744 // check if an effect chain with the same session ID is present on another
745 // output thread and move it here.
746 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
747 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
748 if (mPlaybackThreads.keyAt(i) != output.outputId) {
749 uint32_t sessions = t->hasAudioSession(sessionId);
750 if (sessions & ThreadBase::EFFECT_SESSION) {
751 effectThread = t.get();
752 break;
Eric Laurentde070132010-07-13 04:45:46 -0700753 }
754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 }
Eric Laurent21da6472017-11-09 16:29:26 -0800756 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757
Eric Laurent21da6472017-11-09 16:29:26 -0800758 output.sampleRate = input.config.sample_rate;
759 output.frameCount = input.frameCount;
760 output.notificationFrameCount = input.notificationFrameCount;
761 output.flags = input.flags;
762
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700763 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
764 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800765 &output.frameCount, &output.notificationFrameCount,
766 input.notificationsPerBuffer, input.speed,
767 input.sharedBuffer, sessionId, &output.flags,
768 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800769 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700770 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700771
Eric Laurent21da6472017-11-09 16:29:26 -0800772 output.afFrameCount = thread->frameCount();
773 output.afSampleRate = thread->sampleRate();
774 output.afLatencyMs = thread->latency();
775
Eric Laurent39e94f82010-07-28 01:32:47 -0700776 // move effect chain to this output thread if an effect on same session was waiting
777 // for a track to be created
778 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700779 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700780 Mutex::Autolock _dl(thread->mLock);
781 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800782 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700783 }
Eric Laurenta011e352012-03-29 15:51:43 -0700784
785 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700786 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800787 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700788 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700789 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700790 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700791 } else {
792 mPendingSyncEvents[i]->cancel();
793 }
Eric Laurenta011e352012-03-29 15:51:43 -0700794 mPendingSyncEvents.removeAt(i);
795 i--;
796 }
797 }
798 }
Glenn Kastene198c362013-08-13 09:13:36 -0700799
Eric Laurent21da6472017-11-09 16:29:26 -0800800 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 }
Glenn Kastene198c362013-08-13 09:13:36 -0700802
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700803 if (lStatus != NO_ERROR) {
804 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700805 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700806 // Don't hold mClientLock when releasing the reference on the track as the
807 // destructor will acquire it.
808 {
809 Mutex::Autolock _cl(mClientLock);
810 client.clear();
811 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700813 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 }
815
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700816 // return handle to client
817 trackHandle = new TrackHandle(track);
818
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800820 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700821 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800822 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700823 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824 return trackHandle;
825}
826
Glenn Kasten2c073da2016-02-26 09:14:08 -0800827uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828{
829 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800830 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800832 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return 0;
834 }
835 return thread->sampleRate();
836}
837
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800838audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839{
840 Mutex::Autolock _l(mLock);
841 PlaybackThread *thread = checkPlaybackThread_l(output);
842 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000843 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800844 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 }
846 return thread->format();
847}
848
Glenn Kasten2c073da2016-02-26 09:14:08 -0800849size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850{
851 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800852 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800854 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855 return 0;
856 }
Glenn Kasten58912562012-04-03 10:45:00 -0700857 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
858 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859 return thread->frameCount();
860}
861
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700862size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
863{
864 Mutex::Autolock _l(mLock);
865 ThreadBase *thread = checkThread_l(ioHandle);
866 if (thread == NULL) {
867 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
868 return 0;
869 }
870 return thread->frameCountHAL();
871}
872
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800873uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700874{
875 Mutex::Autolock _l(mLock);
876 PlaybackThread *thread = checkPlaybackThread_l(output);
877 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800878 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700879 return 0;
880 }
881 return thread->latency();
882}
883
884status_t AudioFlinger::setMasterVolume(float value)
885{
Eric Laurenta1884f92011-08-23 08:25:03 -0700886 status_t ret = initCheck();
887 if (ret != NO_ERROR) {
888 return ret;
889 }
890
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 // check calling permissions
892 if (!settingsAllowed()) {
893 return PERMISSION_DENIED;
894 }
895
Eric Laurenta4c5a552012-03-29 10:12:40 -0700896 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700897 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700898
John Grossmanee578c02012-07-23 17:05:46 -0700899 // Set master volume in the HALs which support it.
900 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
901 AutoMutex lock(mHardwareLock);
902 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800903
John Grossmanee578c02012-07-23 17:05:46 -0700904 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
905 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700906 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800907 }
John Grossmanee578c02012-07-23 17:05:46 -0700908 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700910
John Grossmanee578c02012-07-23 17:05:46 -0700911 // Now set the master volume in each playback thread. Playback threads
912 // assigned to HALs which do not have master volume support will apply
913 // master volume during the mix operation. Threads with HALs which do
914 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700915 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
916 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
917 continue;
918 }
John Grossmanee578c02012-07-23 17:05:46 -0700919 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700920 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921
922 return NO_ERROR;
923}
924
Glenn Kastenf78aee72012-01-04 11:00:47 -0800925status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926{
Eric Laurenta1884f92011-08-23 08:25:03 -0700927 status_t ret = initCheck();
928 if (ret != NO_ERROR) {
929 return ret;
930 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931
932 // check calling permissions
933 if (!settingsAllowed()) {
934 return PERMISSION_DENIED;
935 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800936 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000937 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 return BAD_VALUE;
939 }
940
941 { // scope for the lock
942 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700943 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700945 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 mHardwareStatus = AUDIO_HW_IDLE;
947 }
948
949 if (NO_ERROR == ret) {
950 Mutex::Autolock _l(mLock);
951 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800952 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700953 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 }
955
956 return ret;
957}
958
959status_t AudioFlinger::setMicMute(bool state)
960{
Eric Laurenta1884f92011-08-23 08:25:03 -0700961 status_t ret = initCheck();
962 if (ret != NO_ERROR) {
963 return ret;
964 }
965
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966 // check calling permissions
967 if (!settingsAllowed()) {
968 return PERMISSION_DENIED;
969 }
970
971 AutoMutex lock(mHardwareLock);
972 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700973 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700974 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
975 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700976 if (result != NO_ERROR) {
977 ret = result;
978 }
979 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 mHardwareStatus = AUDIO_HW_IDLE;
981 return ret;
982}
983
984bool AudioFlinger::getMicMute() const
985{
Eric Laurenta1884f92011-08-23 08:25:03 -0700986 status_t ret = initCheck();
987 if (ret != NO_ERROR) {
988 return false;
989 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800990 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700991 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800992 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800994 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700995 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
996 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800997 if (result == NO_ERROR) {
998 mute = mute && state;
999 }
1000 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001002
1003 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004}
1005
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001006void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1007{
1008 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1009
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001010 AutoMutex lock(mLock);
1011 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001012 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1013 }
1014 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1015 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001016 }
1017}
1018
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019status_t AudioFlinger::setMasterMute(bool muted)
1020{
John Grossmand8f178d2012-07-20 14:51:35 -07001021 status_t ret = initCheck();
1022 if (ret != NO_ERROR) {
1023 return ret;
1024 }
1025
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 // check calling permissions
1027 if (!settingsAllowed()) {
1028 return PERMISSION_DENIED;
1029 }
1030
John Grossmanee578c02012-07-23 17:05:46 -07001031 Mutex::Autolock _l(mLock);
1032 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001033
John Grossmanee578c02012-07-23 17:05:46 -07001034 // Set master mute in the HALs which support it.
1035 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1036 AutoMutex lock(mHardwareLock);
1037 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001038
John Grossmanee578c02012-07-23 17:05:46 -07001039 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1040 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001041 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001042 }
John Grossmanee578c02012-07-23 17:05:46 -07001043 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001044 }
1045
John Grossmanee578c02012-07-23 17:05:46 -07001046 // Now set the master mute in each playback thread. Playback threads
1047 // assigned to HALs which do not have master mute support will apply master
1048 // mute during the mix operation. Threads with HALs which do support master
1049 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001050 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1051 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1052 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054
1055 return NO_ERROR;
1056}
1057
1058float AudioFlinger::masterVolume() const
1059{
Glenn Kasten98067102011-12-13 11:47:54 -08001060 Mutex::Autolock _l(mLock);
1061 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062}
1063
1064bool AudioFlinger::masterMute() const
1065{
Glenn Kasten98067102011-12-13 11:47:54 -08001066 Mutex::Autolock _l(mLock);
1067 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068}
1069
John Grossman4ff14ba2012-02-08 16:37:41 -08001070float AudioFlinger::masterVolume_l() const
1071{
John Grossman4ff14ba2012-02-08 16:37:41 -08001072 return mMasterVolume;
1073}
1074
John Grossmand8f178d2012-07-20 14:51:35 -07001075bool AudioFlinger::masterMute_l() const
1076{
John Grossmanee578c02012-07-23 17:05:46 -07001077 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001078}
1079
Eric Laurent223fd5c2014-11-11 13:43:36 -08001080status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1081{
1082 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001083 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001084 return BAD_VALUE;
1085 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001086 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1087 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1088 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001089 return PERMISSION_DENIED;
1090 }
1091
1092 return NO_ERROR;
1093}
1094
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001095status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1096 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097{
1098 // check calling permissions
1099 if (!settingsAllowed()) {
1100 return PERMISSION_DENIED;
1101 }
1102
Eric Laurent223fd5c2014-11-11 13:43:36 -08001103 status_t status = checkStreamType(stream);
1104 if (status != NO_ERROR) {
1105 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 }
Eric Laurent98e38192018-02-15 18:31:53 -08001107 if (output == AUDIO_IO_HANDLE_NONE) {
1108 return BAD_VALUE;
1109 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001110 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111
1112 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001113 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1114 if (volumeInterface == NULL) {
1115 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 }
Eric Laurent98e38192018-02-15 18:31:53 -08001117 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118
1119 return NO_ERROR;
1120}
1121
Glenn Kastenfff6d712012-01-12 16:38:12 -08001122status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123{
1124 // check calling permissions
1125 if (!settingsAllowed()) {
1126 return PERMISSION_DENIED;
1127 }
1128
Eric Laurent223fd5c2014-11-11 13:43:36 -08001129 status_t status = checkStreamType(stream);
1130 if (status != NO_ERROR) {
1131 return status;
1132 }
1133 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1134
1135 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001136 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 return BAD_VALUE;
1138 }
1139
Eric Laurent93575202011-01-18 18:39:02 -08001140 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001142 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1143 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1144 volumeInterfaces[i]->setStreamMute(stream, muted);
1145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146
1147 return NO_ERROR;
1148}
1149
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001150float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001152 status_t status = checkStreamType(stream);
1153 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 return 0.0f;
1155 }
Eric Laurent98e38192018-02-15 18:31:53 -08001156 if (output == AUDIO_IO_HANDLE_NONE) {
1157 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 }
1159
Eric Laurent98e38192018-02-15 18:31:53 -08001160 AutoMutex lock(mLock);
1161 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1162 if (volumeInterface == NULL) {
1163 return 0.0f;
1164 }
1165
1166 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167}
1168
Glenn Kastenfff6d712012-01-12 16:38:12 -08001169bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001171 status_t status = checkStreamType(stream);
1172 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 return true;
1174 }
1175
Glenn Kasten6637baa2012-01-09 09:40:36 -08001176 AutoMutex lock(mLock);
1177 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178}
1179
Eric Laurent054d9d32015-04-24 08:48:48 -07001180
1181void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1182{
1183 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1184 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1185 }
1186}
1187
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001188// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1189void AudioFlinger::forwardParametersToDownstreamPatches_l(
1190 audio_io_handle_t upStream, const String8& keyValuePairs,
1191 std::function<bool(const sp<PlaybackThread>&)> useThread)
1192{
1193 std::vector<PatchPanel::SoftwarePatch> swPatches;
1194 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1195 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1196 __func__, swPatches.size(), upStream);
1197 for (const auto& swPatch : swPatches) {
1198 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1199 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1200 downStream->setParameters(keyValuePairs);
1201 }
1202 }
1203}
1204
Eric Laurentf1047e82018-04-16 19:18:20 -07001205// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1206// Some keys are used for audio routing and audio path configuration and should be reserved for use
1207// by audio policy and audio flinger for functional, privacy and security reasons.
1208void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1209{
1210 static const String8 kReservedParameters[] = {
1211 String8(AudioParameter::keyRouting),
1212 String8(AudioParameter::keySamplingRate),
1213 String8(AudioParameter::keyFormat),
1214 String8(AudioParameter::keyChannels),
1215 String8(AudioParameter::keyFrameCount),
1216 String8(AudioParameter::keyInputSource),
1217 String8(AudioParameter::keyMonoOutput),
1218 String8(AudioParameter::keyStreamConnect),
1219 String8(AudioParameter::keyStreamDisconnect),
1220 String8(AudioParameter::keyStreamSupportedFormats),
1221 String8(AudioParameter::keyStreamSupportedChannels),
1222 String8(AudioParameter::keyStreamSupportedSamplingRates),
1223 };
1224
Andy Hung4ef19fa2018-05-15 19:35:29 -07001225 if (isAudioServerUid(callingUid)) {
1226 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001227 }
1228
1229 AudioParameter param = AudioParameter(keyValuePairs);
1230 String8 value;
1231 for (auto& key : kReservedParameters) {
1232 if (param.get(key, value) == NO_ERROR) {
1233 ALOGW("%s: filtering key %s value %s from uid %d",
1234 __func__, key.string(), value.string(), callingUid);
1235 param.remove(key);
1236 }
1237 }
1238 keyValuePairs = param.toString();
1239}
1240
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001241status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242{
Eric Laurentf1047e82018-04-16 19:18:20 -07001243 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1244 ioHandle, keyValuePairs.string(),
1245 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001246
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 // check calling permissions
1248 if (!settingsAllowed()) {
1249 return PERMISSION_DENIED;
1250 }
1251
Eric Laurentf1047e82018-04-16 19:18:20 -07001252 String8 filteredKeyValuePairs = keyValuePairs;
1253 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1254
1255 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1256
Glenn Kasten142f5192014-03-25 17:44:59 -07001257 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1258 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001259 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001260 // result will remain NO_INIT if no audio device is present
1261 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001262 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001263 AutoMutex lock(mHardwareLock);
1264 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1265 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001266 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001267 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001268 // return success if at least one audio device accepts the parameters as not all
1269 // HALs are requested to support all parameters. If no audio device supports the
1270 // requested parameters, the last error is reported.
1271 if (final_result != NO_ERROR) {
1272 final_result = result;
1273 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001274 }
1275 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001276 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001277 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001278 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001279 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001280 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1281 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001282 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001283 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001284 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001285 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001286 }
1287 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001288 String8 screenState;
1289 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001290 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001291 if (isOff != (AudioFlinger::mScreenState & 1)) {
1292 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001293 }
1294 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001295 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 }
1297
1298 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1299 // and the thread is exited once the lock is released
1300 sp<ThreadBase> thread;
1301 {
1302 Mutex::Autolock _l(mLock);
1303 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001304 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001306 if (thread == 0) {
1307 thread = checkMmapThread_l(ioHandle);
1308 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001309 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001310 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001311 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001312 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001313 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1314 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001315 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 }
1318 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001319 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001320 status_t result = thread->setParameters(filteredKeyValuePairs);
1321 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1322 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001323 }
1324 return BAD_VALUE;
1325}
1326
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001327String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001329 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1330 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331
Eric Laurenta4c5a552012-03-29 10:12:40 -07001332 Mutex::Autolock _l(mLock);
1333
Glenn Kasten142f5192014-03-25 17:44:59 -07001334 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001335 String8 out_s8;
1336
Dima Zavin799a70e2011-04-18 16:57:27 -07001337 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001338 String8 s;
1339 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001340 {
1341 AutoMutex lock(mHardwareLock);
1342 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001343 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1344 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001345 mHardwareStatus = AUDIO_HW_IDLE;
1346 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001347 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001348 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001349 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350 }
1351
Eric Laurent6acd1d42017-01-04 14:23:29 -08001352 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1353 if (thread == NULL) {
1354 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1355 if (thread == NULL) {
1356 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1357 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001358 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001359 }
1360 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001362 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363}
1364
Glenn Kastendd8104c2012-07-02 12:42:44 -07001365size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1366 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001367{
Eric Laurenta1884f92011-08-23 08:25:03 -07001368 status_t ret = initCheck();
1369 if (ret != NO_ERROR) {
1370 return 0;
1371 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001372 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001373 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001374 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001375 return 0;
1376 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001377
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001378 AutoMutex lock(mHardwareLock);
1379 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001380 audio_config_t config, proposed;
1381 memset(&proposed, 0, sizeof(proposed));
1382 proposed.sample_rate = sampleRate;
1383 proposed.channel_mask = channelMask;
1384 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001385
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001386 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001387 size_t frames;
1388 for (;;) {
1389 // Note: config is currently a const parameter for get_input_buffer_size()
1390 // but we use a copy from proposed in case config changes from the call.
1391 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001392 status_t result = dev->getInputBufferSize(&config, &frames);
1393 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001394 break; // hal success, config is the result
1395 }
1396 // change one parameter of the configuration each iteration to a more "common" value
1397 // to see if the device will support it.
1398 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1399 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1400 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1401 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1402 } else {
1403 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1404 "format %#x, channelMask 0x%X",
1405 sampleRate, format, channelMask);
1406 break; // retries failed, break out of loop with frames == 0.
1407 }
1408 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001409 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001410 if (frames > 0 && config.sample_rate != sampleRate) {
1411 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1412 }
1413 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414}
1415
Glenn Kasten5f972c02014-01-13 09:59:31 -08001416uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001418 Mutex::Autolock _l(mLock);
1419
1420 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1421 if (recordThread != NULL) {
1422 return recordThread->getInputFramesLost();
1423 }
1424 return 0;
1425}
1426
1427status_t AudioFlinger::setVoiceVolume(float value)
1428{
Eric Laurenta1884f92011-08-23 08:25:03 -07001429 status_t ret = initCheck();
1430 if (ret != NO_ERROR) {
1431 return ret;
1432 }
1433
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434 // check calling permissions
1435 if (!settingsAllowed()) {
1436 return PERMISSION_DENIED;
1437 }
1438
1439 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001440 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001441 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001442 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443 mHardwareStatus = AUDIO_HW_IDLE;
1444
1445 return ret;
1446}
1447
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001448status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001449 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451 Mutex::Autolock _l(mLock);
1452
1453 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1454 if (playbackThread != NULL) {
1455 return playbackThread->getRenderPosition(halFrames, dspFrames);
1456 }
1457
1458 return BAD_VALUE;
1459}
1460
1461void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1462{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001464 if (client == 0) {
1465 return;
1466 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001467 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001468 {
1469 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001470 if (mNotificationClients.indexOfKey(pid) < 0) {
1471 sp<NotificationClient> notificationClient = new NotificationClient(this,
1472 client,
1473 pid);
1474 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475
Eric Laurent021cf962014-05-13 10:18:14 -07001476 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477
Marco Nelissen06b46062014-11-14 07:58:25 -08001478 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001479 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001480 }
1481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482
Eric Laurent021cf962014-05-13 10:18:14 -07001483 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001484 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001485 // the config change is always sent from playback or record threads to avoid deadlock
1486 // with AudioSystem::gLock
1487 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001488 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001491 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001492 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 }
1494}
1495
1496void AudioFlinger::removeNotificationClient(pid_t pid)
1497{
1498 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001499 {
1500 Mutex::Autolock _cl(mClientLock);
1501 mNotificationClients.removeItem(pid);
1502 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001503
Steve Block3856b092011-10-20 11:56:00 +01001504 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001505 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001506 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001507 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001508 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001509 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001510 if (ref->mPid == pid) {
1511 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001512 mAudioSessionRefs.removeAt(i);
1513 delete ref;
1514 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001515 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001516 } else {
1517 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001518 }
1519 }
1520 if (removed) {
1521 purgeStaleEffects_l();
1522 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523}
1524
Eric Laurent73e26b62015-04-27 16:55:58 -07001525void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001526 const sp<AudioIoDescriptor>& ioDesc,
1527 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528{
Eric Laurent021cf962014-05-13 10:18:14 -07001529 Mutex::Autolock _l(mClientLock);
1530 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001532 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1533 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1534 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 }
1536}
1537
Eric Laurent021cf962014-05-13 10:18:14 -07001538// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539void AudioFlinger::removeClient_l(pid_t pid)
1540{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001541 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001542 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543 mClients.removeItem(pid);
1544}
1545
Eric Laurent717e1282012-06-29 16:36:52 -07001546// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001547sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1548 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001549{
1550 sp<PlaybackThread> thread;
1551
1552 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1553 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1554 ALOG_ASSERT(thread == 0);
1555 thread = mPlaybackThreads.valueAt(i);
1556 }
1557 }
1558
1559 return thread;
1560}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563
1564// ----------------------------------------------------------------------------
1565
1566AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1567 : RefBase(),
1568 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001569 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570{
Andy Hung6f248bb2018-01-23 14:04:37 -08001571 mMemoryDealer = new MemoryDealer(
1572 audioFlinger->getClientSharedHeapSize(),
1573 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574}
1575
Eric Laurent021cf962014-05-13 10:18:14 -07001576// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577AudioFlinger::Client::~Client()
1578{
1579 mAudioFlinger->removeClient_l(mPid);
1580}
1581
Glenn Kasten435dbe62012-01-30 10:15:48 -08001582sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583{
1584 return mMemoryDealer;
1585}
1586
1587// ----------------------------------------------------------------------------
1588
1589AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1590 const sp<IAudioFlingerClient>& client,
1591 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001592 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593{
1594}
1595
1596AudioFlinger::NotificationClient::~NotificationClient()
1597{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598}
1599
Glenn Kasten0f11b512014-01-31 16:18:54 -08001600void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601{
1602 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001603 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604}
1605
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001606// ----------------------------------------------------------------------------
1607AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1608 : mPendingRequests(false) {}
1609
1610
1611void AudioFlinger::MediaLogNotifier::requestMerge() {
1612 AutoMutex _l(mMutex);
1613 mPendingRequests = true;
1614 mCond.signal();
1615}
1616
1617bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001618 // Should already have been checked, but just in case
1619 if (sMediaLogService == 0) {
1620 return false;
1621 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001622 // Wait until there are pending requests
1623 {
1624 AutoMutex _l(mMutex);
1625 mPendingRequests = false; // to ignore past requests
1626 while (!mPendingRequests) {
1627 mCond.wait(mMutex);
1628 // TODO may also need an exitPending check
1629 }
1630 mPendingRequests = false;
1631 }
1632 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001633 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001634 usleep(kPostTriggerSleepPeriod);
1635 return true;
1636}
1637
1638void AudioFlinger::requestLogMerge() {
1639 mMediaLogNotifier->requestMerge();
1640}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641
1642// ----------------------------------------------------------------------------
1643
Eric Laurentf14db3c2017-12-08 14:20:36 -08001644sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1645 CreateRecordOutput& output,
1646 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647{
1648 sp<RecordThread::RecordTrack> recordTrack;
1649 sp<RecordHandle> recordHandle;
1650 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001652 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001653 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654
Eric Laurentf14db3c2017-12-08 14:20:36 -08001655 output.cblk.clear();
1656 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001657 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001658
Eric Laurentf14db3c2017-12-08 14:20:36 -08001659 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001660 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001661 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001662 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001663 ALOGW_IF(clientUid != callingUid,
1664 "%s uid %d tried to pass itself off as %d",
1665 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001666 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001667 updatePid = true;
1668 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001669 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001670 if (updatePid) {
1671 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001672 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001673 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001674 __func__, callingUid, callingPid, clientPid);
1675 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001676 }
1677
Andy Hung6770c6f2015-04-07 13:43:36 -07001678 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001679 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1680 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001681 lStatus = BAD_VALUE;
1682 goto Exit;
1683 }
1684
Glenn Kasten53b5d092014-02-05 10:00:23 -08001685 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001686 if (!audio_is_input_channel(input.config.channel_mask)) {
1687 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001688 lStatus = BAD_VALUE;
1689 goto Exit;
1690 }
1691
Eric Laurentf14db3c2017-12-08 14:20:36 -08001692 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1693 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1694 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1695 lStatus = BAD_VALUE;
1696 goto Exit;
1697 }
1698
1699 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001700 output.selectedDeviceId = input.selectedDeviceId;
1701 output.flags = input.flags;
1702
1703 client = registerPid(clientPid);
1704
1705 // Not a conventional loop, but a retry loop for at most two iterations total.
1706 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1707 // Exits loop via break on no error of got exit on error
1708 // The sp<> references will be dropped when re-entering scope.
1709 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1710 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001711 // release previously opened input if retrying.
1712 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1713 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001714 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001715 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001716 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001717 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001718 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001719 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1720 sessionId,
1721 // FIXME compare to AudioTrack
1722 clientPid,
1723 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001724 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001725 &input.config,
1726 output.flags, &output.selectedDeviceId, &portId);
1727
Glenn Kasten05997e22014-03-13 15:08:33 -07001728 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001730 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001732 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733 lStatus = BAD_VALUE;
1734 goto Exit;
1735 }
1736
Eric Laurentf14db3c2017-12-08 14:20:36 -08001737 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738
Eric Laurentf14db3c2017-12-08 14:20:36 -08001739 output.sampleRate = input.config.sample_rate;
1740 output.frameCount = input.frameCount;
1741 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001742
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001743 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001744 input.config.format, input.config.channel_mask,
1745 &output.frameCount, sessionId,
1746 &output.notificationFrameCount,
1747 clientUid, &output.flags,
1748 input.clientInfo.clientTid,
1749 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001750 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001751
Eric Laurentf14db3c2017-12-08 14:20:36 -08001752 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1753 // audio policy manager without FAST constraint
1754 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001755 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001756 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001757
1758 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001759 goto Exit;
1760 }
1761
1762 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1763 // session and move it to this thread.
1764 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1765 if (chain != 0) {
1766 Mutex::Autolock _l(thread->mLock);
1767 thread->addEffectChain_l(chain);
1768 }
1769 break;
1770 }
1771 // End of retry loop.
1772 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 }
Glenn Kastene198c362013-08-13 09:13:36 -07001774
Eric Laurentf14db3c2017-12-08 14:20:36 -08001775 output.cblk = recordTrack->getCblk();
1776 output.buffers = recordTrack->getBuffers();
1777
1778 // return handle to client
1779 recordHandle = new RecordHandle(recordTrack);
1780
1781Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001782 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001783 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001784 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001785 // Don't hold mClientLock when releasing the reference on the track as the
1786 // destructor will acquire it.
1787 {
1788 Mutex::Autolock _cl(mClientLock);
1789 client.clear();
1790 }
Eric Laurent896c9672017-12-08 14:08:45 -08001791 recordTrack.clear();
1792 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001793 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001794 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 }
1796
Glenn Kasten9156ef32013-08-06 15:39:08 -07001797 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 return recordHandle;
1799}
1800
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001801
1802
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803// ----------------------------------------------------------------------------
1804
Eric Laurenta4c5a552012-03-29 10:12:40 -07001805audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1806{
Eric Laurent44622db2014-08-01 19:00:33 -07001807 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001808 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001809 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001810 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001811 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001812 }
1813 Mutex::Autolock _l(mLock);
1814 return loadHwModule_l(name);
1815}
1816
1817// loadHwModule_l() must be called with AudioFlinger::mLock held
1818audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1819{
1820 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1821 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1822 ALOGW("loadHwModule() module %s already loaded", name);
1823 return mAudioHwDevs.keyAt(i);
1824 }
1825 }
1826
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001827 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001828
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001829 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001830 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001831 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001832 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001833 }
1834
1835 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001836 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001837 mHardwareStatus = AUDIO_HW_IDLE;
1838 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001839 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001840 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001841 }
1842
John Grossmanee578c02012-07-23 17:05:46 -07001843 // Check and cache this HAL's level of support for master mute and master
1844 // volume. If this is the first HAL opened, and it supports the get
1845 // methods, use the initial values provided by the HAL as the current
1846 // master mute and volume settings.
1847
1848 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1849 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001850 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001851
1852 if (0 == mAudioHwDevs.size()) {
1853 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001854 float mv;
1855 if (OK == dev->getMasterVolume(&mv)) {
1856 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001857 }
1858
1859 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001860 bool mm;
1861 if (OK == dev->getMasterMute(&mm)) {
1862 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001863 }
1864 }
1865
Eric Laurenta4c5a552012-03-29 10:12:40 -07001866 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001867 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001868 flags = static_cast<AudioHwDevice::Flags>(flags |
1869 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1870 }
1871
1872 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001873 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001874 flags = static_cast<AudioHwDevice::Flags>(flags |
1875 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1876 }
1877
Eric Laurenta4c5a552012-03-29 10:12:40 -07001878 mHardwareStatus = AUDIO_HW_IDLE;
1879 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07001880 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07001881 // An MSD module is inserted before hardware modules in order to mix encoded streams.
1882 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
1883 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001884
Glenn Kastena13cde92016-03-28 15:26:02 -07001885 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001886 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001887
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001888 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001889
1890 return handle;
1891
1892}
1893
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001894// ----------------------------------------------------------------------------
1895
Glenn Kasten3b16c762012-11-14 08:44:39 -08001896uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001897{
1898 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001899 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001900 return thread != NULL ? thread->sampleRate() : 0;
1901}
1902
Glenn Kastene33054e2012-11-14 12:54:39 -08001903size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001904{
1905 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001906 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001907 return thread != NULL ? thread->frameCountHAL() : 0;
1908}
1909
1910// ----------------------------------------------------------------------------
1911
Andy Hung6f248bb2018-01-23 14:04:37 -08001912status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001913{
1914 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001915 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001916 return PERMISSION_DENIED;
1917 }
1918 Mutex::Autolock _l(mLock);
1919 if (mIsDeviceTypeKnown) {
1920 return INVALID_OPERATION;
1921 }
1922 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001923 mTotalMemory = totalMemory;
1924 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1925 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1926 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1927 // though actual setting is determined through device configuration.
1928 constexpr int64_t GB = 1024 * 1024 * 1024;
1929 mClientSharedHeapSize =
1930 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1931 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1932 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1933 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1934 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001935 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001936
1937 // TODO: Cache the client shared heap size in a persistent property.
1938 // It's possible that a native process or Java service or app accesses audioserver
1939 // after it is registered by system server, but before AudioService updates
1940 // the memory info. This would occur immediately after boot or an audioserver
1941 // crash and restore. Before update from AudioService, the client would get the
1942 // minimum heap size.
1943
1944 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1945 (isLowRamDevice ? "true" : "false"),
1946 (long long)mTotalMemory,
1947 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001948 return NO_ERROR;
1949}
1950
Andy Hung6f248bb2018-01-23 14:04:37 -08001951size_t AudioFlinger::getClientSharedHeapSize() const
1952{
1953 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1954 if (heapSizeInBytes != 0) { // read-only property overrides all.
1955 return heapSizeInBytes;
1956 }
1957 return mClientSharedHeapSize;
1958}
1959
Mikhail Naganovdea53042018-04-26 13:10:21 -07001960status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1961{
1962 ALOGV(__func__);
1963
1964 audio_module_handle_t module;
1965 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1966 module = config->ext.device.hw_module;
1967 } else {
1968 module = config->ext.mix.hw_module;
1969 }
1970
1971 Mutex::Autolock _l(mLock);
1972 ssize_t index = mAudioHwDevs.indexOfKey(module);
1973 if (index < 0) {
1974 ALOGW("%s() bad hw module %d", __func__, module);
1975 return BAD_VALUE;
1976 }
1977
1978 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
1979 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
1980}
1981
Eric Laurent93c3d412014-08-01 14:48:35 -07001982audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1983{
1984 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001985
1986 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1987 if (index >= 0) {
1988 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1989 mHwAvSyncIds.valueAt(index), sessionId);
1990 return mHwAvSyncIds.valueAt(index);
1991 }
1992
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001993 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001994 if (dev == NULL) {
1995 return AUDIO_HW_SYNC_INVALID;
1996 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001997 String8 reply;
1998 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001999 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002000 param = AudioParameter(reply);
2001 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002002
2003 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002004 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002005 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2006 return AUDIO_HW_SYNC_INVALID;
2007 }
2008
2009 // allow only one session for a given HW A/V sync ID.
2010 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2011 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2012 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2013 value, mHwAvSyncIds.keyAt(i));
2014 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002015 break;
2016 }
2017 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002018
2019 mHwAvSyncIds.add(sessionId, value);
2020
2021 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2022 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2023 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002024 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002025 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002026 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002027 String8 keyValuePairs = param.toString();
2028 thread->setParameters(keyValuePairs);
2029 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2030 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002031 break;
2032 }
2033 }
2034
2035 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2036 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002037}
2038
Eric Laurent72e3f392015-05-20 14:43:50 -07002039status_t AudioFlinger::systemReady()
2040{
2041 Mutex::Autolock _l(mLock);
2042 ALOGI("%s", __FUNCTION__);
2043 if (mSystemReady) {
2044 ALOGW("%s called twice", __FUNCTION__);
2045 return NO_ERROR;
2046 }
2047 mSystemReady = true;
2048 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2049 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2050 thread->systemReady();
2051 }
2052 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2053 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2054 thread->systemReady();
2055 }
2056 return NO_ERROR;
2057}
2058
jiabin46a76fa2018-01-05 10:18:21 -08002059status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2060{
jiabin9ff780e2018-03-19 18:19:52 -07002061 AutoMutex lock(mHardwareLock);
2062 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2063 status_t status = dev->getMicrophones(microphones);
2064 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002065}
2066
Eric Laurentfa90e842014-10-17 18:12:31 -07002067// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2068void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2069{
2070 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2071 if (index >= 0) {
2072 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2073 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2074 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002075 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002076 String8 keyValuePairs = param.toString();
2077 thread->setParameters(keyValuePairs);
2078 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2079 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002080 }
2081}
2082
2083
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002084// ----------------------------------------------------------------------------
2085
Eric Laurent83b88082014-06-20 18:31:16 -07002086
Eric Laurent6acd1d42017-01-04 14:23:29 -08002087sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002088 audio_io_handle_t *output,
2089 audio_config_t *config,
2090 audio_devices_t devices,
2091 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002092 audio_output_flags_t flags)
2093{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002094 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002095 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002096 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002097 }
2098
Eric Laurentcf2c0212014-07-25 16:20:43 -07002099 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002100 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2101 } else {
2102 // Audio Policy does not currently request a specific output handle.
2103 // If this is ever needed, see openInput_l() for example code.
2104 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2105 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002106 }
Eric Laurent83b88082014-06-20 18:31:16 -07002107
2108 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2109
Eric Laurent83b88082014-06-20 18:31:16 -07002110 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002111 // This if statement allows overriding the audio policy settings
2112 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2113 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2114 // Check only for Normal Mixing mode
2115 if (kEnableExtendedPrecision) {
2116 // Specify format (uncomment one below to choose)
2117 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2118 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2119 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2120 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002121 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002122 }
2123 if (kEnableExtendedChannels) {
2124 // Specify channel mask (uncomment one below to choose)
2125 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2126 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2127 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2128 }
Eric Laurent83b88082014-06-20 18:31:16 -07002129 }
2130
Phil Burk062e67a2015-02-11 13:40:50 -08002131 AudioStreamOut *outputStream = NULL;
2132 status_t status = outHwDev->openOutputStream(
2133 &outputStream,
2134 *output,
2135 devices,
2136 flags,
2137 config,
2138 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002139
2140 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002141
Phil Burk062e67a2015-02-11 13:40:50 -08002142 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002143 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2144 sp<MmapPlaybackThread> thread =
2145 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2146 devices, AUDIO_DEVICE_NONE, mSystemReady);
2147 mMmapThreads.add(*output, thread);
2148 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2149 *output, thread.get());
2150 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002151 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002152 sp<PlaybackThread> thread;
2153 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2154 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2155 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2156 *output, thread.get());
2157 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2158 || !isValidPcmSinkFormat(config->format)
2159 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2160 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2161 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2162 *output, thread.get());
2163 } else {
2164 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2165 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2166 *output, thread.get());
2167 }
2168 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002169 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002170 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002171 }
Eric Laurent83b88082014-06-20 18:31:16 -07002172 }
2173
2174 return 0;
2175}
2176
Eric Laurentcf2c0212014-07-25 16:20:43 -07002177status_t AudioFlinger::openOutput(audio_module_handle_t module,
2178 audio_io_handle_t *output,
2179 audio_config_t *config,
2180 audio_devices_t *devices,
2181 const String8& address,
2182 uint32_t *latencyMs,
2183 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002185 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2186 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002187 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002188 (devices != NULL) ? *devices : 0,
2189 config->sample_rate,
2190 config->format,
2191 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002192 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002194 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002195 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002197
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198 Mutex::Autolock _l(mLock);
2199
Eric Laurent6acd1d42017-01-04 14:23:29 -08002200 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002201 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002202 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2203 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2204 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205
Eric Laurent6acd1d42017-01-04 14:23:29 -08002206 // notify client processes of the new output creation
2207 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002208
Eric Laurent6acd1d42017-01-04 14:23:29 -08002209 // the first primary output opened designates the primary hw device
2210 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002211 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002212 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002213
Eric Laurent6acd1d42017-01-04 14:23:29 -08002214 AutoMutex lock(mHardwareLock);
2215 mHardwareStatus = AUDIO_HW_SET_MODE;
2216 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2217 mHardwareStatus = AUDIO_HW_IDLE;
2218 }
2219 } else {
2220 MmapThread *mmapThread = (MmapThread *)thread.get();
2221 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002222 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002223 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 }
2225
Eric Laurentcf2c0212014-07-25 16:20:43 -07002226 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227}
2228
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002229audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2230 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231{
2232 Mutex::Autolock _l(mLock);
2233 MixerThread *thread1 = checkMixerThread_l(output1);
2234 MixerThread *thread2 = checkMixerThread_l(output2);
2235
2236 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002237 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2238 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002239 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 }
2241
Glenn Kasteneeecb982016-02-26 10:44:04 -08002242 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002243 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 thread->addOutputTrack(thread2);
2245 mPlaybackThreads.add(id, thread);
2246 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002247 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 return id;
2249}
2250
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002251status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252{
Glenn Kastend96c5722012-04-25 13:44:49 -07002253 return closeOutput_nonvirtual(output);
2254}
2255
2256status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2257{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 // keep strong reference on the playback thread so that
2259 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002260 sp<PlaybackThread> playbackThread;
2261 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262 {
2263 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002264 playbackThread = checkPlaybackThread_l(output);
2265 if (playbackThread != NULL) {
2266 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267
Eric Laurent6acd1d42017-01-04 14:23:29 -08002268 if (playbackThread->type() == ThreadBase::MIXER) {
2269 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2270 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2271 DuplicatingThread *dupThread =
2272 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2273 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002275 }
2276 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277
2278
Eric Laurent6acd1d42017-01-04 14:23:29 -08002279 mPlaybackThreads.removeItem(output);
2280 // save all effects to the default thread
2281 if (mPlaybackThreads.size()) {
2282 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2283 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002284 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002285 Mutex::Autolock _dl(dstThread->mLock);
2286 Mutex::Autolock _sl(playbackThread->mLock);
2287 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2288 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002289 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2290 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002291 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 }
2293 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002294 } else {
2295 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2296 if (mmapThread == 0) {
2297 return BAD_VALUE;
2298 }
2299 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002300 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002302 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2303 ioDesc->mIoHandle = output;
2304 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002305 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002307 // The thread entity (active unit of execution) is no longer running here,
2308 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309
Eric Laurent6acd1d42017-01-04 14:23:29 -08002310 if (playbackThread != 0) {
2311 playbackThread->exit();
2312 if (!playbackThread->isDuplicating()) {
2313 closeOutputFinish(playbackThread);
2314 }
2315 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002316 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002317 mmapThread->exit();
2318 AudioStreamOut *out = mmapThread->clearOutput();
2319 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2320 // from now on thread->mOutput is NULL
2321 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 }
2323 return NO_ERROR;
2324}
2325
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002326void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002327{
2328 AudioStreamOut *out = thread->clearOutput();
2329 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2330 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002331 delete out;
2332}
2333
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002334void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002335{
2336 mPlaybackThreads.removeItem(thread->mId);
2337 thread->exit();
2338 closeOutputFinish(thread);
2339}
2340
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002341status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342{
2343 Mutex::Autolock _l(mLock);
2344 PlaybackThread *thread = checkPlaybackThread_l(output);
2345
2346 if (thread == NULL) {
2347 return BAD_VALUE;
2348 }
2349
Steve Block3856b092011-10-20 11:56:00 +01002350 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 thread->suspend();
2352
2353 return NO_ERROR;
2354}
2355
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002356status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357{
2358 Mutex::Autolock _l(mLock);
2359 PlaybackThread *thread = checkPlaybackThread_l(output);
2360
2361 if (thread == NULL) {
2362 return BAD_VALUE;
2363 }
2364
Steve Block3856b092011-10-20 11:56:00 +01002365 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002366
2367 thread->restore();
2368
2369 return NO_ERROR;
2370}
2371
Eric Laurentcf2c0212014-07-25 16:20:43 -07002372status_t AudioFlinger::openInput(audio_module_handle_t module,
2373 audio_io_handle_t *input,
2374 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002375 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002376 const String8& address,
2377 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002378 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379{
Eric Laurent83b88082014-06-20 18:31:16 -07002380 Mutex::Autolock _l(mLock);
2381
Glenn Kastene7d66712015-03-05 13:46:52 -08002382 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002383 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002384 }
2385
Eric Laurent6acd1d42017-01-04 14:23:29 -08002386 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002387
2388 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002389 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002390 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002391 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002393 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002394}
Dima Zavin799a70e2011-04-18 16:57:27 -07002395
Eric Laurent6acd1d42017-01-04 14:23:29 -08002396sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002397 audio_io_handle_t *input,
2398 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002399 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002400 const String8& address,
2401 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002402 audio_input_flags_t flags)
2403{
Glenn Kastene7d66712015-03-05 13:46:52 -08002404 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002405 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002406 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002407 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002408 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002409
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002410 // Some flags are specific to framework and must not leak to the HAL.
2411 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2412
Glenn Kasteneeecb982016-02-26 10:44:04 -08002413 // Audio Policy can request a specific handle for hardware hotword.
2414 // The goal here is not to re-open an already opened input.
2415 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002416 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002417 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2418 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2419 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2420 return 0;
2421 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2422 // This should not happen in a transient state with current design.
2423 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2424 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002425 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002426
Eric Laurentcf2c0212014-07-25 16:20:43 -07002427 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002428 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002429 sp<StreamInHalInterface> inStream;
2430 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002431 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002432 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2433 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002434 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002435 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002436 halconfig.sample_rate,
2437 halconfig.format,
2438 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002439 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002440 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002442 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002443 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002444 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002445 audio_is_linear_pcm(config->format) &&
2446 audio_is_linear_pcm(halconfig.format) &&
2447 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002448 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2449 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002450 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002451 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002452 inStream.clear();
2453 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002454 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002455 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 }
2457
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002458 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002459 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002460 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2461 sp<MmapCaptureThread> thread =
2462 new MmapCaptureThread(this, *input,
2463 inHwDev, inputStream,
2464 primaryOutputDevice_l(), devices, mSystemReady);
2465 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002466 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2467 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002468 return thread;
2469 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002470 // Start record thread
2471 // RecordThread requires both input and output device indication to forward to audio
2472 // pre processing modules
2473 sp<RecordThread> thread = new RecordThread(this,
2474 inputStream,
2475 *input,
2476 primaryOutputDevice_l(),
2477 devices,
2478 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002479 );
2480 mRecordThreads.add(*input, thread);
2481 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2482 return thread;
2483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 }
2485
Eric Laurentcf2c0212014-07-25 16:20:43 -07002486 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 return 0;
2488}
2489
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002490status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491{
Glenn Kastend96c5722012-04-25 13:44:49 -07002492 return closeInput_nonvirtual(input);
2493}
2494
2495status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2496{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497 // keep strong reference on the record thread so that
2498 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002499 sp<RecordThread> recordThread;
2500 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 {
2502 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002503 recordThread = checkRecordThread_l(input);
2504 if (recordThread != 0) {
2505 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506
Eric Laurent6acd1d42017-01-04 14:23:29 -08002507 // If we still have effect chains, it means that a client still holds a handle
2508 // on at least one effect. We must either move the chain to an existing thread with the
2509 // same session ID or put it aside in case a new record thread is opened for a
2510 // new capture on the same session
2511 sp<EffectChain> chain;
2512 {
2513 Mutex::Autolock _sl(recordThread->mLock);
2514 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2515 // Note: maximum one chain per record thread
2516 if (effectChains.size() != 0) {
2517 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002518 }
2519 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002520 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002521 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002522 // This should only happen in case of overlap between one thread tear down and the
2523 // creation of its replacement
2524 size_t i;
2525 for (i = 0; i < mRecordThreads.size(); i++) {
2526 sp<RecordThread> t = mRecordThreads.valueAt(i);
2527 if (t == recordThread) {
2528 continue;
2529 }
2530 if (t->hasAudioSession(chain->sessionId()) != 0) {
2531 Mutex::Autolock _l(t->mLock);
2532 ALOGV("closeInput() found thread %d for effect session %d",
2533 t->id(), chain->sessionId());
2534 t->addEffectChain_l(chain);
2535 break;
2536 }
2537 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002538 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002539 if (i == mRecordThreads.size()) {
2540 putOrphanEffectChain_l(chain);
2541 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002542 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002543 mRecordThreads.removeItem(input);
2544 } else {
2545 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2546 if (mmapThread == 0) {
2547 return BAD_VALUE;
2548 }
2549 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002550 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002551 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2552 ioDesc->mIoHandle = input;
2553 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 }
Eric Laurent83b88082014-06-20 18:31:16 -07002555 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2556 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002557 if (recordThread != 0) {
2558 closeInputFinish(recordThread);
2559 } else if (mmapThread != 0) {
2560 mmapThread->exit();
2561 AudioStreamIn *in = mmapThread->clearInput();
2562 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2563 // from now on thread->mInput is NULL
2564 delete in;
2565 }
Eric Laurent83b88082014-06-20 18:31:16 -07002566 return NO_ERROR;
2567}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002569void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002570{
2571 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002572 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002573 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002574 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002575 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002576}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002578void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002579{
2580 mRecordThreads.removeItem(thread->mId);
2581 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582}
2583
Glenn Kastend2304db2014-02-03 07:40:31 -08002584status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585{
2586 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002587 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588
2589 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2590 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002591 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002592 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002593 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2594 mMmapThreads[i]->invalidateTracks(stream);
2595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 return NO_ERROR;
2597}
2598
2599
Glenn Kasteneeecb982016-02-26 10:44:04 -08002600audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601{
Glenn Kasten9d003132016-04-06 14:38:09 -07002602 // This is a binder API, so a malicious client could pass in a bad parameter.
2603 // Check for that before calling the internal API nextUniqueId().
2604 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2605 ALOGE("newAudioUniqueId invalid use %d", use);
2606 return AUDIO_UNIQUE_ID_ALLOCATE;
2607 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002608 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609}
2610
Glenn Kastend848eb42016-03-08 13:42:11 -08002611void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002612{
2613 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002614 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002615 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002616 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2617 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002618 caller = pid;
2619 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002620
Eric Laurent021cf962014-05-13 10:18:14 -07002621 {
2622 Mutex::Autolock _cl(mClientLock);
2623 // Ignore requests received from processes not known as notification client. The request
2624 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2625 // called from a different pid leaving a stale session reference. Also we don't know how
2626 // to clear this reference if the client process dies.
2627 if (mNotificationClients.indexOfKey(caller) < 0) {
2628 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2629 return;
2630 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002631 }
2632
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002633 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002634 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002635 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002636 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2637 ref->mCnt++;
2638 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002639 return;
2640 }
2641 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002642 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2643 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002644}
2645
Glenn Kastend848eb42016-03-08 13:42:11 -08002646void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002647{
2648 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002649 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002650 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002651 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2652 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002653 caller = pid;
2654 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002655 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002656 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002657 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002658 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2659 ref->mCnt--;
2660 ALOGV(" decremented refcount to %d", ref->mCnt);
2661 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002662 mAudioSessionRefs.removeAt(i);
2663 delete ref;
2664 purgeStaleEffects_l();
2665 }
2666 return;
2667 }
2668 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002669 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002670 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002671 ALOGW_IF(!isAudioServerUid(callerUid),
2672 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002673}
2674
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002675bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2676{
2677 size_t num = mAudioSessionRefs.size();
2678 for (size_t i = 0; i < num; i++) {
2679 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2680 if (ref->mSessionid == audioSession) {
2681 return true;
2682 }
2683 }
2684 return false;
2685}
2686
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002687void AudioFlinger::purgeStaleEffects_l() {
2688
Steve Block3856b092011-10-20 11:56:00 +01002689 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002690
2691 Vector< sp<EffectChain> > chains;
2692
2693 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2694 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002695 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002696 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2697 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002698 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2699 chains.push(ec);
2700 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002701 }
2702 }
2703 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2704 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002705 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002706 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2707 sp<EffectChain> ec = t->mEffectChains[j];
2708 chains.push(ec);
2709 }
2710 }
2711
2712 for (size_t i = 0; i < chains.size(); i++) {
2713 sp<EffectChain> ec = chains[i];
2714 int sessionid = ec->sessionId();
2715 sp<ThreadBase> t = ec->mThread.promote();
2716 if (t == 0) {
2717 continue;
2718 }
2719 size_t numsessionrefs = mAudioSessionRefs.size();
2720 bool found = false;
2721 for (size_t k = 0; k < numsessionrefs; k++) {
2722 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002723 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002724 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002725 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002726 found = true;
2727 break;
2728 }
2729 }
2730 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002731 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002732 // remove all effects from the chain
2733 while (ec->mEffects.size()) {
2734 sp<EffectModule> effect = ec->mEffects[0];
2735 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002736 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002737 if (effect->purgeHandles()) {
2738 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002739 }
2740 AudioSystem::unregisterEffect(effect->id());
2741 }
2742 }
2743 }
2744 return;
2745}
2746
Glenn Kasteneeecb982016-02-26 10:44:04 -08002747// checkThread_l() must be called with AudioFlinger::mLock held
2748AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2749{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002750 ThreadBase *thread = checkMmapThread_l(ioHandle);
2751 if (thread == 0) {
2752 switch (audio_unique_id_get_use(ioHandle)) {
2753 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2754 thread = checkPlaybackThread_l(ioHandle);
2755 break;
2756 case AUDIO_UNIQUE_ID_USE_INPUT:
2757 thread = checkRecordThread_l(ioHandle);
2758 break;
2759 default:
2760 break;
2761 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002762 }
2763 return thread;
2764}
2765
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002767AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768{
Glenn Kastena1117922012-01-26 10:53:32 -08002769 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770}
2771
2772// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002773AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774{
2775 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002776 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777}
2778
2779// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002780AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781{
Glenn Kastena1117922012-01-26 10:53:32 -08002782 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783}
2784
Eric Laurent6acd1d42017-01-04 14:23:29 -08002785// checkMmapThread_l() must be called with AudioFlinger::mLock held
2786AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2787{
2788 return mMmapThreads.valueFor(io).get();
2789}
2790
2791
2792// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2793AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2794{
Eric Laurent7459b902017-04-19 18:10:41 -07002795 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002796 if (volumeInterface == nullptr) {
2797 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2798 if (mmapThread != nullptr) {
2799 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002800 MmapPlaybackThread *mmapPlaybackThread =
2801 static_cast<MmapPlaybackThread *>(mmapThread);
2802 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002803 }
2804 }
2805 }
2806 return volumeInterface;
2807}
2808
2809Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2810{
2811 Vector <VolumeInterface *> volumeInterfaces;
2812 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002813 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002814 }
2815 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2816 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002817 MmapPlaybackThread *mmapPlaybackThread =
2818 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2819 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002820 }
2821 }
2822 return volumeInterfaces;
2823}
2824
Glenn Kasteneeecb982016-02-26 10:44:04 -08002825audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826{
Glenn Kasten9d003132016-04-06 14:38:09 -07002827 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002828 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002829 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2830 for (int retry = 0; retry < maxRetries; retry++) {
2831 // The cast allows wraparound from max positive to min negative instead of abort
2832 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2833 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2834 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2835 // allow wrap by skipping 0 and -1 for session ids
2836 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2837 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2838 return (audio_unique_id_t) (base | use);
2839 }
2840 }
2841 // We have no way of recovering from wraparound
2842 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2843 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844}
2845
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002846AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002847{
2848 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2849 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002850 if(thread->isDuplicating()) {
2851 continue;
2852 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002853 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002854 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002855 return thread;
2856 }
2857 }
2858 return NULL;
2859}
2860
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002861audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002862{
2863 PlaybackThread *thread = primaryPlaybackThread_l();
2864
2865 if (thread == NULL) {
2866 return 0;
2867 }
2868
Eric Laurentf1c04f92012-08-28 14:26:53 -07002869 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002870}
2871
Glenn Kastena7335632016-06-09 17:09:53 -07002872AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2873{
2874 size_t minFrameCount = 0;
2875 PlaybackThread *minThread = NULL;
2876 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2877 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2878 if (!thread->isDuplicating()) {
2879 size_t frameCount = thread->frameCountHAL();
2880 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2881 (frameCount == minFrameCount && thread->hasFastMixer() &&
2882 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2883 minFrameCount = frameCount;
2884 minThread = thread;
2885 }
2886 }
2887 }
2888 return minThread;
2889}
2890
Eric Laurenta011e352012-03-29 15:51:43 -07002891sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002892 audio_session_t triggerSession,
2893 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002894 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002895 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002896{
2897 Mutex::Autolock _l(mLock);
2898
2899 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2900 status_t playStatus = NAME_NOT_FOUND;
2901 status_t recStatus = NAME_NOT_FOUND;
2902 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2903 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2904 if (playStatus == NO_ERROR) {
2905 return event;
2906 }
2907 }
2908 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2909 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2910 if (recStatus == NO_ERROR) {
2911 return event;
2912 }
2913 }
2914 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2915 mPendingSyncEvents.add(event);
2916 } else {
2917 ALOGV("createSyncEvent() invalid event %d", event->type());
2918 event.clear();
2919 }
2920 return event;
2921}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002922
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923// ----------------------------------------------------------------------------
2924// Effect management
2925// ----------------------------------------------------------------------------
2926
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002927sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2928 return mEffectsFactoryHal;
2929}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930
Glenn Kastenf587ba52012-01-26 16:25:10 -08002931status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932{
2933 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002934 if (mEffectsFactoryHal.get()) {
2935 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2936 } else {
2937 return -ENODEV;
2938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939}
2940
Glenn Kastenf587ba52012-01-26 16:25:10 -08002941status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942{
2943 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002944 if (mEffectsFactoryHal.get()) {
2945 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2946 } else {
2947 return -ENODEV;
2948 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949}
2950
Glenn Kasten5e92a782012-01-30 07:40:52 -08002951status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002952 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953{
2954 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002955 if (mEffectsFactoryHal.get()) {
2956 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2957 } else {
2958 return -ENODEV;
2959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960}
2961
2962
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002963sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 effect_descriptor_t *pDesc,
2965 const sp<IEffectClient>& effectClient,
2966 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002967 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002968 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002969 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002970 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 status_t *status,
2972 int *id,
2973 int *enabled)
2974{
2975 status_t lStatus = NO_ERROR;
2976 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978
Eric Laurentb6436272016-12-07 19:24:50 -08002979 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002980 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08002981 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2982 ALOGW_IF(pid != -1 && pid != callingPid,
2983 "%s uid %d pid %d tried to pass itself off as pid %d",
2984 __func__, callingUid, callingPid, pid);
2985 pid = callingPid;
2986 }
2987
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002988 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2989 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990
2991 if (pDesc == NULL) {
2992 lStatus = BAD_VALUE;
2993 goto Exit;
2994 }
2995
Eric Laurent84e9a102010-09-23 16:10:16 -07002996 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002997 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002998 lStatus = PERMISSION_DENIED;
2999 goto Exit;
3000 }
3001
Dima Zavinfce7a472011-04-19 22:30:36 -07003002 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003003 // that can only be created by audio policy manager
3004 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003005 lStatus = PERMISSION_DENIED;
3006 goto Exit;
3007 }
3008
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003009 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003010 lStatus = NO_INIT;
3011 goto Exit;
3012 }
3013
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003015 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003017 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003019 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020 goto Exit;
3021 }
3022 } else {
3023 // if uuid is not specified, look for an available implementation
3024 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003025 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003026 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 lStatus = BAD_VALUE;
3028 goto Exit;
3029 }
3030 uint32_t numEffects = 0;
3031 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003032 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033 bool found = false;
3034
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003035 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003037 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038 goto Exit;
3039 }
3040 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003041 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003043 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 continue;
3045 }
3046 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3047 // If matching type found save effect descriptor. If the session is
3048 // 0 and the effect is not auxiliary, continue enumeration in case
3049 // an auxiliary version of this effect type is available
3050 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003051 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003052 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3054 break;
3055 }
3056 }
3057 }
3058 if (!found) {
3059 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003060 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 goto Exit;
3062 }
3063 // For same effect type, chose auxiliary version over insert version if
3064 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003065 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003067 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003068 }
3069 }
3070
3071 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003072 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3074 lStatus = INVALID_OPERATION;
3075 goto Exit;
3076 }
3077
Eric Laurent59255e42011-07-27 19:49:51 -07003078 // check recording permission for visualizer
3079 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003080 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003081 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003082 lStatus = PERMISSION_DENIED;
3083 goto Exit;
3084 }
3085
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003087 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003088 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003089 // if the output returned by getOutputForEffect() is removed before we lock the
3090 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3091 // and we will exit safely
3092 io = AudioSystem::getOutputForEffect(&desc);
3093 ALOGV("createEffect got output %d", io);
3094 }
3095
3096 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097
3098 // If output is not specified try to find a matching audio session ID in one of the
3099 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003100 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3101 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003102 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003103 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003104 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3105 // output must be specified by AudioPolicyManager when using session
3106 // AUDIO_SESSION_OUTPUT_STAGE
3107 lStatus = BAD_VALUE;
3108 goto Exit;
3109 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003110 // look for the thread where the specified audio session is present
3111 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3112 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3113 io = mPlaybackThreads.keyAt(i);
3114 break;
3115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003117 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003118 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3119 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3120 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003121 break;
3122 }
3123 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003124 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003125 if (io == AUDIO_IO_HANDLE_NONE) {
3126 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3127 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3128 io = mMmapThreads.keyAt(i);
3129 break;
3130 }
3131 }
3132 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003133 // If no output thread contains the requested session ID, default to
3134 // first output. The effect chain will be moved to the correct output
3135 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003136 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003137 io = mPlaybackThreads.keyAt(0);
3138 }
Steve Block3856b092011-10-20 11:56:00 +01003139 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003140 }
3141 ThreadBase *thread = checkRecordThread_l(io);
3142 if (thread == NULL) {
3143 thread = checkPlaybackThread_l(io);
3144 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003145 thread = checkMmapThread_l(io);
3146 if (thread == NULL) {
3147 ALOGE("createEffect() unknown output thread");
3148 lStatus = BAD_VALUE;
3149 goto Exit;
3150 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003151 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003152 } else {
3153 // Check if one effect chain was awaiting for an effect to be created on this
3154 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003155 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003156 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003157 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003158 thread->addEffectChain_l(chain);
3159 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003161
Eric Laurent021cf962014-05-13 10:18:14 -07003162 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003164 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003165 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003166 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003167 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003168 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003169 // remove local strong reference to Client with mClientLock held
3170 Mutex::Autolock _cl(mClientLock);
3171 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003172 } else {
3173 // handle must be valid here, but check again to be safe.
3174 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003175 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 }
3177
haobo101735295ff7b0d2017-03-17 17:44:03 +08003178 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3179 // handle must be cleared outside lock.
3180 handle.clear();
3181 }
3182
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003184 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 return handle;
3186}
3187
Glenn Kastend848eb42016-03-08 13:42:11 -08003188status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003189 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003190{
Steve Block3856b092011-10-20 11:56:00 +01003191 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003192 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003193 Mutex::Autolock _l(mLock);
3194 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003195 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003196 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 }
Eric Laurentde070132010-07-13 04:45:46 -07003198 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3199 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003200 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003201 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202 }
Eric Laurentde070132010-07-13 04:45:46 -07003203 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3204 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003205 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003206 return BAD_VALUE;
3207 }
3208
3209 Mutex::Autolock _dl(dstThread->mLock);
3210 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003211 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212}
3213
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003214// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003215status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003216 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003217 AudioFlinger::PlaybackThread *dstThread,
3218 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003219{
Steve Block3856b092011-10-20 11:56:00 +01003220 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003221 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003222
Eric Laurent59255e42011-07-27 19:49:51 -07003223 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003224 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003225 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003226 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003227 return INVALID_OPERATION;
3228 }
3229
Eric Laurent4c415062016-06-17 16:14:16 -07003230 // Check whether the destination thread and all effects in the chain are compatible
3231 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003232 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003233 " destination thread %p is not compatible with effects in the chain",
3234 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003235 return INVALID_OPERATION;
3236 }
3237
Eric Laurent39e94f82010-07-28 01:32:47 -07003238 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003239 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003240 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003241 // removed.
3242 srcThread->removeEffectChain_l(chain);
3243
3244 // transfer all effects one by one so that new effect chain is created on new thread with
3245 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003246 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003247 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003248 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003249 Vector< sp<EffectModule> > removed;
3250 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003251 while (effect != 0) {
3252 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003253 removed.add(effect);
3254 status = dstThread->addEffect_l(effect);
3255 if (status != NO_ERROR) {
3256 break;
3257 }
Eric Laurentec35a142011-10-05 17:42:25 -07003258 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3259 if (effect->state() == EffectModule::ACTIVE ||
3260 effect->state() == EffectModule::STOPPING) {
3261 effect->start();
3262 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003263 // if the move request is not received from audio policy manager, the effect must be
3264 // re-registered with the new strategy and output
3265 if (dstChain == 0) {
3266 dstChain = effect->chain().promote();
3267 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003268 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003269 status = NO_INIT;
3270 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003271 }
3272 strategy = dstChain->strategy();
3273 }
3274 if (reRegister) {
3275 AudioSystem::unregisterEffect(effect->id());
3276 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003277 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003278 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003279 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003280 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003281 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003282 }
Eric Laurentde070132010-07-13 04:45:46 -07003283 effect = chain->getEffectFromId_l(0);
3284 }
3285
Eric Laurent5baf2af2013-09-12 17:37:00 -07003286 if (status != NO_ERROR) {
3287 for (size_t i = 0; i < removed.size(); i++) {
3288 srcThread->addEffect_l(removed[i]);
3289 if (dstChain != 0 && reRegister) {
3290 AudioSystem::unregisterEffect(removed[i]->id());
3291 AudioSystem::registerEffect(&removed[i]->desc(),
3292 srcThread->id(),
3293 strategy,
3294 sessionId,
3295 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003296 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003297 }
3298 }
3299 }
3300
3301 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302}
3303
Eric Laurent5baf2af2013-09-12 17:37:00 -07003304bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003305{
3306 if (mGlobalEffectEnableTime != 0 &&
3307 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3308 return true;
3309 }
3310
3311 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3312 sp<EffectChain> ec =
3313 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003314 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003315 return true;
3316 }
3317 }
3318 return false;
3319}
3320
Eric Laurent5baf2af2013-09-12 17:37:00 -07003321void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003322{
3323 Mutex::Autolock _l(mLock);
3324
3325 mGlobalEffectEnableTime = systemTime();
3326
3327 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3328 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3329 if (t->mType == ThreadBase::OFFLOAD) {
3330 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3331 }
3332 }
3333
3334}
3335
Eric Laurentaaa44472014-09-12 17:41:50 -07003336status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3337{
Eric Laurentd8365c52017-07-16 15:27:05 -07003338 // clear possible suspended state before parking the chain so that it starts in default state
3339 // when attached to a new record thread
3340 chain->setEffectSuspended_l(FX_IID_AEC, false);
3341 chain->setEffectSuspended_l(FX_IID_NS, false);
3342
Glenn Kastend848eb42016-03-08 13:42:11 -08003343 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003344 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003345 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003346 if (index >= 0) {
3347 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3348 return ALREADY_EXISTS;
3349 }
3350 mOrphanEffectChains.add(session, chain);
3351 return NO_ERROR;
3352}
3353
3354sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3355{
3356 sp<EffectChain> chain;
3357 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003358 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003359 if (index >= 0) {
3360 chain = mOrphanEffectChains.valueAt(index);
3361 mOrphanEffectChains.removeItemsAt(index);
3362 }
3363 return chain;
3364}
3365
3366bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3367{
3368 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003369 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003370 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003371 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003372 if (index >= 0) {
3373 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003374 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003375 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003376 mOrphanEffectChains.removeItemsAt(index);
3377 }
3378 return true;
3379 }
3380 return false;
3381}
3382
3383
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384// ----------------------------------------------------------------------------
3385
3386status_t AudioFlinger::onTransact(
3387 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3388{
3389 return BnAudioFlinger::onTransact(code, data, reply, flags);
3390}
3391
Glenn Kasten63238ef2015-03-02 15:50:29 -08003392} // namespace android