blob: ed2b3c0e00d31c50c6853e15c78a436a161c1c77 [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 Tan1882f162018-08-02 18:05:39 -070061#include <json/json.h>
62
Eric Laurentfeb0db62011-07-22 09:04:31 -070063#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080064
Glenn Kasten9e58b552013-01-18 15:09:48 -080065#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070066#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080067#include <media/nbaio/Pipe.h>
68#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070070#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070071#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080072
rago3bd1c872016-09-26 12:58:14 -070073//#define BUFLOG_NDEBUG 0
74#include <BufLog.h>
75
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080076#include "TypedLogger.h"
77
Mathias Agopian65ab4712010-07-14 17:59:35 -070078// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
John Grossman1c345192012-03-27 14:00:17 -070080// Note: the following macro is used for extremely verbose logging message. In
81// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
82// 0; but one side effect of this is to turn all LOGV's as well. Some messages
83// are so verbose that we want to suppress them even when we have ALOG_ASSERT
84// turned on. Do not uncomment the #def below unless you really know what you
85// are doing and want to see all of the extremely verbose messages.
86//#define VERY_VERY_VERBOSE_LOGGING
87#ifdef VERY_VERY_VERBOSE_LOGGING
88#define ALOGVV ALOGV
89#else
90#define ALOGVV(a...) do { } while(0)
91#endif
Eric Laurentde070132010-07-13 04:45:46 -070092
Mathias Agopian65ab4712010-07-14 17:59:35 -070093namespace android {
94
Glenn Kastenec1d6b52011-12-12 09:04:45 -080095static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
96static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070097static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070098static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070099
Glenn Kasten58912562012-04-03 10:45:00 -0700100
John Grossman4ff14ba2012-02-08 16:37:41 -0800101nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800102
Eric Laurent81784c32012-11-19 14:55:58 -0800103uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700104
Eric Laurent813e2a72013-08-31 12:59:48 -0700105// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
106// we define a minimum time during which a global effect is considered enabled.
107static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
108
Eric Laurentfc235202016-12-20 18:48:17 -0800109Mutex gLock;
110wp<AudioFlinger> gAudioFlinger;
111
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700112// Keep a strong reference to media.log service around forever.
113// The service is within our parent process so it can never die in a way that we could observe.
114// These two variables are const after initialization.
115static sp<IBinder> sMediaLogServiceAsBinder;
116static sp<IMediaLogService> sMediaLogService;
117
118static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
119
120static void sMediaLogInit()
121{
122 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
123 if (sMediaLogServiceAsBinder != 0) {
124 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
125 }
126}
127
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128// ----------------------------------------------------------------------------
129
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700130std::string formatToString(audio_format_t format) {
131 std::string result;
132 FormatConverter::toString(format, result);
133 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800134}
135
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136// ----------------------------------------------------------------------------
137
138AudioFlinger::AudioFlinger()
139 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800140 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800141 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800142 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700143 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800144 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800145 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700146 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800147 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700148 mBtNrecIsOff(false),
149 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700150 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800151 mTotalMemory(0),
152 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700153 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700154 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700155 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700156{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700157 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
158 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
159 // zero ID has a special meaning, so unavailable
160 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
161 }
162
Glenn Kastenae0cff12016-02-24 13:57:49 -0800163 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800164 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800165 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
166 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700167 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800168 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700169
Wei Jia3f273d12015-11-24 09:06:49 -0800170 // reset battery stats.
171 // if the audio service has crashed, battery stats could be left
172 // in bad state, reset the state upon service start.
173 BatteryNotifier::getInstance().noteResetAudio();
174
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700175 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700176 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
177
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800178 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700179}
180
181void AudioFlinger::onFirstRef()
182{
Eric Laurent93575202011-01-18 18:39:02 -0800183 Mutex::Autolock _l(mLock);
184
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800186 char val_str[PROPERTY_VALUE_MAX] = { 0 };
187 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
188 uint32_t int_val;
189 if (1 == sscanf(val_str, "%u", &int_val)) {
190 mStandbyTimeInNsecs = milliseconds(int_val);
191 ALOGI("Using %u mSec as standby time.", int_val);
192 } else {
193 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
194 ALOGI("Using default %u mSec as standby time.",
195 (uint32_t)(mStandbyTimeInNsecs / 1000000));
196 }
197 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700198
Eric Laurenta4c5a552012-03-29 10:12:40 -0700199 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800200
201 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700202}
203
204AudioFlinger::~AudioFlinger()
205{
206 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700207 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700208 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700209 }
210 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700211 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700212 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700213 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700214
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800215 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
216 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700217 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700218 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700219
220 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700221 if (sMediaLogService != 0) {
222 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
223 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
224 mUnregisteredWriters.pop();
225 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700226 }
227 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228}
229
Eric Laurentfc235202016-12-20 18:48:17 -0800230//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800231__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800232status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
233 const audio_attributes_t *attr,
234 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700235 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800236 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800237 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800238 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700239 sp<MmapStreamInterface>& interface,
240 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800241{
242 sp<AudioFlinger> af;
243 {
244 Mutex::Autolock _l(gLock);
245 af = gAudioFlinger.promote();
246 }
247 status_t ret = NO_INIT;
248 if (af != 0) {
249 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800250 direction, attr, config, client, deviceId,
251 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800252 }
253 return ret;
254}
255
Eric Laurent6acd1d42017-01-04 14:23:29 -0800256status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
257 const audio_attributes_t *attr,
258 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700259 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800260 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800261 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800262 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700263 sp<MmapStreamInterface>& interface,
264 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800265{
266 status_t ret = initCheck();
267 if (ret != NO_ERROR) {
268 return ret;
269 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800270 audio_session_t actualSessionId = *sessionId;
271 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
272 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
273 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800274 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700275 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800276 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
277 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
278 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
279 fullConfig.sample_rate = config->sample_rate;
280 fullConfig.channel_mask = config->channel_mask;
281 fullConfig.format = config->format;
282 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800283 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200284 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800285 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800286 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
287 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700288 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800289 } else {
290 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800291 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800292 client.clientPid,
293 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800294 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800295 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700296 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800297 }
298 if (ret != NO_ERROR) {
299 return ret;
300 }
301
302 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
303 // audio policy manager and we can retrieve it
304 sp<MmapThread> thread = mMmapThreads.valueFor(io);
305 if (thread != 0) {
306 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800307 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700308 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800309 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800310 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700311 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700312 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700313 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800314 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700315 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800316 ret = NO_INIT;
317 }
318
319 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
320
Eric Laurentfc235202016-12-20 18:48:17 -0800321 return ret;
322}
323
Eric Laurenta4c5a552012-03-29 10:12:40 -0700324static const char * const audio_interfaces[] = {
325 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
326 AUDIO_HARDWARE_MODULE_ID_A2DP,
327 AUDIO_HARDWARE_MODULE_ID_USB,
328};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700329
Phil Burk062e67a2015-02-11 13:40:50 -0800330AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700331 audio_module_handle_t module,
332 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700333{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700334 // if module is 0, the request comes from an old policy manager and we should load
335 // well known modules
336 if (module == 0) {
337 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700338 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700339 loadHwModule_l(audio_interfaces[i]);
340 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700341 // then try to find a module supporting the requested device.
342 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
343 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700344 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
345 uint32_t supportedDevices;
346 if (dev->getSupportedDevices(&supportedDevices) == OK &&
347 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700348 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700349 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700350 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700351 } else {
352 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700353 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
354 if (audioHwDevice != NULL) {
355 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700356 }
357 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700358
Dima Zavin799a70e2011-04-18 16:57:27 -0700359 return NULL;
360}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361
Glenn Kasten0f11b512014-01-31 16:18:54 -0800362void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363{
364 const size_t SIZE = 256;
365 char buffer[SIZE];
366 String8 result;
367
368 result.append("Clients:\n");
369 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800370 sp<Client> client = mClients.valueAt(i).promote();
371 if (client != 0) {
372 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
373 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700374 }
375 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700376
Eric Laurentd1b28d42013-09-18 18:47:13 -0700377 result.append("Notification Clients:\n");
378 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
379 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
380 result.append(buffer);
381 }
382
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700383 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800384 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700385 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
386 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800387 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700388 result.append(buffer);
389 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700391}
392
393
Glenn Kasten0f11b512014-01-31 16:18:54 -0800394void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395{
396 const size_t SIZE = 256;
397 char buffer[SIZE];
398 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800399 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400
John Grossman4ff14ba2012-02-08 16:37:41 -0800401 snprintf(buffer, SIZE, "Hardware status: %d\n"
402 "Standby Time mSec: %u\n",
403 hardwareStatus,
404 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 result.append(buffer);
406 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407}
408
Glenn Kasten0f11b512014-01-31 16:18:54 -0800409void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410{
411 const size_t SIZE = 256;
412 char buffer[SIZE];
413 String8 result;
414 snprintf(buffer, SIZE, "Permission Denial: "
415 "can't dump AudioFlinger from pid=%d, uid=%d\n",
416 IPCThreadState::self()->getCallingPid(),
417 IPCThreadState::self()->getCallingUid());
418 result.append(buffer);
419 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420}
421
Eric Laurent81784c32012-11-19 14:55:58 -0800422bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700423{
424 bool locked = false;
425 for (int i = 0; i < kDumpLockRetries; ++i) {
426 if (mutex.tryLock() == NO_ERROR) {
427 locked = true;
428 break;
429 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800430 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 }
432 return locked;
433}
434
435status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
436{
Glenn Kasten44deb052012-02-05 18:09:08 -0800437 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 dumpPermissionDenial(fd, args);
439 } else {
Eric Tan7b651152018-07-13 10:17:19 -0700440 // XXX This is sort of hacky for now.
441 const bool formatJson = std::any_of(args.begin(), args.end(),
442 [](const String16 &arg) { return arg == String16("--json"); });
443 if (formatJson) {
Eric Tan1882f162018-08-02 18:05:39 -0700444 Json::Value root = getJsonDump();
445 Json::FastWriter writer;
446 std::string rootStr = writer.write(root);
Eric Tan7b651152018-07-13 10:17:19 -0700447 // XXX consider buffering if the string happens to be too long.
Eric Tan1882f162018-08-02 18:05:39 -0700448 dprintf(fd, "%s", rootStr.c_str());
Eric Tan7b651152018-07-13 10:17:19 -0700449 return NO_ERROR;
450 }
451
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800453 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 if (!hardwareLocked) {
455 String8 result(kHardwareLockedString);
456 write(fd, result.string(), result.size());
457 } else {
458 mHardwareLock.unlock();
459 }
460
Eric Tan7b651152018-07-13 10:17:19 -0700461 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462
463 // failed to lock - AudioFlinger is probably deadlocked
464 if (!locked) {
465 String8 result(kDeadlockedString);
466 write(fd, result.string(), result.size());
467 }
468
Eric Laurent021cf962014-05-13 10:18:14 -0700469 bool clientLocked = dumpTryLock(mClientLock);
470 if (!clientLocked) {
471 String8 result(kClientLockedString);
472 write(fd, result.string(), result.size());
473 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700474
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700475 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700476 mEffectsFactoryHal->dumpEffects(fd);
477 } else {
478 String8 result(kNoEffectsFactory);
479 write(fd, result.string(), result.size());
480 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700481
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700483 if (clientLocked) {
484 mClientLock.unlock();
485 }
486
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 dumpInternals(fd, args);
488
489 // dump playback threads
490 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
491 mPlaybackThreads.valueAt(i)->dump(fd, args);
492 }
493
494 // dump record threads
495 for (size_t i = 0; i < mRecordThreads.size(); i++) {
496 mRecordThreads.valueAt(i)->dump(fd, args);
497 }
498
Eric Laurent6acd1d42017-01-04 14:23:29 -0800499 // dump mmap threads
500 for (size_t i = 0; i < mMmapThreads.size(); i++) {
501 mMmapThreads.valueAt(i)->dump(fd, args);
502 }
503
Eric Laurentaaa44472014-09-12 17:41:50 -0700504 // dump orphan effect chains
505 if (mOrphanEffectChains.size() != 0) {
506 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
507 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
508 mOrphanEffectChains.valueAt(i)->dump(fd, args);
509 }
510 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700511 // dump all hardware devs
512 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700513 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
514 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700516
Mikhail Naganov201369b2018-05-16 16:52:32 -0700517 mPatchPanel.dump(fd);
518
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700519 // dump external setParameters
520 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
521 dprintf(fd, "\n%s setParameters:\n", name);
522 logger.dump(fd, " " /* prefix */);
523 };
524 dumpLogger(mRejectedSetParameterLog, "Rejected");
525 dumpLogger(mAppSetParameterLog, "App");
526 dumpLogger(mSystemSetParameterLog, "System");
527
rago3bd1c872016-09-26 12:58:14 -0700528 BUFLOG_RESET;
529
Glenn Kastend65d73c2012-06-22 17:21:07 -0700530 if (locked) {
531 mLock.unlock();
532 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800533
Andy Hung8946a282018-04-19 20:04:56 -0700534#ifdef TEE_SINK
535 // NBAIO_Tee dump is safe to call outside of AF lock.
536 NBAIO_Tee::dumpAll(fd, "_DUMP");
537#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800538 // append a copy of media.log here by forwarding fd to it, but don't attempt
539 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700540 if (sMediaLogServiceAsBinder != 0) {
541 dprintf(fd, "\nmedia.log:\n");
542 Vector<String16> args;
543 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800544 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700545
546 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700547 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700548 bool unreachableMemory = false;
549 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700550 if (arg == String16("-m")) {
551 dumpMem = true;
552 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700553 unreachableMemory = true;
554 }
555 }
556
Andy Hung07b745e2016-05-23 16:21:07 -0700557 if (dumpMem) {
558 dprintf(fd, "\nDumping memory:\n");
559 std::string s = dumpMemoryAddresses(100 /* limit */);
560 write(fd, s.c_str(), s.size());
561 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700562 if (unreachableMemory) {
563 dprintf(fd, "\nDumping unreachable memory:\n");
564 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700565 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700566 write(fd, s.c_str(), s.size());
567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 }
569 return NO_ERROR;
570}
571
Eric Tan1882f162018-08-02 18:05:39 -0700572Json::Value AudioFlinger::getJsonDump()
Eric Tan7b651152018-07-13 10:17:19 -0700573{
Eric Tan1882f162018-08-02 18:05:39 -0700574 Json::Value root(Json::objectValue);
Eric Tan7b651152018-07-13 10:17:19 -0700575 const bool locked = dumpTryLock(mLock);
576
577 // failed to lock - AudioFlinger is probably deadlocked
578 if (!locked) {
Eric Tan1882f162018-08-02 18:05:39 -0700579 root["deadlock_message"] = kDeadlockedString;
Eric Tan7b651152018-07-13 10:17:19 -0700580 }
581 // FIXME risky to access data structures without a lock held?
582
Eric Tan1882f162018-08-02 18:05:39 -0700583 Json::Value playbackThreads = Json::arrayValue;
Eric Tan7b651152018-07-13 10:17:19 -0700584 // dump playback threads
585 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Tan1882f162018-08-02 18:05:39 -0700586 playbackThreads.append(mPlaybackThreads.valueAt(i)->getJsonDump());
Eric Tan7b651152018-07-13 10:17:19 -0700587 }
Eric Tan7b651152018-07-13 10:17:19 -0700588
589 if (locked) {
590 mLock.unlock();
591 }
592
Eric Tan1882f162018-08-02 18:05:39 -0700593 root["playback_threads"] = playbackThreads;
594
595 return root;
Eric Tan7b651152018-07-13 10:17:19 -0700596}
597
Eric Laurent021cf962014-05-13 10:18:14 -0700598sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800599{
Eric Laurent021cf962014-05-13 10:18:14 -0700600 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800601 // If pid is already in the mClients wp<> map, then use that entry
602 // (for which promote() is always != 0), otherwise create a new entry and Client.
603 sp<Client> client = mClients.valueFor(pid).promote();
604 if (client == 0) {
605 client = new Client(this, pid);
606 mClients.add(pid, client);
607 }
608
609 return client;
610}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611
Glenn Kasten9e58b552013-01-18 15:09:48 -0800612sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
613{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700614 // If there is no memory allocated for logs, return a dummy writer that does nothing.
615 // Similarly if we can't contact the media.log service, also return a dummy writer.
616 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800617 return new NBLog::Writer();
618 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700619 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
620 // If allocation fails, consult the vector of previously unregistered writers
621 // and garbage-collect one or more them until an allocation succeeds
622 if (shared == 0) {
623 Mutex::Autolock _l(mUnregisteredWritersLock);
624 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
625 {
626 // Pick the oldest stale writer to garbage-collect
627 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
628 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700629 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700630 // Now the media.log remote reference to IMemory is gone. When our last local
631 // reference to IMemory also drops to zero at end of this block,
632 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
633 }
634 // Re-attempt the allocation
635 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
636 if (shared != 0) {
637 goto success;
638 }
639 }
640 // Even after garbage-collecting all old writers, there is still not enough memory,
641 // so return a dummy writer
642 return new NBLog::Writer();
643 }
644success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800645 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
646 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
647 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700648 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800649 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800650}
651
652void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
653{
Glenn Kasten685ef092013-02-04 08:15:34 -0800654 if (writer == 0) {
655 return;
656 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800657 sp<IMemory> iMemory(writer->getIMemory());
658 if (iMemory == 0) {
659 return;
660 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700661 // Rather than removing the writer immediately, append it to a queue of old writers to
662 // be garbage-collected later. This allows us to continue to view old logs for a while.
663 Mutex::Autolock _l(mUnregisteredWritersLock);
664 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800665}
666
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667// IAudioFlinger interface
668
Eric Laurent21da6472017-11-09 16:29:26 -0800669sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
670 CreateTrackOutput& output,
671 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672{
673 sp<PlaybackThread::Track> track;
674 sp<TrackHandle> trackHandle;
675 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800677 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800678 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679
Eric Laurent21da6472017-11-09 16:29:26 -0800680 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700681 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800682 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700683 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800684 ALOGW_IF(clientUid != callingUid,
685 "%s uid %d tried to pass itself off as %d",
686 __FUNCTION__, callingUid, clientUid);
687 clientUid = callingUid;
688 updatePid = true;
689 }
690 pid_t clientPid = input.clientInfo.clientPid;
691 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700692 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800693 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700694 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800695 __func__, callingUid, callingPid, clientPid);
696 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700697 }
698
Eric Laurent21da6472017-11-09 16:29:26 -0800699 audio_session_t sessionId = input.sessionId;
700 if (sessionId == AUDIO_SESSION_ALLOCATE) {
701 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800702 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
703 lStatus = BAD_VALUE;
704 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800705 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800706
Eric Laurent21da6472017-11-09 16:29:26 -0800707 output.sessionId = sessionId;
708 output.outputId = AUDIO_IO_HANDLE_NONE;
709 output.selectedDeviceId = input.selectedDeviceId;
710
711 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200712 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800713 &output.selectedDeviceId, &portId);
714
715 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
716 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
717 goto Exit;
718 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800719 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
720 // but if someone uses binder directly they could bypass that and cause us to crash
721 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000722 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 lStatus = BAD_VALUE;
724 goto Exit;
725 }
726
Glenn Kasten53b5d092014-02-05 10:00:23 -0800727 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800728 if (!audio_is_output_channel(input.config.channel_mask)) {
729 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800730 lStatus = BAD_VALUE;
731 goto Exit;
732 }
733
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700734 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800735 if (!audio_is_valid_format(input.config.format)) {
736 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700737 lStatus = BAD_VALUE;
738 goto Exit;
739 }
740
Mathias Agopian65ab4712010-07-14 17:59:35 -0700741 {
742 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800743 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800745 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 lStatus = BAD_VALUE;
747 goto Exit;
748 }
749
Eric Laurent21da6472017-11-09 16:29:26 -0800750 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751
Glenn Kastene848bd92014-03-13 15:00:32 -0700752 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800753 // check if an effect chain with the same session ID is present on another
754 // output thread and move it here.
755 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
756 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
757 if (mPlaybackThreads.keyAt(i) != output.outputId) {
758 uint32_t sessions = t->hasAudioSession(sessionId);
759 if (sessions & ThreadBase::EFFECT_SESSION) {
760 effectThread = t.get();
761 break;
Eric Laurentde070132010-07-13 04:45:46 -0700762 }
763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 }
Eric Laurent21da6472017-11-09 16:29:26 -0800765 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766
Eric Laurent21da6472017-11-09 16:29:26 -0800767 output.sampleRate = input.config.sample_rate;
768 output.frameCount = input.frameCount;
769 output.notificationFrameCount = input.notificationFrameCount;
770 output.flags = input.flags;
771
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700772 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
773 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800774 &output.frameCount, &output.notificationFrameCount,
775 input.notificationsPerBuffer, input.speed,
776 input.sharedBuffer, sessionId, &output.flags,
777 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800778 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700779 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700780
Eric Laurent21da6472017-11-09 16:29:26 -0800781 output.afFrameCount = thread->frameCount();
782 output.afSampleRate = thread->sampleRate();
783 output.afLatencyMs = thread->latency();
784
Eric Laurent39e94f82010-07-28 01:32:47 -0700785 // move effect chain to this output thread if an effect on same session was waiting
786 // for a track to be created
787 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700788 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700789 Mutex::Autolock _dl(thread->mLock);
790 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800791 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700792 }
Eric Laurenta011e352012-03-29 15:51:43 -0700793
794 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700795 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800796 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700797 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700798 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700799 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700800 } else {
801 mPendingSyncEvents[i]->cancel();
802 }
Eric Laurenta011e352012-03-29 15:51:43 -0700803 mPendingSyncEvents.removeAt(i);
804 i--;
805 }
806 }
807 }
Glenn Kastene198c362013-08-13 09:13:36 -0700808
Eric Laurent21da6472017-11-09 16:29:26 -0800809 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
Glenn Kastene198c362013-08-13 09:13:36 -0700811
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700812 if (lStatus != NO_ERROR) {
813 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700814 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700815 // Don't hold mClientLock when releasing the reference on the track as the
816 // destructor will acquire it.
817 {
818 Mutex::Autolock _cl(mClientLock);
819 client.clear();
820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700822 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 }
824
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700825 // return handle to client
826 trackHandle = new TrackHandle(track);
827
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800829 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700830 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800831 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700832 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return trackHandle;
834}
835
Glenn Kasten2c073da2016-02-26 09:14:08 -0800836uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837{
838 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800839 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800841 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 return 0;
843 }
844 return thread->sampleRate();
845}
846
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800847audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848{
849 Mutex::Autolock _l(mLock);
850 PlaybackThread *thread = checkPlaybackThread_l(output);
851 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000852 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800853 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 }
855 return thread->format();
856}
857
Glenn Kasten2c073da2016-02-26 09:14:08 -0800858size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859{
860 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800861 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800863 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 return 0;
865 }
Glenn Kasten58912562012-04-03 10:45:00 -0700866 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
867 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 return thread->frameCount();
869}
870
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700871size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
872{
873 Mutex::Autolock _l(mLock);
874 ThreadBase *thread = checkThread_l(ioHandle);
875 if (thread == NULL) {
876 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
877 return 0;
878 }
879 return thread->frameCountHAL();
880}
881
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800882uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883{
884 Mutex::Autolock _l(mLock);
885 PlaybackThread *thread = checkPlaybackThread_l(output);
886 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800887 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 return 0;
889 }
890 return thread->latency();
891}
892
893status_t AudioFlinger::setMasterVolume(float value)
894{
Eric Laurenta1884f92011-08-23 08:25:03 -0700895 status_t ret = initCheck();
896 if (ret != NO_ERROR) {
897 return ret;
898 }
899
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900 // check calling permissions
901 if (!settingsAllowed()) {
902 return PERMISSION_DENIED;
903 }
904
Eric Laurenta4c5a552012-03-29 10:12:40 -0700905 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700906 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700907
John Grossmanee578c02012-07-23 17:05:46 -0700908 // Set master volume in the HALs which support it.
909 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
910 AutoMutex lock(mHardwareLock);
911 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800912
John Grossmanee578c02012-07-23 17:05:46 -0700913 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
914 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700915 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800916 }
John Grossmanee578c02012-07-23 17:05:46 -0700917 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919
John Grossmanee578c02012-07-23 17:05:46 -0700920 // Now set the master volume in each playback thread. Playback threads
921 // assigned to HALs which do not have master volume support will apply
922 // master volume during the mix operation. Threads with HALs which do
923 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700924 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
925 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
926 continue;
927 }
John Grossmanee578c02012-07-23 17:05:46 -0700928 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700929 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930
931 return NO_ERROR;
932}
933
Glenn Kastenf78aee72012-01-04 11:00:47 -0800934status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935{
Eric Laurenta1884f92011-08-23 08:25:03 -0700936 status_t ret = initCheck();
937 if (ret != NO_ERROR) {
938 return ret;
939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940
941 // check calling permissions
942 if (!settingsAllowed()) {
943 return PERMISSION_DENIED;
944 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800945 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000946 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 return BAD_VALUE;
948 }
949
950 { // scope for the lock
951 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700952 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700954 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 mHardwareStatus = AUDIO_HW_IDLE;
956 }
957
958 if (NO_ERROR == ret) {
959 Mutex::Autolock _l(mLock);
960 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800961 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700962 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 }
964
965 return ret;
966}
967
968status_t AudioFlinger::setMicMute(bool state)
969{
Eric Laurenta1884f92011-08-23 08:25:03 -0700970 status_t ret = initCheck();
971 if (ret != NO_ERROR) {
972 return ret;
973 }
974
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 // check calling permissions
976 if (!settingsAllowed()) {
977 return PERMISSION_DENIED;
978 }
979
980 AutoMutex lock(mHardwareLock);
981 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700982 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700983 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
984 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700985 if (result != NO_ERROR) {
986 ret = result;
987 }
988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 mHardwareStatus = AUDIO_HW_IDLE;
990 return ret;
991}
992
993bool AudioFlinger::getMicMute() const
994{
Eric Laurenta1884f92011-08-23 08:25:03 -0700995 status_t ret = initCheck();
996 if (ret != NO_ERROR) {
997 return false;
998 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800999 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001000 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001001 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001003 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001004 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1005 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001006 if (result == NO_ERROR) {
1007 mute = mute && state;
1008 }
1009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001011
1012 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013}
1014
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001015void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1016{
1017 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1018
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001019 AutoMutex lock(mLock);
1020 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001021 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1022 }
1023 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1024 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001025 }
1026}
1027
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028status_t AudioFlinger::setMasterMute(bool muted)
1029{
John Grossmand8f178d2012-07-20 14:51:35 -07001030 status_t ret = initCheck();
1031 if (ret != NO_ERROR) {
1032 return ret;
1033 }
1034
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 // check calling permissions
1036 if (!settingsAllowed()) {
1037 return PERMISSION_DENIED;
1038 }
1039
John Grossmanee578c02012-07-23 17:05:46 -07001040 Mutex::Autolock _l(mLock);
1041 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001042
John Grossmanee578c02012-07-23 17:05:46 -07001043 // Set master mute in the HALs which support it.
1044 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1045 AutoMutex lock(mHardwareLock);
1046 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001047
John Grossmanee578c02012-07-23 17:05:46 -07001048 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1049 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001050 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001051 }
John Grossmanee578c02012-07-23 17:05:46 -07001052 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001053 }
1054
John Grossmanee578c02012-07-23 17:05:46 -07001055 // Now set the master mute in each playback thread. Playback threads
1056 // assigned to HALs which do not have master mute support will apply master
1057 // mute during the mix operation. Threads with HALs which do support master
1058 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001059 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1060 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1061 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063
1064 return NO_ERROR;
1065}
1066
1067float AudioFlinger::masterVolume() const
1068{
Glenn Kasten98067102011-12-13 11:47:54 -08001069 Mutex::Autolock _l(mLock);
1070 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071}
1072
1073bool AudioFlinger::masterMute() const
1074{
Glenn Kasten98067102011-12-13 11:47:54 -08001075 Mutex::Autolock _l(mLock);
1076 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077}
1078
John Grossman4ff14ba2012-02-08 16:37:41 -08001079float AudioFlinger::masterVolume_l() const
1080{
John Grossman4ff14ba2012-02-08 16:37:41 -08001081 return mMasterVolume;
1082}
1083
John Grossmand8f178d2012-07-20 14:51:35 -07001084bool AudioFlinger::masterMute_l() const
1085{
John Grossmanee578c02012-07-23 17:05:46 -07001086 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001087}
1088
Eric Laurent223fd5c2014-11-11 13:43:36 -08001089status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1090{
1091 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001092 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001093 return BAD_VALUE;
1094 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001095 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1096 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1097 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001098 return PERMISSION_DENIED;
1099 }
1100
1101 return NO_ERROR;
1102}
1103
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001104status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1105 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106{
1107 // check calling permissions
1108 if (!settingsAllowed()) {
1109 return PERMISSION_DENIED;
1110 }
1111
Eric Laurent223fd5c2014-11-11 13:43:36 -08001112 status_t status = checkStreamType(stream);
1113 if (status != NO_ERROR) {
1114 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 }
Eric Laurent98e38192018-02-15 18:31:53 -08001116 if (output == AUDIO_IO_HANDLE_NONE) {
1117 return BAD_VALUE;
1118 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001119 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120
1121 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001122 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1123 if (volumeInterface == NULL) {
1124 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 }
Eric Laurent98e38192018-02-15 18:31:53 -08001126 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127
1128 return NO_ERROR;
1129}
1130
Glenn Kastenfff6d712012-01-12 16:38:12 -08001131status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132{
1133 // check calling permissions
1134 if (!settingsAllowed()) {
1135 return PERMISSION_DENIED;
1136 }
1137
Eric Laurent223fd5c2014-11-11 13:43:36 -08001138 status_t status = checkStreamType(stream);
1139 if (status != NO_ERROR) {
1140 return status;
1141 }
1142 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1143
1144 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001145 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 return BAD_VALUE;
1147 }
1148
Eric Laurent93575202011-01-18 18:39:02 -08001149 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001151 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1152 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1153 volumeInterfaces[i]->setStreamMute(stream, muted);
1154 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155
1156 return NO_ERROR;
1157}
1158
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001159float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001161 status_t status = checkStreamType(stream);
1162 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 return 0.0f;
1164 }
Eric Laurent98e38192018-02-15 18:31:53 -08001165 if (output == AUDIO_IO_HANDLE_NONE) {
1166 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 }
1168
Eric Laurent98e38192018-02-15 18:31:53 -08001169 AutoMutex lock(mLock);
1170 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1171 if (volumeInterface == NULL) {
1172 return 0.0f;
1173 }
1174
1175 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176}
1177
Glenn Kastenfff6d712012-01-12 16:38:12 -08001178bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001180 status_t status = checkStreamType(stream);
1181 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 return true;
1183 }
1184
Glenn Kasten6637baa2012-01-09 09:40:36 -08001185 AutoMutex lock(mLock);
1186 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187}
1188
Eric Laurent054d9d32015-04-24 08:48:48 -07001189
1190void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1191{
1192 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1193 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1194 }
1195}
1196
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001197// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1198void AudioFlinger::forwardParametersToDownstreamPatches_l(
1199 audio_io_handle_t upStream, const String8& keyValuePairs,
1200 std::function<bool(const sp<PlaybackThread>&)> useThread)
1201{
1202 std::vector<PatchPanel::SoftwarePatch> swPatches;
1203 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1204 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1205 __func__, swPatches.size(), upStream);
1206 for (const auto& swPatch : swPatches) {
1207 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1208 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1209 downStream->setParameters(keyValuePairs);
1210 }
1211 }
1212}
1213
Eric Laurentf1047e82018-04-16 19:18:20 -07001214// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1215// Some keys are used for audio routing and audio path configuration and should be reserved for use
1216// by audio policy and audio flinger for functional, privacy and security reasons.
1217void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1218{
1219 static const String8 kReservedParameters[] = {
1220 String8(AudioParameter::keyRouting),
1221 String8(AudioParameter::keySamplingRate),
1222 String8(AudioParameter::keyFormat),
1223 String8(AudioParameter::keyChannels),
1224 String8(AudioParameter::keyFrameCount),
1225 String8(AudioParameter::keyInputSource),
1226 String8(AudioParameter::keyMonoOutput),
1227 String8(AudioParameter::keyStreamConnect),
1228 String8(AudioParameter::keyStreamDisconnect),
1229 String8(AudioParameter::keyStreamSupportedFormats),
1230 String8(AudioParameter::keyStreamSupportedChannels),
1231 String8(AudioParameter::keyStreamSupportedSamplingRates),
1232 };
1233
Andy Hung4ef19fa2018-05-15 19:35:29 -07001234 if (isAudioServerUid(callingUid)) {
1235 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001236 }
1237
1238 AudioParameter param = AudioParameter(keyValuePairs);
1239 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001240 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001241 for (auto& key : kReservedParameters) {
1242 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001243 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001244 param.remove(key);
1245 }
1246 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001247 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1248 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001249 keyValuePairs = param.toString();
1250}
1251
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001252void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1253 size_t rejectedKVPSize, const String8& rejectedKVPs,
1254 uid_t callingUid) {
1255 auto prefix = String8::format("UID %5d", callingUid);
1256 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1257 if (rejectedKVPSize != 0) {
1258 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1259 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1260 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1261 } else {
1262 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1263 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1264 }
1265}
1266
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001267status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268{
Eric Laurentf1047e82018-04-16 19:18:20 -07001269 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1270 ioHandle, keyValuePairs.string(),
1271 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001272
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273 // check calling permissions
1274 if (!settingsAllowed()) {
1275 return PERMISSION_DENIED;
1276 }
1277
Eric Laurentf1047e82018-04-16 19:18:20 -07001278 String8 filteredKeyValuePairs = keyValuePairs;
1279 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1280
1281 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1282
Glenn Kasten142f5192014-03-25 17:44:59 -07001283 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1284 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001285 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001286 // result will remain NO_INIT if no audio device is present
1287 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001288 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001289 AutoMutex lock(mHardwareLock);
1290 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1291 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001292 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001293 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001294 // return success if at least one audio device accepts the parameters as not all
1295 // HALs are requested to support all parameters. If no audio device supports the
1296 // requested parameters, the last error is reported.
1297 if (final_result != NO_ERROR) {
1298 final_result = result;
1299 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001300 }
1301 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001302 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001303 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001304 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001305 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001306 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1307 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001308 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001309 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001310 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001311 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001312 }
1313 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001314 String8 screenState;
1315 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001316 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001317 if (isOff != (AudioFlinger::mScreenState & 1)) {
1318 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001319 }
1320 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001321 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322 }
1323
1324 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1325 // and the thread is exited once the lock is released
1326 sp<ThreadBase> thread;
1327 {
1328 Mutex::Autolock _l(mLock);
1329 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001330 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001332 if (thread == 0) {
1333 thread = checkMmapThread_l(ioHandle);
1334 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001335 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001336 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001337 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001338 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001339 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1340 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001341 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001342 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001343 }
1344 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001345 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001346 status_t result = thread->setParameters(filteredKeyValuePairs);
1347 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1348 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001349 }
1350 return BAD_VALUE;
1351}
1352
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001353String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001355 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1356 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001357
Eric Laurenta4c5a552012-03-29 10:12:40 -07001358 Mutex::Autolock _l(mLock);
1359
Glenn Kasten142f5192014-03-25 17:44:59 -07001360 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001361 String8 out_s8;
1362
Dima Zavin799a70e2011-04-18 16:57:27 -07001363 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001364 String8 s;
1365 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001366 {
1367 AutoMutex lock(mHardwareLock);
1368 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001369 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1370 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001371 mHardwareStatus = AUDIO_HW_IDLE;
1372 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001373 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001374 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001375 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001376 }
1377
Eric Laurent6acd1d42017-01-04 14:23:29 -08001378 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1379 if (thread == NULL) {
1380 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1381 if (thread == NULL) {
1382 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1383 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001384 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001385 }
1386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001388 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389}
1390
Glenn Kastendd8104c2012-07-02 12:42:44 -07001391size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1392 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393{
Eric Laurenta1884f92011-08-23 08:25:03 -07001394 status_t ret = initCheck();
1395 if (ret != NO_ERROR) {
1396 return 0;
1397 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001398 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001399 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001400 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001401 return 0;
1402 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001403
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001404 AutoMutex lock(mHardwareLock);
1405 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001406 audio_config_t config, proposed;
1407 memset(&proposed, 0, sizeof(proposed));
1408 proposed.sample_rate = sampleRate;
1409 proposed.channel_mask = channelMask;
1410 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001411
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001412 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001413 size_t frames;
1414 for (;;) {
1415 // Note: config is currently a const parameter for get_input_buffer_size()
1416 // but we use a copy from proposed in case config changes from the call.
1417 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001418 status_t result = dev->getInputBufferSize(&config, &frames);
1419 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001420 break; // hal success, config is the result
1421 }
1422 // change one parameter of the configuration each iteration to a more "common" value
1423 // to see if the device will support it.
1424 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1425 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1426 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1427 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1428 } else {
1429 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1430 "format %#x, channelMask 0x%X",
1431 sampleRate, format, channelMask);
1432 break; // retries failed, break out of loop with frames == 0.
1433 }
1434 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001435 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001436 if (frames > 0 && config.sample_rate != sampleRate) {
1437 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1438 }
1439 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440}
1441
Glenn Kasten5f972c02014-01-13 09:59:31 -08001442uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444 Mutex::Autolock _l(mLock);
1445
1446 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1447 if (recordThread != NULL) {
1448 return recordThread->getInputFramesLost();
1449 }
1450 return 0;
1451}
1452
1453status_t AudioFlinger::setVoiceVolume(float value)
1454{
Eric Laurenta1884f92011-08-23 08:25:03 -07001455 status_t ret = initCheck();
1456 if (ret != NO_ERROR) {
1457 return ret;
1458 }
1459
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 // check calling permissions
1461 if (!settingsAllowed()) {
1462 return PERMISSION_DENIED;
1463 }
1464
1465 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001466 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001467 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001468 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 mHardwareStatus = AUDIO_HW_IDLE;
1470
1471 return ret;
1472}
1473
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001474status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001475 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 Mutex::Autolock _l(mLock);
1478
1479 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1480 if (playbackThread != NULL) {
1481 return playbackThread->getRenderPosition(halFrames, dspFrames);
1482 }
1483
1484 return BAD_VALUE;
1485}
1486
1487void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1488{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001490 if (client == 0) {
1491 return;
1492 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001493 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001494 {
1495 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001496 if (mNotificationClients.indexOfKey(pid) < 0) {
1497 sp<NotificationClient> notificationClient = new NotificationClient(this,
1498 client,
1499 pid);
1500 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501
Eric Laurent021cf962014-05-13 10:18:14 -07001502 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503
Marco Nelissen06b46062014-11-14 07:58:25 -08001504 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001505 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001506 }
1507 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508
Eric Laurent021cf962014-05-13 10:18:14 -07001509 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001510 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001511 // the config change is always sent from playback or record threads to avoid deadlock
1512 // with AudioSystem::gLock
1513 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001514 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001515 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001517 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001518 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519 }
1520}
1521
1522void AudioFlinger::removeNotificationClient(pid_t pid)
1523{
1524 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001525 {
1526 Mutex::Autolock _cl(mClientLock);
1527 mNotificationClients.removeItem(pid);
1528 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001529
Steve Block3856b092011-10-20 11:56:00 +01001530 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001531 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001532 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001533 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001534 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001535 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001536 if (ref->mPid == pid) {
1537 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001538 mAudioSessionRefs.removeAt(i);
1539 delete ref;
1540 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001541 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001542 } else {
1543 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001544 }
1545 }
1546 if (removed) {
1547 purgeStaleEffects_l();
1548 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549}
1550
Eric Laurent73e26b62015-04-27 16:55:58 -07001551void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001552 const sp<AudioIoDescriptor>& ioDesc,
1553 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554{
Eric Laurent021cf962014-05-13 10:18:14 -07001555 Mutex::Autolock _l(mClientLock);
1556 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001558 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1559 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 }
1562}
1563
Eric Laurent021cf962014-05-13 10:18:14 -07001564// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565void AudioFlinger::removeClient_l(pid_t pid)
1566{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001567 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001568 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 mClients.removeItem(pid);
1570}
1571
Eric Laurent717e1282012-06-29 16:36:52 -07001572// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001573sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1574 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001575{
1576 sp<PlaybackThread> thread;
1577
1578 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1579 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1580 ALOG_ASSERT(thread == 0);
1581 thread = mPlaybackThreads.valueAt(i);
1582 }
1583 }
1584
1585 return thread;
1586}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589
1590// ----------------------------------------------------------------------------
1591
1592AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1593 : RefBase(),
1594 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001595 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596{
Andy Hung6f248bb2018-01-23 14:04:37 -08001597 mMemoryDealer = new MemoryDealer(
1598 audioFlinger->getClientSharedHeapSize(),
1599 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600}
1601
Eric Laurent021cf962014-05-13 10:18:14 -07001602// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603AudioFlinger::Client::~Client()
1604{
1605 mAudioFlinger->removeClient_l(mPid);
1606}
1607
Glenn Kasten435dbe62012-01-30 10:15:48 -08001608sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609{
1610 return mMemoryDealer;
1611}
1612
1613// ----------------------------------------------------------------------------
1614
1615AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1616 const sp<IAudioFlingerClient>& client,
1617 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001618 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619{
1620}
1621
1622AudioFlinger::NotificationClient::~NotificationClient()
1623{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624}
1625
Glenn Kasten0f11b512014-01-31 16:18:54 -08001626void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627{
1628 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001629 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630}
1631
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001632// ----------------------------------------------------------------------------
1633AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1634 : mPendingRequests(false) {}
1635
1636
1637void AudioFlinger::MediaLogNotifier::requestMerge() {
1638 AutoMutex _l(mMutex);
1639 mPendingRequests = true;
1640 mCond.signal();
1641}
1642
1643bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001644 // Should already have been checked, but just in case
1645 if (sMediaLogService == 0) {
1646 return false;
1647 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001648 // Wait until there are pending requests
1649 {
1650 AutoMutex _l(mMutex);
1651 mPendingRequests = false; // to ignore past requests
1652 while (!mPendingRequests) {
1653 mCond.wait(mMutex);
1654 // TODO may also need an exitPending check
1655 }
1656 mPendingRequests = false;
1657 }
1658 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001659 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001660 usleep(kPostTriggerSleepPeriod);
1661 return true;
1662}
1663
1664void AudioFlinger::requestLogMerge() {
1665 mMediaLogNotifier->requestMerge();
1666}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667
1668// ----------------------------------------------------------------------------
1669
Eric Laurentf14db3c2017-12-08 14:20:36 -08001670sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1671 CreateRecordOutput& output,
1672 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673{
1674 sp<RecordThread::RecordTrack> recordTrack;
1675 sp<RecordHandle> recordHandle;
1676 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001678 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001679 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680
Eric Laurentf14db3c2017-12-08 14:20:36 -08001681 output.cblk.clear();
1682 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001683 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001684
Eric Laurentf14db3c2017-12-08 14:20:36 -08001685 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001686 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001687 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001688 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001689 ALOGW_IF(clientUid != callingUid,
1690 "%s uid %d tried to pass itself off as %d",
1691 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001692 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001693 updatePid = true;
1694 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001695 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001696 if (updatePid) {
1697 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001698 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001699 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001700 __func__, callingUid, callingPid, clientPid);
1701 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001702 }
1703
Andy Hung6770c6f2015-04-07 13:43:36 -07001704 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001705 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1706 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001707 lStatus = BAD_VALUE;
1708 goto Exit;
1709 }
1710
Glenn Kasten53b5d092014-02-05 10:00:23 -08001711 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001712 if (!audio_is_input_channel(input.config.channel_mask)) {
1713 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001714 lStatus = BAD_VALUE;
1715 goto Exit;
1716 }
1717
Eric Laurentf14db3c2017-12-08 14:20:36 -08001718 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1719 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1720 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1721 lStatus = BAD_VALUE;
1722 goto Exit;
1723 }
1724
1725 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001726 output.selectedDeviceId = input.selectedDeviceId;
1727 output.flags = input.flags;
1728
1729 client = registerPid(clientPid);
1730
1731 // Not a conventional loop, but a retry loop for at most two iterations total.
1732 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1733 // Exits loop via break on no error of got exit on error
1734 // The sp<> references will be dropped when re-entering scope.
1735 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1736 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001737 // release previously opened input if retrying.
1738 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1739 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001740 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001741 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001742 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001743 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001744 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001745 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1746 sessionId,
1747 // FIXME compare to AudioTrack
1748 clientPid,
1749 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001750 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001751 &input.config,
1752 output.flags, &output.selectedDeviceId, &portId);
1753
Glenn Kasten05997e22014-03-13 15:08:33 -07001754 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001756 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001758 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 lStatus = BAD_VALUE;
1760 goto Exit;
1761 }
1762
Eric Laurentf14db3c2017-12-08 14:20:36 -08001763 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764
Eric Laurentf14db3c2017-12-08 14:20:36 -08001765 output.sampleRate = input.config.sample_rate;
1766 output.frameCount = input.frameCount;
1767 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001768
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001769 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001770 input.config.format, input.config.channel_mask,
1771 &output.frameCount, sessionId,
1772 &output.notificationFrameCount,
1773 clientUid, &output.flags,
1774 input.clientInfo.clientTid,
1775 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001776 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001777
Eric Laurentf14db3c2017-12-08 14:20:36 -08001778 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1779 // audio policy manager without FAST constraint
1780 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001781 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001782 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001783
1784 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001785 goto Exit;
1786 }
1787
1788 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1789 // session and move it to this thread.
1790 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1791 if (chain != 0) {
1792 Mutex::Autolock _l(thread->mLock);
1793 thread->addEffectChain_l(chain);
1794 }
1795 break;
1796 }
1797 // End of retry loop.
1798 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 }
Glenn Kastene198c362013-08-13 09:13:36 -07001800
Eric Laurentf14db3c2017-12-08 14:20:36 -08001801 output.cblk = recordTrack->getCblk();
1802 output.buffers = recordTrack->getBuffers();
1803
1804 // return handle to client
1805 recordHandle = new RecordHandle(recordTrack);
1806
1807Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001808 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001809 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001810 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001811 // Don't hold mClientLock when releasing the reference on the track as the
1812 // destructor will acquire it.
1813 {
1814 Mutex::Autolock _cl(mClientLock);
1815 client.clear();
1816 }
Eric Laurent896c9672017-12-08 14:08:45 -08001817 recordTrack.clear();
1818 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001819 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 }
1822
Glenn Kasten9156ef32013-08-06 15:39:08 -07001823 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 return recordHandle;
1825}
1826
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001827
1828
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829// ----------------------------------------------------------------------------
1830
Eric Laurenta4c5a552012-03-29 10:12:40 -07001831audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1832{
Eric Laurent44622db2014-08-01 19:00:33 -07001833 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001834 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001835 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001836 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001837 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001838 }
1839 Mutex::Autolock _l(mLock);
1840 return loadHwModule_l(name);
1841}
1842
1843// loadHwModule_l() must be called with AudioFlinger::mLock held
1844audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1845{
1846 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1847 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1848 ALOGW("loadHwModule() module %s already loaded", name);
1849 return mAudioHwDevs.keyAt(i);
1850 }
1851 }
1852
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001853 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001854
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001855 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001856 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001857 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001858 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001859 }
1860
1861 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001862 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001863 mHardwareStatus = AUDIO_HW_IDLE;
1864 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001865 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001866 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001867 }
1868
John Grossmanee578c02012-07-23 17:05:46 -07001869 // Check and cache this HAL's level of support for master mute and master
1870 // volume. If this is the first HAL opened, and it supports the get
1871 // methods, use the initial values provided by the HAL as the current
1872 // master mute and volume settings.
1873
1874 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1875 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001876 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001877
1878 if (0 == mAudioHwDevs.size()) {
1879 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001880 float mv;
1881 if (OK == dev->getMasterVolume(&mv)) {
1882 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001883 }
1884
1885 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001886 bool mm;
1887 if (OK == dev->getMasterMute(&mm)) {
1888 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001889 }
1890 }
1891
Eric Laurenta4c5a552012-03-29 10:12:40 -07001892 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001893 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001894 flags = static_cast<AudioHwDevice::Flags>(flags |
1895 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1896 }
1897
1898 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001899 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001900 flags = static_cast<AudioHwDevice::Flags>(flags |
1901 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1902 }
1903
Eric Laurenta4c5a552012-03-29 10:12:40 -07001904 mHardwareStatus = AUDIO_HW_IDLE;
1905 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07001906 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07001907 // An MSD module is inserted before hardware modules in order to mix encoded streams.
1908 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
1909 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001910
Glenn Kastena13cde92016-03-28 15:26:02 -07001911 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001912 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001913
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001914 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001915
1916 return handle;
1917
1918}
1919
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001920// ----------------------------------------------------------------------------
1921
Glenn Kasten3b16c762012-11-14 08:44:39 -08001922uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001923{
1924 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001925 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001926 return thread != NULL ? thread->sampleRate() : 0;
1927}
1928
Glenn Kastene33054e2012-11-14 12:54:39 -08001929size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001930{
1931 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001932 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001933 return thread != NULL ? thread->frameCountHAL() : 0;
1934}
1935
1936// ----------------------------------------------------------------------------
1937
Andy Hung6f248bb2018-01-23 14:04:37 -08001938status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001939{
1940 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001941 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001942 return PERMISSION_DENIED;
1943 }
1944 Mutex::Autolock _l(mLock);
1945 if (mIsDeviceTypeKnown) {
1946 return INVALID_OPERATION;
1947 }
1948 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001949 mTotalMemory = totalMemory;
1950 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1951 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1952 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1953 // though actual setting is determined through device configuration.
1954 constexpr int64_t GB = 1024 * 1024 * 1024;
1955 mClientSharedHeapSize =
1956 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1957 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1958 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1959 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1960 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001961 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001962
1963 // TODO: Cache the client shared heap size in a persistent property.
1964 // It's possible that a native process or Java service or app accesses audioserver
1965 // after it is registered by system server, but before AudioService updates
1966 // the memory info. This would occur immediately after boot or an audioserver
1967 // crash and restore. Before update from AudioService, the client would get the
1968 // minimum heap size.
1969
1970 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1971 (isLowRamDevice ? "true" : "false"),
1972 (long long)mTotalMemory,
1973 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001974 return NO_ERROR;
1975}
1976
Andy Hung6f248bb2018-01-23 14:04:37 -08001977size_t AudioFlinger::getClientSharedHeapSize() const
1978{
1979 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1980 if (heapSizeInBytes != 0) { // read-only property overrides all.
1981 return heapSizeInBytes;
1982 }
1983 return mClientSharedHeapSize;
1984}
1985
Mikhail Naganovdea53042018-04-26 13:10:21 -07001986status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1987{
1988 ALOGV(__func__);
1989
1990 audio_module_handle_t module;
1991 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1992 module = config->ext.device.hw_module;
1993 } else {
1994 module = config->ext.mix.hw_module;
1995 }
1996
1997 Mutex::Autolock _l(mLock);
1998 ssize_t index = mAudioHwDevs.indexOfKey(module);
1999 if (index < 0) {
2000 ALOGW("%s() bad hw module %d", __func__, module);
2001 return BAD_VALUE;
2002 }
2003
2004 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2005 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2006}
2007
Eric Laurent93c3d412014-08-01 14:48:35 -07002008audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2009{
2010 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002011
2012 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2013 if (index >= 0) {
2014 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2015 mHwAvSyncIds.valueAt(index), sessionId);
2016 return mHwAvSyncIds.valueAt(index);
2017 }
2018
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002019 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002020 if (dev == NULL) {
2021 return AUDIO_HW_SYNC_INVALID;
2022 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002023 String8 reply;
2024 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002025 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002026 param = AudioParameter(reply);
2027 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002028
2029 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002030 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002031 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2032 return AUDIO_HW_SYNC_INVALID;
2033 }
2034
2035 // allow only one session for a given HW A/V sync ID.
2036 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2037 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2038 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2039 value, mHwAvSyncIds.keyAt(i));
2040 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002041 break;
2042 }
2043 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002044
2045 mHwAvSyncIds.add(sessionId, value);
2046
2047 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2048 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2049 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002050 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002051 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002052 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002053 String8 keyValuePairs = param.toString();
2054 thread->setParameters(keyValuePairs);
2055 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2056 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002057 break;
2058 }
2059 }
2060
2061 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2062 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002063}
2064
Eric Laurent72e3f392015-05-20 14:43:50 -07002065status_t AudioFlinger::systemReady()
2066{
2067 Mutex::Autolock _l(mLock);
2068 ALOGI("%s", __FUNCTION__);
2069 if (mSystemReady) {
2070 ALOGW("%s called twice", __FUNCTION__);
2071 return NO_ERROR;
2072 }
2073 mSystemReady = true;
2074 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2075 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2076 thread->systemReady();
2077 }
2078 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2079 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2080 thread->systemReady();
2081 }
2082 return NO_ERROR;
2083}
2084
jiabin46a76fa2018-01-05 10:18:21 -08002085status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2086{
jiabin9ff780e2018-03-19 18:19:52 -07002087 AutoMutex lock(mHardwareLock);
2088 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2089 status_t status = dev->getMicrophones(microphones);
2090 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002091}
2092
Eric Laurentfa90e842014-10-17 18:12:31 -07002093// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2094void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2095{
2096 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2097 if (index >= 0) {
2098 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2099 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2100 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002101 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002102 String8 keyValuePairs = param.toString();
2103 thread->setParameters(keyValuePairs);
2104 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2105 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002106 }
2107}
2108
2109
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002110// ----------------------------------------------------------------------------
2111
Eric Laurent83b88082014-06-20 18:31:16 -07002112
Eric Laurent6acd1d42017-01-04 14:23:29 -08002113sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002114 audio_io_handle_t *output,
2115 audio_config_t *config,
2116 audio_devices_t devices,
2117 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002118 audio_output_flags_t flags)
2119{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002120 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002121 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002122 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002123 }
2124
Eric Laurentcf2c0212014-07-25 16:20:43 -07002125 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002126 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2127 } else {
2128 // Audio Policy does not currently request a specific output handle.
2129 // If this is ever needed, see openInput_l() for example code.
2130 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2131 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002132 }
Eric Laurent83b88082014-06-20 18:31:16 -07002133
2134 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2135
Eric Laurent83b88082014-06-20 18:31:16 -07002136 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002137 // This if statement allows overriding the audio policy settings
2138 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2139 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2140 // Check only for Normal Mixing mode
2141 if (kEnableExtendedPrecision) {
2142 // Specify format (uncomment one below to choose)
2143 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2144 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2145 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2146 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002147 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002148 }
2149 if (kEnableExtendedChannels) {
2150 // Specify channel mask (uncomment one below to choose)
2151 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2152 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2153 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2154 }
Eric Laurent83b88082014-06-20 18:31:16 -07002155 }
2156
Phil Burk062e67a2015-02-11 13:40:50 -08002157 AudioStreamOut *outputStream = NULL;
2158 status_t status = outHwDev->openOutputStream(
2159 &outputStream,
2160 *output,
2161 devices,
2162 flags,
2163 config,
2164 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002165
2166 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002167
Phil Burk062e67a2015-02-11 13:40:50 -08002168 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002169 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2170 sp<MmapPlaybackThread> thread =
2171 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2172 devices, AUDIO_DEVICE_NONE, mSystemReady);
2173 mMmapThreads.add(*output, thread);
2174 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2175 *output, thread.get());
2176 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002177 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002178 sp<PlaybackThread> thread;
2179 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2180 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2181 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2182 *output, thread.get());
2183 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2184 || !isValidPcmSinkFormat(config->format)
2185 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2186 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2187 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2188 *output, thread.get());
2189 } else {
2190 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2191 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2192 *output, thread.get());
2193 }
2194 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002195 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002196 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002197 }
Eric Laurent83b88082014-06-20 18:31:16 -07002198 }
2199
2200 return 0;
2201}
2202
Eric Laurentcf2c0212014-07-25 16:20:43 -07002203status_t AudioFlinger::openOutput(audio_module_handle_t module,
2204 audio_io_handle_t *output,
2205 audio_config_t *config,
2206 audio_devices_t *devices,
2207 const String8& address,
2208 uint32_t *latencyMs,
2209 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002211 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2212 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002213 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002214 (devices != NULL) ? *devices : 0,
2215 config->sample_rate,
2216 config->format,
2217 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002218 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002220 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002221 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002223
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 Mutex::Autolock _l(mLock);
2225
Eric Laurent6acd1d42017-01-04 14:23:29 -08002226 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002227 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002228 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2229 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2230 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231
Eric Laurent6acd1d42017-01-04 14:23:29 -08002232 // notify client processes of the new output creation
2233 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002234
Eric Laurent6acd1d42017-01-04 14:23:29 -08002235 // the first primary output opened designates the primary hw device
2236 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002237 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002238 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002239
Eric Laurent6acd1d42017-01-04 14:23:29 -08002240 AutoMutex lock(mHardwareLock);
2241 mHardwareStatus = AUDIO_HW_SET_MODE;
2242 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2243 mHardwareStatus = AUDIO_HW_IDLE;
2244 }
2245 } else {
2246 MmapThread *mmapThread = (MmapThread *)thread.get();
2247 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002248 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002249 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 }
2251
Eric Laurentcf2c0212014-07-25 16:20:43 -07002252 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253}
2254
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002255audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2256 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257{
2258 Mutex::Autolock _l(mLock);
2259 MixerThread *thread1 = checkMixerThread_l(output1);
2260 MixerThread *thread2 = checkMixerThread_l(output2);
2261
2262 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002263 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2264 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002265 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 }
2267
Glenn Kasteneeecb982016-02-26 10:44:04 -08002268 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002269 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 thread->addOutputTrack(thread2);
2271 mPlaybackThreads.add(id, thread);
2272 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002273 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 return id;
2275}
2276
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002277status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278{
Glenn Kastend96c5722012-04-25 13:44:49 -07002279 return closeOutput_nonvirtual(output);
2280}
2281
2282status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2283{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 // keep strong reference on the playback thread so that
2285 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002286 sp<PlaybackThread> playbackThread;
2287 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 {
2289 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002290 playbackThread = checkPlaybackThread_l(output);
2291 if (playbackThread != NULL) {
2292 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293
Eric Laurent6acd1d42017-01-04 14:23:29 -08002294 if (playbackThread->type() == ThreadBase::MIXER) {
2295 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2296 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2297 DuplicatingThread *dupThread =
2298 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2299 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2300 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002301 }
2302 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303
2304
Eric Laurent6acd1d42017-01-04 14:23:29 -08002305 mPlaybackThreads.removeItem(output);
2306 // save all effects to the default thread
2307 if (mPlaybackThreads.size()) {
2308 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2309 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002310 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002311 Mutex::Autolock _dl(dstThread->mLock);
2312 Mutex::Autolock _sl(playbackThread->mLock);
2313 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2314 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002315 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2316 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002317 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 }
2319 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002320 } else {
2321 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2322 if (mmapThread == 0) {
2323 return BAD_VALUE;
2324 }
2325 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002326 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002328 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2329 ioDesc->mIoHandle = output;
2330 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002331 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002333 // The thread entity (active unit of execution) is no longer running here,
2334 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335
Eric Laurent6acd1d42017-01-04 14:23:29 -08002336 if (playbackThread != 0) {
2337 playbackThread->exit();
2338 if (!playbackThread->isDuplicating()) {
2339 closeOutputFinish(playbackThread);
2340 }
2341 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002342 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002343 mmapThread->exit();
2344 AudioStreamOut *out = mmapThread->clearOutput();
2345 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2346 // from now on thread->mOutput is NULL
2347 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 }
2349 return NO_ERROR;
2350}
2351
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002352void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002353{
2354 AudioStreamOut *out = thread->clearOutput();
2355 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2356 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002357 delete out;
2358}
2359
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002360void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002361{
2362 mPlaybackThreads.removeItem(thread->mId);
2363 thread->exit();
2364 closeOutputFinish(thread);
2365}
2366
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002367status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002368{
2369 Mutex::Autolock _l(mLock);
2370 PlaybackThread *thread = checkPlaybackThread_l(output);
2371
2372 if (thread == NULL) {
2373 return BAD_VALUE;
2374 }
2375
Steve Block3856b092011-10-20 11:56:00 +01002376 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377 thread->suspend();
2378
2379 return NO_ERROR;
2380}
2381
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002382status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383{
2384 Mutex::Autolock _l(mLock);
2385 PlaybackThread *thread = checkPlaybackThread_l(output);
2386
2387 if (thread == NULL) {
2388 return BAD_VALUE;
2389 }
2390
Steve Block3856b092011-10-20 11:56:00 +01002391 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392
2393 thread->restore();
2394
2395 return NO_ERROR;
2396}
2397
Eric Laurentcf2c0212014-07-25 16:20:43 -07002398status_t AudioFlinger::openInput(audio_module_handle_t module,
2399 audio_io_handle_t *input,
2400 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002401 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002402 const String8& address,
2403 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002404 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405{
Eric Laurent83b88082014-06-20 18:31:16 -07002406 Mutex::Autolock _l(mLock);
2407
Glenn Kastene7d66712015-03-05 13:46:52 -08002408 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002409 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002410 }
2411
Eric Laurent6acd1d42017-01-04 14:23:29 -08002412 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002413
2414 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002415 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002416 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002417 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002419 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002420}
Dima Zavin799a70e2011-04-18 16:57:27 -07002421
Eric Laurent6acd1d42017-01-04 14:23:29 -08002422sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002423 audio_io_handle_t *input,
2424 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002425 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002426 const String8& address,
2427 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002428 audio_input_flags_t flags)
2429{
Glenn Kastene7d66712015-03-05 13:46:52 -08002430 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002431 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002432 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002433 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002434 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002435
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002436 // Some flags are specific to framework and must not leak to the HAL.
2437 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2438
Glenn Kasteneeecb982016-02-26 10:44:04 -08002439 // Audio Policy can request a specific handle for hardware hotword.
2440 // The goal here is not to re-open an already opened input.
2441 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002442 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002443 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2444 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2445 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2446 return 0;
2447 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2448 // This should not happen in a transient state with current design.
2449 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2450 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002451 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002452
Eric Laurentcf2c0212014-07-25 16:20:43 -07002453 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002454 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002455 sp<StreamInHalInterface> inStream;
2456 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002457 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002458 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2459 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002460 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002461 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002462 halconfig.sample_rate,
2463 halconfig.format,
2464 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002465 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002466 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002468 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002469 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002470 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002471 audio_is_linear_pcm(config->format) &&
2472 audio_is_linear_pcm(halconfig.format) &&
2473 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002474 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2475 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002476 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002477 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002478 inStream.clear();
2479 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002480 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002481 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 }
2483
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002484 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002485 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002486 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2487 sp<MmapCaptureThread> thread =
2488 new MmapCaptureThread(this, *input,
2489 inHwDev, inputStream,
2490 primaryOutputDevice_l(), devices, mSystemReady);
2491 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002492 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2493 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002494 return thread;
2495 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002496 // Start record thread
2497 // RecordThread requires both input and output device indication to forward to audio
2498 // pre processing modules
2499 sp<RecordThread> thread = new RecordThread(this,
2500 inputStream,
2501 *input,
2502 primaryOutputDevice_l(),
2503 devices,
2504 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002505 );
2506 mRecordThreads.add(*input, thread);
2507 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2508 return thread;
2509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 }
2511
Eric Laurentcf2c0212014-07-25 16:20:43 -07002512 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513 return 0;
2514}
2515
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002516status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517{
Glenn Kastend96c5722012-04-25 13:44:49 -07002518 return closeInput_nonvirtual(input);
2519}
2520
2521status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2522{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 // keep strong reference on the record thread so that
2524 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002525 sp<RecordThread> recordThread;
2526 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527 {
2528 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 recordThread = checkRecordThread_l(input);
2530 if (recordThread != 0) {
2531 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532
Eric Laurent6acd1d42017-01-04 14:23:29 -08002533 // If we still have effect chains, it means that a client still holds a handle
2534 // on at least one effect. We must either move the chain to an existing thread with the
2535 // same session ID or put it aside in case a new record thread is opened for a
2536 // new capture on the same session
2537 sp<EffectChain> chain;
2538 {
2539 Mutex::Autolock _sl(recordThread->mLock);
2540 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2541 // Note: maximum one chain per record thread
2542 if (effectChains.size() != 0) {
2543 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002544 }
2545 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002546 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002547 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002548 // This should only happen in case of overlap between one thread tear down and the
2549 // creation of its replacement
2550 size_t i;
2551 for (i = 0; i < mRecordThreads.size(); i++) {
2552 sp<RecordThread> t = mRecordThreads.valueAt(i);
2553 if (t == recordThread) {
2554 continue;
2555 }
2556 if (t->hasAudioSession(chain->sessionId()) != 0) {
2557 Mutex::Autolock _l(t->mLock);
2558 ALOGV("closeInput() found thread %d for effect session %d",
2559 t->id(), chain->sessionId());
2560 t->addEffectChain_l(chain);
2561 break;
2562 }
2563 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002564 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002565 if (i == mRecordThreads.size()) {
2566 putOrphanEffectChain_l(chain);
2567 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002568 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002569 mRecordThreads.removeItem(input);
2570 } else {
2571 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2572 if (mmapThread == 0) {
2573 return BAD_VALUE;
2574 }
2575 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002576 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002577 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2578 ioDesc->mIoHandle = input;
2579 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 }
Eric Laurent83b88082014-06-20 18:31:16 -07002581 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2582 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583 if (recordThread != 0) {
2584 closeInputFinish(recordThread);
2585 } else if (mmapThread != 0) {
2586 mmapThread->exit();
2587 AudioStreamIn *in = mmapThread->clearInput();
2588 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2589 // from now on thread->mInput is NULL
2590 delete in;
2591 }
Eric Laurent83b88082014-06-20 18:31:16 -07002592 return NO_ERROR;
2593}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002595void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002596{
2597 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002598 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002599 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002600 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002601 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002602}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002603
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002604void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002605{
2606 mRecordThreads.removeItem(thread->mId);
2607 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608}
2609
Glenn Kastend2304db2014-02-03 07:40:31 -08002610status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611{
2612 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002613 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614
2615 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2616 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002617 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002618 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002619 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2620 mMmapThreads[i]->invalidateTracks(stream);
2621 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622 return NO_ERROR;
2623}
2624
2625
Glenn Kasteneeecb982016-02-26 10:44:04 -08002626audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627{
Glenn Kasten9d003132016-04-06 14:38:09 -07002628 // This is a binder API, so a malicious client could pass in a bad parameter.
2629 // Check for that before calling the internal API nextUniqueId().
2630 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2631 ALOGE("newAudioUniqueId invalid use %d", use);
2632 return AUDIO_UNIQUE_ID_ALLOCATE;
2633 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002634 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635}
2636
Glenn Kastend848eb42016-03-08 13:42:11 -08002637void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002638{
2639 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002640 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002641 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002642 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2643 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002644 caller = pid;
2645 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002646
Eric Laurent021cf962014-05-13 10:18:14 -07002647 {
2648 Mutex::Autolock _cl(mClientLock);
2649 // Ignore requests received from processes not known as notification client. The request
2650 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2651 // called from a different pid leaving a stale session reference. Also we don't know how
2652 // to clear this reference if the client process dies.
2653 if (mNotificationClients.indexOfKey(caller) < 0) {
2654 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2655 return;
2656 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002657 }
2658
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002659 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002660 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002661 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002662 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2663 ref->mCnt++;
2664 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002665 return;
2666 }
2667 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002668 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2669 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002670}
2671
Glenn Kastend848eb42016-03-08 13:42:11 -08002672void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002673{
2674 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002675 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002676 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002677 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2678 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002679 caller = pid;
2680 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002681 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002682 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002683 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002684 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2685 ref->mCnt--;
2686 ALOGV(" decremented refcount to %d", ref->mCnt);
2687 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002688 mAudioSessionRefs.removeAt(i);
2689 delete ref;
2690 purgeStaleEffects_l();
2691 }
2692 return;
2693 }
2694 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002695 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002696 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002697 ALOGW_IF(!isAudioServerUid(callerUid),
2698 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002699}
2700
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002701bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2702{
2703 size_t num = mAudioSessionRefs.size();
2704 for (size_t i = 0; i < num; i++) {
2705 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2706 if (ref->mSessionid == audioSession) {
2707 return true;
2708 }
2709 }
2710 return false;
2711}
2712
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002713void AudioFlinger::purgeStaleEffects_l() {
2714
Steve Block3856b092011-10-20 11:56:00 +01002715 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002716
2717 Vector< sp<EffectChain> > chains;
2718
2719 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2720 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002721 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002722 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2723 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002724 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2725 chains.push(ec);
2726 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002727 }
2728 }
2729 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2730 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002731 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002732 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2733 sp<EffectChain> ec = t->mEffectChains[j];
2734 chains.push(ec);
2735 }
2736 }
2737
2738 for (size_t i = 0; i < chains.size(); i++) {
2739 sp<EffectChain> ec = chains[i];
2740 int sessionid = ec->sessionId();
2741 sp<ThreadBase> t = ec->mThread.promote();
2742 if (t == 0) {
2743 continue;
2744 }
2745 size_t numsessionrefs = mAudioSessionRefs.size();
2746 bool found = false;
2747 for (size_t k = 0; k < numsessionrefs; k++) {
2748 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002749 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002750 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002751 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002752 found = true;
2753 break;
2754 }
2755 }
2756 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002757 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002758 // remove all effects from the chain
2759 while (ec->mEffects.size()) {
2760 sp<EffectModule> effect = ec->mEffects[0];
2761 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002762 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002763 if (effect->purgeHandles()) {
2764 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002765 }
2766 AudioSystem::unregisterEffect(effect->id());
2767 }
2768 }
2769 }
2770 return;
2771}
2772
Glenn Kasteneeecb982016-02-26 10:44:04 -08002773// checkThread_l() must be called with AudioFlinger::mLock held
2774AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2775{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002776 ThreadBase *thread = checkMmapThread_l(ioHandle);
2777 if (thread == 0) {
2778 switch (audio_unique_id_get_use(ioHandle)) {
2779 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2780 thread = checkPlaybackThread_l(ioHandle);
2781 break;
2782 case AUDIO_UNIQUE_ID_USE_INPUT:
2783 thread = checkRecordThread_l(ioHandle);
2784 break;
2785 default:
2786 break;
2787 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002788 }
2789 return thread;
2790}
2791
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002793AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794{
Glenn Kastena1117922012-01-26 10:53:32 -08002795 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796}
2797
2798// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002799AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800{
2801 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002802 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803}
2804
2805// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002806AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807{
Glenn Kastena1117922012-01-26 10:53:32 -08002808 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809}
2810
Eric Laurent6acd1d42017-01-04 14:23:29 -08002811// checkMmapThread_l() must be called with AudioFlinger::mLock held
2812AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2813{
2814 return mMmapThreads.valueFor(io).get();
2815}
2816
2817
2818// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2819AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2820{
Eric Laurent7459b902017-04-19 18:10:41 -07002821 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002822 if (volumeInterface == nullptr) {
2823 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2824 if (mmapThread != nullptr) {
2825 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002826 MmapPlaybackThread *mmapPlaybackThread =
2827 static_cast<MmapPlaybackThread *>(mmapThread);
2828 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002829 }
2830 }
2831 }
2832 return volumeInterface;
2833}
2834
2835Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2836{
2837 Vector <VolumeInterface *> volumeInterfaces;
2838 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002839 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002840 }
2841 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2842 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002843 MmapPlaybackThread *mmapPlaybackThread =
2844 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2845 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002846 }
2847 }
2848 return volumeInterfaces;
2849}
2850
Glenn Kasteneeecb982016-02-26 10:44:04 -08002851audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852{
Glenn Kasten9d003132016-04-06 14:38:09 -07002853 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002854 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002855 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2856 for (int retry = 0; retry < maxRetries; retry++) {
2857 // The cast allows wraparound from max positive to min negative instead of abort
2858 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2859 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2860 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2861 // allow wrap by skipping 0 and -1 for session ids
2862 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2863 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2864 return (audio_unique_id_t) (base | use);
2865 }
2866 }
2867 // We have no way of recovering from wraparound
2868 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2869 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870}
2871
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002872AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002873{
2874 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2875 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002876 if(thread->isDuplicating()) {
2877 continue;
2878 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002879 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002880 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002881 return thread;
2882 }
2883 }
2884 return NULL;
2885}
2886
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002887audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002888{
2889 PlaybackThread *thread = primaryPlaybackThread_l();
2890
2891 if (thread == NULL) {
2892 return 0;
2893 }
2894
Eric Laurentf1c04f92012-08-28 14:26:53 -07002895 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002896}
2897
Glenn Kastena7335632016-06-09 17:09:53 -07002898AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2899{
2900 size_t minFrameCount = 0;
2901 PlaybackThread *minThread = NULL;
2902 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2903 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2904 if (!thread->isDuplicating()) {
2905 size_t frameCount = thread->frameCountHAL();
2906 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2907 (frameCount == minFrameCount && thread->hasFastMixer() &&
2908 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2909 minFrameCount = frameCount;
2910 minThread = thread;
2911 }
2912 }
2913 }
2914 return minThread;
2915}
2916
Eric Laurenta011e352012-03-29 15:51:43 -07002917sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002918 audio_session_t triggerSession,
2919 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002920 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002921 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002922{
2923 Mutex::Autolock _l(mLock);
2924
2925 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2926 status_t playStatus = NAME_NOT_FOUND;
2927 status_t recStatus = NAME_NOT_FOUND;
2928 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2929 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2930 if (playStatus == NO_ERROR) {
2931 return event;
2932 }
2933 }
2934 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2935 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2936 if (recStatus == NO_ERROR) {
2937 return event;
2938 }
2939 }
2940 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2941 mPendingSyncEvents.add(event);
2942 } else {
2943 ALOGV("createSyncEvent() invalid event %d", event->type());
2944 event.clear();
2945 }
2946 return event;
2947}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002948
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949// ----------------------------------------------------------------------------
2950// Effect management
2951// ----------------------------------------------------------------------------
2952
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002953sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2954 return mEffectsFactoryHal;
2955}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956
Glenn Kastenf587ba52012-01-26 16:25:10 -08002957status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958{
2959 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002960 if (mEffectsFactoryHal.get()) {
2961 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2962 } else {
2963 return -ENODEV;
2964 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965}
2966
Glenn Kastenf587ba52012-01-26 16:25:10 -08002967status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968{
2969 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002970 if (mEffectsFactoryHal.get()) {
2971 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2972 } else {
2973 return -ENODEV;
2974 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975}
2976
Glenn Kasten5e92a782012-01-30 07:40:52 -08002977status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002978 const effect_uuid_t *pTypeUuid,
2979 uint32_t preferredTypeFlag,
2980 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002982 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
2983 return BAD_VALUE;
2984 }
2985
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002987
2988 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002989 return -ENODEV;
2990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07002992 status_t status = NO_ERROR;
2993 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
2994 // If uuid is specified, request effect descriptor from that.
2995 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2996 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
2997 // If uuid is not specified, look for an available implementation
2998 // of the required type instead.
2999
3000 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3001 effect_descriptor_t desc;
3002 desc.flags = 0; // prevent compiler warning
3003
3004 uint32_t numEffects = 0;
3005 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3006 if (status < 0) {
3007 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3008 return status;
3009 }
3010
3011 bool found = false;
3012 for (uint32_t i = 0; i < numEffects; i++) {
3013 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3014 if (status < 0) {
3015 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3016 continue;
3017 }
3018 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3019 // If matching type found save effect descriptor.
3020 found = true;
3021 *descriptor = desc;
3022
3023 // If there's no preferred flag or this descriptor matches the preferred
3024 // flag, success! If this descriptor doesn't match the preferred
3025 // flag, continue enumeration in case a better matching version of this
3026 // effect type is available. Note that this means if no effect with a
3027 // correct flag is found, the descriptor returned will correspond to the
3028 // last effect that at least had a matching type uuid (if any).
3029 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3030 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3031 break;
3032 }
3033 }
3034 }
3035
3036 if (!found) {
3037 status = NAME_NOT_FOUND;
3038 ALOGW("getEffectDescriptor(): Effect not found by type.");
3039 }
3040 } else {
3041 status = BAD_VALUE;
3042 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3043 }
3044 return status;
3045}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003047sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 effect_descriptor_t *pDesc,
3049 const sp<IEffectClient>& effectClient,
3050 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003051 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003052 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003053 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003054 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 status_t *status,
3056 int *id,
3057 int *enabled)
3058{
3059 status_t lStatus = NO_ERROR;
3060 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062
Eric Laurentb6436272016-12-07 19:24:50 -08003063 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003064 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003065 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3066 ALOGW_IF(pid != -1 && pid != callingPid,
3067 "%s uid %d pid %d tried to pass itself off as pid %d",
3068 __func__, callingUid, callingPid, pid);
3069 pid = callingPid;
3070 }
3071
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003072 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3073 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074
3075 if (pDesc == NULL) {
3076 lStatus = BAD_VALUE;
3077 goto Exit;
3078 }
3079
Eric Laurent84e9a102010-09-23 16:10:16 -07003080 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003081 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003082 lStatus = PERMISSION_DENIED;
3083 goto Exit;
3084 }
3085
Dima Zavinfce7a472011-04-19 22:30:36 -07003086 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003087 // that can only be created by audio policy manager
3088 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003089 lStatus = PERMISSION_DENIED;
3090 goto Exit;
3091 }
3092
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003093 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003094 lStatus = NO_INIT;
3095 goto Exit;
3096 }
3097
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003099 // Get the full effect descriptor from the uuid/type.
3100 // If the session is the output mix, prefer an auxiliary effect,
3101 // otherwise no preference.
3102 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3103 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3104 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3105 if (lStatus < 0) {
3106 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3107 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 }
3109
3110 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003111 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3113 lStatus = INVALID_OPERATION;
3114 goto Exit;
3115 }
3116
Eric Laurent59255e42011-07-27 19:49:51 -07003117 // check recording permission for visualizer
3118 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003119 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003120 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003121 lStatus = PERMISSION_DENIED;
3122 goto Exit;
3123 }
3124
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003126 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003127 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003128 // if the output returned by getOutputForEffect() is removed before we lock the
3129 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3130 // and we will exit safely
3131 io = AudioSystem::getOutputForEffect(&desc);
3132 ALOGV("createEffect got output %d", io);
3133 }
3134
3135 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136
3137 // If output is not specified try to find a matching audio session ID in one of the
3138 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003139 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3140 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003141 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003142 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003143 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3144 // output must be specified by AudioPolicyManager when using session
3145 // AUDIO_SESSION_OUTPUT_STAGE
3146 lStatus = BAD_VALUE;
3147 goto Exit;
3148 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003149 // look for the thread where the specified audio session is present
3150 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3151 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3152 io = mPlaybackThreads.keyAt(i);
3153 break;
3154 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003156 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003157 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3158 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3159 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003160 break;
3161 }
3162 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003163 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003164 if (io == AUDIO_IO_HANDLE_NONE) {
3165 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3166 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3167 io = mMmapThreads.keyAt(i);
3168 break;
3169 }
3170 }
3171 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003172 // If no output thread contains the requested session ID, default to
3173 // first output. The effect chain will be moved to the correct output
3174 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003175 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003176 io = mPlaybackThreads.keyAt(0);
3177 }
Steve Block3856b092011-10-20 11:56:00 +01003178 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003179 }
3180 ThreadBase *thread = checkRecordThread_l(io);
3181 if (thread == NULL) {
3182 thread = checkPlaybackThread_l(io);
3183 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003184 thread = checkMmapThread_l(io);
3185 if (thread == NULL) {
3186 ALOGE("createEffect() unknown output thread");
3187 lStatus = BAD_VALUE;
3188 goto Exit;
3189 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003190 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003191 } else {
3192 // Check if one effect chain was awaiting for an effect to be created on this
3193 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003194 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003195 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003196 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003197 thread->addEffectChain_l(chain);
3198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003200
Eric Laurent021cf962014-05-13 10:18:14 -07003201 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003203 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003204 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003205 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003206 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003207 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003208 // remove local strong reference to Client with mClientLock held
3209 Mutex::Autolock _cl(mClientLock);
3210 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003211 } else {
3212 // handle must be valid here, but check again to be safe.
3213 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003214 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 }
3216
haobo101735295ff7b0d2017-03-17 17:44:03 +08003217 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3218 // handle must be cleared outside lock.
3219 handle.clear();
3220 }
3221
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003223 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 return handle;
3225}
3226
Glenn Kastend848eb42016-03-08 13:42:11 -08003227status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003228 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003229{
Steve Block3856b092011-10-20 11:56:00 +01003230 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003231 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003232 Mutex::Autolock _l(mLock);
3233 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003234 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003235 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 }
Eric Laurentde070132010-07-13 04:45:46 -07003237 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3238 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003239 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003240 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 }
Eric Laurentde070132010-07-13 04:45:46 -07003242 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3243 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003244 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003245 return BAD_VALUE;
3246 }
3247
3248 Mutex::Autolock _dl(dstThread->mLock);
3249 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003250 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251}
3252
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003253// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003254status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003255 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003256 AudioFlinger::PlaybackThread *dstThread,
3257 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003258{
Steve Block3856b092011-10-20 11:56:00 +01003259 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003260 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003261
Eric Laurent59255e42011-07-27 19:49:51 -07003262 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003263 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003264 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003265 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003266 return INVALID_OPERATION;
3267 }
3268
Eric Laurent4c415062016-06-17 16:14:16 -07003269 // Check whether the destination thread and all effects in the chain are compatible
3270 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003271 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003272 " destination thread %p is not compatible with effects in the chain",
3273 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003274 return INVALID_OPERATION;
3275 }
3276
Eric Laurent39e94f82010-07-28 01:32:47 -07003277 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003278 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003279 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003280 // removed.
3281 srcThread->removeEffectChain_l(chain);
3282
3283 // transfer all effects one by one so that new effect chain is created on new thread with
3284 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003285 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003286 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003287 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003288 Vector< sp<EffectModule> > removed;
3289 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003290 while (effect != 0) {
3291 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003292 removed.add(effect);
3293 status = dstThread->addEffect_l(effect);
3294 if (status != NO_ERROR) {
3295 break;
3296 }
Eric Laurentec35a142011-10-05 17:42:25 -07003297 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3298 if (effect->state() == EffectModule::ACTIVE ||
3299 effect->state() == EffectModule::STOPPING) {
3300 effect->start();
3301 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003302 // if the move request is not received from audio policy manager, the effect must be
3303 // re-registered with the new strategy and output
3304 if (dstChain == 0) {
3305 dstChain = effect->chain().promote();
3306 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003307 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003308 status = NO_INIT;
3309 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003310 }
3311 strategy = dstChain->strategy();
3312 }
3313 if (reRegister) {
3314 AudioSystem::unregisterEffect(effect->id());
3315 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003316 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003317 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003318 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003319 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003320 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003321 }
Eric Laurentde070132010-07-13 04:45:46 -07003322 effect = chain->getEffectFromId_l(0);
3323 }
3324
Eric Laurent5baf2af2013-09-12 17:37:00 -07003325 if (status != NO_ERROR) {
3326 for (size_t i = 0; i < removed.size(); i++) {
3327 srcThread->addEffect_l(removed[i]);
3328 if (dstChain != 0 && reRegister) {
3329 AudioSystem::unregisterEffect(removed[i]->id());
3330 AudioSystem::registerEffect(&removed[i]->desc(),
3331 srcThread->id(),
3332 strategy,
3333 sessionId,
3334 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003335 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003336 }
3337 }
3338 }
3339
3340 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341}
3342
Eric Laurent5baf2af2013-09-12 17:37:00 -07003343bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003344{
3345 if (mGlobalEffectEnableTime != 0 &&
3346 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3347 return true;
3348 }
3349
3350 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3351 sp<EffectChain> ec =
3352 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003353 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003354 return true;
3355 }
3356 }
3357 return false;
3358}
3359
Eric Laurent5baf2af2013-09-12 17:37:00 -07003360void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003361{
3362 Mutex::Autolock _l(mLock);
3363
3364 mGlobalEffectEnableTime = systemTime();
3365
3366 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3367 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3368 if (t->mType == ThreadBase::OFFLOAD) {
3369 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3370 }
3371 }
3372
3373}
3374
Eric Laurentaaa44472014-09-12 17:41:50 -07003375status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3376{
Eric Laurentd8365c52017-07-16 15:27:05 -07003377 // clear possible suspended state before parking the chain so that it starts in default state
3378 // when attached to a new record thread
3379 chain->setEffectSuspended_l(FX_IID_AEC, false);
3380 chain->setEffectSuspended_l(FX_IID_NS, false);
3381
Glenn Kastend848eb42016-03-08 13:42:11 -08003382 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003383 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003384 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003385 if (index >= 0) {
3386 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3387 return ALREADY_EXISTS;
3388 }
3389 mOrphanEffectChains.add(session, chain);
3390 return NO_ERROR;
3391}
3392
3393sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3394{
3395 sp<EffectChain> chain;
3396 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003397 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003398 if (index >= 0) {
3399 chain = mOrphanEffectChains.valueAt(index);
3400 mOrphanEffectChains.removeItemsAt(index);
3401 }
3402 return chain;
3403}
3404
3405bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3406{
3407 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003408 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003409 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003410 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003411 if (index >= 0) {
3412 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003413 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003414 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003415 mOrphanEffectChains.removeItemsAt(index);
3416 }
3417 return true;
3418 }
3419 return false;
3420}
3421
3422
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423// ----------------------------------------------------------------------------
3424
3425status_t AudioFlinger::onTransact(
3426 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3427{
3428 return BnAudioFlinger::onTransact(code, data, reply, flags);
3429}
3430
Glenn Kasten63238ef2015-03-02 15:50:29 -08003431} // namespace android