blob: 47dbabfeb4bbef471b257de0d4c054caba01d463 [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
Andy Hunga8115dc2018-08-24 15:51:59 -0700528 // dump historical threads in the last 10 seconds
529 const std::string threadLog = mThreadLog.dumpToString(
530 "Historical Thread Log ", 0 /* lines */,
531 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
532 write(fd, threadLog.c_str(), threadLog.size());
533
rago3bd1c872016-09-26 12:58:14 -0700534 BUFLOG_RESET;
535
Glenn Kastend65d73c2012-06-22 17:21:07 -0700536 if (locked) {
537 mLock.unlock();
538 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800539
Andy Hung8946a282018-04-19 20:04:56 -0700540#ifdef TEE_SINK
541 // NBAIO_Tee dump is safe to call outside of AF lock.
542 NBAIO_Tee::dumpAll(fd, "_DUMP");
543#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800544 // append a copy of media.log here by forwarding fd to it, but don't attempt
545 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700546 if (sMediaLogServiceAsBinder != 0) {
547 dprintf(fd, "\nmedia.log:\n");
548 Vector<String16> args;
549 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800550 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700551
552 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700553 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700554 bool unreachableMemory = false;
555 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700556 if (arg == String16("-m")) {
557 dumpMem = true;
558 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700559 unreachableMemory = true;
560 }
561 }
562
Andy Hung07b745e2016-05-23 16:21:07 -0700563 if (dumpMem) {
564 dprintf(fd, "\nDumping memory:\n");
565 std::string s = dumpMemoryAddresses(100 /* limit */);
566 write(fd, s.c_str(), s.size());
567 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700568 if (unreachableMemory) {
569 dprintf(fd, "\nDumping unreachable memory:\n");
570 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700571 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700572 write(fd, s.c_str(), s.size());
573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 }
575 return NO_ERROR;
576}
577
Eric Tan1882f162018-08-02 18:05:39 -0700578Json::Value AudioFlinger::getJsonDump()
Eric Tan7b651152018-07-13 10:17:19 -0700579{
Eric Tan1882f162018-08-02 18:05:39 -0700580 Json::Value root(Json::objectValue);
Eric Tan7b651152018-07-13 10:17:19 -0700581 const bool locked = dumpTryLock(mLock);
582
583 // failed to lock - AudioFlinger is probably deadlocked
584 if (!locked) {
Eric Tan1882f162018-08-02 18:05:39 -0700585 root["deadlock_message"] = kDeadlockedString;
Eric Tan7b651152018-07-13 10:17:19 -0700586 }
587 // FIXME risky to access data structures without a lock held?
588
Eric Tan1882f162018-08-02 18:05:39 -0700589 Json::Value playbackThreads = Json::arrayValue;
Eric Tan7b651152018-07-13 10:17:19 -0700590 // dump playback threads
591 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Tan1882f162018-08-02 18:05:39 -0700592 playbackThreads.append(mPlaybackThreads.valueAt(i)->getJsonDump());
Eric Tan7b651152018-07-13 10:17:19 -0700593 }
Eric Tan7b651152018-07-13 10:17:19 -0700594
595 if (locked) {
596 mLock.unlock();
597 }
598
Eric Tan1882f162018-08-02 18:05:39 -0700599 root["playback_threads"] = playbackThreads;
600
601 return root;
Eric Tan7b651152018-07-13 10:17:19 -0700602}
603
Eric Laurent021cf962014-05-13 10:18:14 -0700604sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800605{
Eric Laurent021cf962014-05-13 10:18:14 -0700606 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800607 // If pid is already in the mClients wp<> map, then use that entry
608 // (for which promote() is always != 0), otherwise create a new entry and Client.
609 sp<Client> client = mClients.valueFor(pid).promote();
610 if (client == 0) {
611 client = new Client(this, pid);
612 mClients.add(pid, client);
613 }
614
615 return client;
616}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617
Glenn Kasten9e58b552013-01-18 15:09:48 -0800618sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
619{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700620 // If there is no memory allocated for logs, return a dummy writer that does nothing.
621 // Similarly if we can't contact the media.log service, also return a dummy writer.
622 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800623 return new NBLog::Writer();
624 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700625 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
626 // If allocation fails, consult the vector of previously unregistered writers
627 // and garbage-collect one or more them until an allocation succeeds
628 if (shared == 0) {
629 Mutex::Autolock _l(mUnregisteredWritersLock);
630 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
631 {
632 // Pick the oldest stale writer to garbage-collect
633 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
634 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700635 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700636 // Now the media.log remote reference to IMemory is gone. When our last local
637 // reference to IMemory also drops to zero at end of this block,
638 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
639 }
640 // Re-attempt the allocation
641 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
642 if (shared != 0) {
643 goto success;
644 }
645 }
646 // Even after garbage-collecting all old writers, there is still not enough memory,
647 // so return a dummy writer
648 return new NBLog::Writer();
649 }
650success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800651 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
652 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
653 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700654 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800655 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800656}
657
658void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
659{
Glenn Kasten685ef092013-02-04 08:15:34 -0800660 if (writer == 0) {
661 return;
662 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800663 sp<IMemory> iMemory(writer->getIMemory());
664 if (iMemory == 0) {
665 return;
666 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700667 // Rather than removing the writer immediately, append it to a queue of old writers to
668 // be garbage-collected later. This allows us to continue to view old logs for a while.
669 Mutex::Autolock _l(mUnregisteredWritersLock);
670 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800671}
672
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673// IAudioFlinger interface
674
Eric Laurent21da6472017-11-09 16:29:26 -0800675sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
676 CreateTrackOutput& output,
677 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678{
679 sp<PlaybackThread::Track> track;
680 sp<TrackHandle> trackHandle;
681 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800683 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800684 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685
Eric Laurent21da6472017-11-09 16:29:26 -0800686 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700687 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800688 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700689 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800690 ALOGW_IF(clientUid != callingUid,
691 "%s uid %d tried to pass itself off as %d",
692 __FUNCTION__, callingUid, clientUid);
693 clientUid = callingUid;
694 updatePid = true;
695 }
696 pid_t clientPid = input.clientInfo.clientPid;
697 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700698 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800699 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700700 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800701 __func__, callingUid, callingPid, clientPid);
702 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700703 }
704
Eric Laurent21da6472017-11-09 16:29:26 -0800705 audio_session_t sessionId = input.sessionId;
706 if (sessionId == AUDIO_SESSION_ALLOCATE) {
707 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800708 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
709 lStatus = BAD_VALUE;
710 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800711 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800712
Eric Laurent21da6472017-11-09 16:29:26 -0800713 output.sessionId = sessionId;
714 output.outputId = AUDIO_IO_HANDLE_NONE;
715 output.selectedDeviceId = input.selectedDeviceId;
716
717 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200718 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800719 &output.selectedDeviceId, &portId);
720
721 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
722 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
723 goto Exit;
724 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800725 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
726 // but if someone uses binder directly they could bypass that and cause us to crash
727 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000728 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 lStatus = BAD_VALUE;
730 goto Exit;
731 }
732
Glenn Kasten53b5d092014-02-05 10:00:23 -0800733 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800734 if (!audio_is_output_channel(input.config.channel_mask)) {
735 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800736 lStatus = BAD_VALUE;
737 goto Exit;
738 }
739
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700740 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800741 if (!audio_is_valid_format(input.config.format)) {
742 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700743 lStatus = BAD_VALUE;
744 goto Exit;
745 }
746
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 {
748 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800749 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800751 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 lStatus = BAD_VALUE;
753 goto Exit;
754 }
755
Eric Laurent21da6472017-11-09 16:29:26 -0800756 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757
Glenn Kastene848bd92014-03-13 15:00:32 -0700758 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800759 // check if an effect chain with the same session ID is present on another
760 // output thread and move it here.
761 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
762 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
763 if (mPlaybackThreads.keyAt(i) != output.outputId) {
764 uint32_t sessions = t->hasAudioSession(sessionId);
765 if (sessions & ThreadBase::EFFECT_SESSION) {
766 effectThread = t.get();
767 break;
Eric Laurentde070132010-07-13 04:45:46 -0700768 }
769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 }
Eric Laurent21da6472017-11-09 16:29:26 -0800771 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772
Eric Laurent21da6472017-11-09 16:29:26 -0800773 output.sampleRate = input.config.sample_rate;
774 output.frameCount = input.frameCount;
775 output.notificationFrameCount = input.notificationFrameCount;
776 output.flags = input.flags;
777
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700778 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
779 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800780 &output.frameCount, &output.notificationFrameCount,
781 input.notificationsPerBuffer, input.speed,
782 input.sharedBuffer, sessionId, &output.flags,
783 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800784 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700785 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700786
Eric Laurent21da6472017-11-09 16:29:26 -0800787 output.afFrameCount = thread->frameCount();
788 output.afSampleRate = thread->sampleRate();
789 output.afLatencyMs = thread->latency();
Andy Hungfb8ede22018-09-12 19:03:24 -0700790 output.trackId = track->id();
Eric Laurent21da6472017-11-09 16:29:26 -0800791
Eric Laurent39e94f82010-07-28 01:32:47 -0700792 // move effect chain to this output thread if an effect on same session was waiting
793 // for a track to be created
794 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700795 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700796 Mutex::Autolock _dl(thread->mLock);
797 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800798 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700799 }
Eric Laurenta011e352012-03-29 15:51:43 -0700800
801 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700802 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800803 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700804 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700805 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700806 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700807 } else {
808 mPendingSyncEvents[i]->cancel();
809 }
Eric Laurenta011e352012-03-29 15:51:43 -0700810 mPendingSyncEvents.removeAt(i);
811 i--;
812 }
813 }
814 }
Glenn Kastene198c362013-08-13 09:13:36 -0700815
Eric Laurent21da6472017-11-09 16:29:26 -0800816 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 }
Glenn Kastene198c362013-08-13 09:13:36 -0700818
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700819 if (lStatus != NO_ERROR) {
820 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700821 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700822 // Don't hold mClientLock when releasing the reference on the track as the
823 // destructor will acquire it.
824 {
825 Mutex::Autolock _cl(mClientLock);
826 client.clear();
827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700829 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 }
831
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700832 // return handle to client
833 trackHandle = new TrackHandle(track);
834
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800836 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700837 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800838 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700839 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 return trackHandle;
841}
842
Glenn Kasten2c073da2016-02-26 09:14:08 -0800843uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844{
845 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800846 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800848 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 return 0;
850 }
851 return thread->sampleRate();
852}
853
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800854audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855{
856 Mutex::Autolock _l(mLock);
857 PlaybackThread *thread = checkPlaybackThread_l(output);
858 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000859 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800860 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861 }
862 return thread->format();
863}
864
Glenn Kasten2c073da2016-02-26 09:14:08 -0800865size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866{
867 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800868 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800870 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 return 0;
872 }
Glenn Kasten58912562012-04-03 10:45:00 -0700873 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
874 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 return thread->frameCount();
876}
877
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700878size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
879{
880 Mutex::Autolock _l(mLock);
881 ThreadBase *thread = checkThread_l(ioHandle);
882 if (thread == NULL) {
883 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
884 return 0;
885 }
886 return thread->frameCountHAL();
887}
888
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800889uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890{
891 Mutex::Autolock _l(mLock);
892 PlaybackThread *thread = checkPlaybackThread_l(output);
893 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800894 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 return 0;
896 }
897 return thread->latency();
898}
899
900status_t AudioFlinger::setMasterVolume(float value)
901{
Eric Laurenta1884f92011-08-23 08:25:03 -0700902 status_t ret = initCheck();
903 if (ret != NO_ERROR) {
904 return ret;
905 }
906
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907 // check calling permissions
908 if (!settingsAllowed()) {
909 return PERMISSION_DENIED;
910 }
911
Eric Laurenta4c5a552012-03-29 10:12:40 -0700912 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700913 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700914
John Grossmanee578c02012-07-23 17:05:46 -0700915 // Set master volume in the HALs which support it.
916 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
917 AutoMutex lock(mHardwareLock);
918 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800919
John Grossmanee578c02012-07-23 17:05:46 -0700920 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
921 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700922 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800923 }
John Grossmanee578c02012-07-23 17:05:46 -0700924 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926
John Grossmanee578c02012-07-23 17:05:46 -0700927 // Now set the master volume in each playback thread. Playback threads
928 // assigned to HALs which do not have master volume support will apply
929 // master volume during the mix operation. Threads with HALs which do
930 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700931 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
932 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
933 continue;
934 }
John Grossmanee578c02012-07-23 17:05:46 -0700935 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700936 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937
938 return NO_ERROR;
939}
940
Glenn Kastenf78aee72012-01-04 11:00:47 -0800941status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942{
Eric Laurenta1884f92011-08-23 08:25:03 -0700943 status_t ret = initCheck();
944 if (ret != NO_ERROR) {
945 return ret;
946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947
948 // check calling permissions
949 if (!settingsAllowed()) {
950 return PERMISSION_DENIED;
951 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800952 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000953 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 return BAD_VALUE;
955 }
956
957 { // scope for the lock
958 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700959 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700961 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962 mHardwareStatus = AUDIO_HW_IDLE;
963 }
964
965 if (NO_ERROR == ret) {
966 Mutex::Autolock _l(mLock);
967 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800968 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700969 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970 }
971
972 return ret;
973}
974
975status_t AudioFlinger::setMicMute(bool state)
976{
Eric Laurenta1884f92011-08-23 08:25:03 -0700977 status_t ret = initCheck();
978 if (ret != NO_ERROR) {
979 return ret;
980 }
981
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 // check calling permissions
983 if (!settingsAllowed()) {
984 return PERMISSION_DENIED;
985 }
986
987 AutoMutex lock(mHardwareLock);
988 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700989 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700990 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
991 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700992 if (result != NO_ERROR) {
993 ret = result;
994 }
995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996 mHardwareStatus = AUDIO_HW_IDLE;
997 return ret;
998}
999
1000bool AudioFlinger::getMicMute() const
1001{
Eric Laurenta1884f92011-08-23 08:25:03 -07001002 status_t ret = initCheck();
1003 if (ret != NO_ERROR) {
1004 return false;
1005 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001006 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001007 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001008 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001010 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001011 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1012 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001013 if (result == NO_ERROR) {
1014 mute = mute && state;
1015 }
1016 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001018
1019 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020}
1021
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001022void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1023{
1024 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1025
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001026 AutoMutex lock(mLock);
1027 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001028 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1029 }
1030 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1031 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001032 }
1033}
1034
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035status_t AudioFlinger::setMasterMute(bool muted)
1036{
John Grossmand8f178d2012-07-20 14:51:35 -07001037 status_t ret = initCheck();
1038 if (ret != NO_ERROR) {
1039 return ret;
1040 }
1041
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 // check calling permissions
1043 if (!settingsAllowed()) {
1044 return PERMISSION_DENIED;
1045 }
1046
John Grossmanee578c02012-07-23 17:05:46 -07001047 Mutex::Autolock _l(mLock);
1048 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001049
John Grossmanee578c02012-07-23 17:05:46 -07001050 // Set master mute in the HALs which support it.
1051 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1052 AutoMutex lock(mHardwareLock);
1053 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001054
John Grossmanee578c02012-07-23 17:05:46 -07001055 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1056 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001057 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001058 }
John Grossmanee578c02012-07-23 17:05:46 -07001059 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001060 }
1061
John Grossmanee578c02012-07-23 17:05:46 -07001062 // Now set the master mute in each playback thread. Playback threads
1063 // assigned to HALs which do not have master mute support will apply master
1064 // mute during the mix operation. Threads with HALs which do support master
1065 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001066 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1067 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1068 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001069 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070
1071 return NO_ERROR;
1072}
1073
1074float AudioFlinger::masterVolume() const
1075{
Glenn Kasten98067102011-12-13 11:47:54 -08001076 Mutex::Autolock _l(mLock);
1077 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078}
1079
1080bool AudioFlinger::masterMute() const
1081{
Glenn Kasten98067102011-12-13 11:47:54 -08001082 Mutex::Autolock _l(mLock);
1083 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084}
1085
John Grossman4ff14ba2012-02-08 16:37:41 -08001086float AudioFlinger::masterVolume_l() const
1087{
John Grossman4ff14ba2012-02-08 16:37:41 -08001088 return mMasterVolume;
1089}
1090
John Grossmand8f178d2012-07-20 14:51:35 -07001091bool AudioFlinger::masterMute_l() const
1092{
John Grossmanee578c02012-07-23 17:05:46 -07001093 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001094}
1095
Eric Laurent223fd5c2014-11-11 13:43:36 -08001096status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1097{
1098 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001099 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001100 return BAD_VALUE;
1101 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001102 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1103 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1104 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001105 return PERMISSION_DENIED;
1106 }
1107
1108 return NO_ERROR;
1109}
1110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001111status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1112 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113{
1114 // check calling permissions
1115 if (!settingsAllowed()) {
1116 return PERMISSION_DENIED;
1117 }
1118
Eric Laurent223fd5c2014-11-11 13:43:36 -08001119 status_t status = checkStreamType(stream);
1120 if (status != NO_ERROR) {
1121 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 }
Eric Laurent98e38192018-02-15 18:31:53 -08001123 if (output == AUDIO_IO_HANDLE_NONE) {
1124 return BAD_VALUE;
1125 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001126 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127
1128 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001129 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1130 if (volumeInterface == NULL) {
1131 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 }
Eric Laurent98e38192018-02-15 18:31:53 -08001133 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134
1135 return NO_ERROR;
1136}
1137
Glenn Kastenfff6d712012-01-12 16:38:12 -08001138status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139{
1140 // check calling permissions
1141 if (!settingsAllowed()) {
1142 return PERMISSION_DENIED;
1143 }
1144
Eric Laurent223fd5c2014-11-11 13:43:36 -08001145 status_t status = checkStreamType(stream);
1146 if (status != NO_ERROR) {
1147 return status;
1148 }
1149 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1150
1151 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001152 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 return BAD_VALUE;
1154 }
1155
Eric Laurent93575202011-01-18 18:39:02 -08001156 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001158 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1159 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1160 volumeInterfaces[i]->setStreamMute(stream, muted);
1161 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162
1163 return NO_ERROR;
1164}
1165
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001166float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001168 status_t status = checkStreamType(stream);
1169 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 return 0.0f;
1171 }
Eric Laurent98e38192018-02-15 18:31:53 -08001172 if (output == AUDIO_IO_HANDLE_NONE) {
1173 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 }
1175
Eric Laurent98e38192018-02-15 18:31:53 -08001176 AutoMutex lock(mLock);
1177 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1178 if (volumeInterface == NULL) {
1179 return 0.0f;
1180 }
1181
1182 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183}
1184
Glenn Kastenfff6d712012-01-12 16:38:12 -08001185bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001187 status_t status = checkStreamType(stream);
1188 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 return true;
1190 }
1191
Glenn Kasten6637baa2012-01-09 09:40:36 -08001192 AutoMutex lock(mLock);
1193 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194}
1195
Eric Laurent054d9d32015-04-24 08:48:48 -07001196
1197void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1198{
1199 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1200 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1201 }
1202}
1203
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001204// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1205void AudioFlinger::forwardParametersToDownstreamPatches_l(
1206 audio_io_handle_t upStream, const String8& keyValuePairs,
1207 std::function<bool(const sp<PlaybackThread>&)> useThread)
1208{
1209 std::vector<PatchPanel::SoftwarePatch> swPatches;
1210 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1211 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1212 __func__, swPatches.size(), upStream);
1213 for (const auto& swPatch : swPatches) {
1214 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1215 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1216 downStream->setParameters(keyValuePairs);
1217 }
1218 }
1219}
1220
Eric Laurentf1047e82018-04-16 19:18:20 -07001221// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1222// Some keys are used for audio routing and audio path configuration and should be reserved for use
1223// by audio policy and audio flinger for functional, privacy and security reasons.
1224void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1225{
1226 static const String8 kReservedParameters[] = {
1227 String8(AudioParameter::keyRouting),
1228 String8(AudioParameter::keySamplingRate),
1229 String8(AudioParameter::keyFormat),
1230 String8(AudioParameter::keyChannels),
1231 String8(AudioParameter::keyFrameCount),
1232 String8(AudioParameter::keyInputSource),
1233 String8(AudioParameter::keyMonoOutput),
1234 String8(AudioParameter::keyStreamConnect),
1235 String8(AudioParameter::keyStreamDisconnect),
1236 String8(AudioParameter::keyStreamSupportedFormats),
1237 String8(AudioParameter::keyStreamSupportedChannels),
1238 String8(AudioParameter::keyStreamSupportedSamplingRates),
1239 };
1240
Andy Hung4ef19fa2018-05-15 19:35:29 -07001241 if (isAudioServerUid(callingUid)) {
1242 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001243 }
1244
1245 AudioParameter param = AudioParameter(keyValuePairs);
1246 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001247 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001248 for (auto& key : kReservedParameters) {
1249 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001250 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001251 param.remove(key);
1252 }
1253 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001254 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1255 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001256 keyValuePairs = param.toString();
1257}
1258
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001259void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1260 size_t rejectedKVPSize, const String8& rejectedKVPs,
1261 uid_t callingUid) {
1262 auto prefix = String8::format("UID %5d", callingUid);
1263 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1264 if (rejectedKVPSize != 0) {
1265 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1266 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1267 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1268 } else {
1269 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1270 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1271 }
1272}
1273
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001274status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275{
Eric Laurentf1047e82018-04-16 19:18:20 -07001276 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1277 ioHandle, keyValuePairs.string(),
1278 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001279
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280 // check calling permissions
1281 if (!settingsAllowed()) {
1282 return PERMISSION_DENIED;
1283 }
1284
Eric Laurentf1047e82018-04-16 19:18:20 -07001285 String8 filteredKeyValuePairs = keyValuePairs;
1286 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1287
1288 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1289
Glenn Kasten142f5192014-03-25 17:44:59 -07001290 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1291 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001292 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001293 // result will remain NO_INIT if no audio device is present
1294 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001295 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001296 AutoMutex lock(mHardwareLock);
1297 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1298 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001299 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001300 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001301 // return success if at least one audio device accepts the parameters as not all
1302 // HALs are requested to support all parameters. If no audio device supports the
1303 // requested parameters, the last error is reported.
1304 if (final_result != NO_ERROR) {
1305 final_result = result;
1306 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001307 }
1308 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001309 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001310 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001311 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001312 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001313 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1314 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001315 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001316 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001317 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001318 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001319 }
1320 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001321 String8 screenState;
1322 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001323 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (isOff != (AudioFlinger::mScreenState & 1)) {
1325 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001326 }
1327 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001328 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001329 }
1330
1331 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1332 // and the thread is exited once the lock is released
1333 sp<ThreadBase> thread;
1334 {
1335 Mutex::Autolock _l(mLock);
1336 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001337 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001339 if (thread == 0) {
1340 thread = checkMmapThread_l(ioHandle);
1341 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001342 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001343 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001344 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001345 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001346 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1347 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001348 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001349 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350 }
1351 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001352 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001353 status_t result = thread->setParameters(filteredKeyValuePairs);
1354 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1355 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356 }
1357 return BAD_VALUE;
1358}
1359
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001360String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001362 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1363 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364
Eric Laurenta4c5a552012-03-29 10:12:40 -07001365 Mutex::Autolock _l(mLock);
1366
Glenn Kasten142f5192014-03-25 17:44:59 -07001367 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001368 String8 out_s8;
1369
Dima Zavin799a70e2011-04-18 16:57:27 -07001370 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001371 String8 s;
1372 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001373 {
1374 AutoMutex lock(mHardwareLock);
1375 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001376 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1377 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001378 mHardwareStatus = AUDIO_HW_IDLE;
1379 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001380 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001381 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001382 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 }
1384
Eric Laurent6acd1d42017-01-04 14:23:29 -08001385 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1386 if (thread == NULL) {
1387 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1388 if (thread == NULL) {
1389 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1390 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001391 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001392 }
1393 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001395 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396}
1397
Glenn Kastendd8104c2012-07-02 12:42:44 -07001398size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1399 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400{
Eric Laurenta1884f92011-08-23 08:25:03 -07001401 status_t ret = initCheck();
1402 if (ret != NO_ERROR) {
1403 return 0;
1404 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001405 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001406 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001407 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001408 return 0;
1409 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001410
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001411 AutoMutex lock(mHardwareLock);
1412 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001413 audio_config_t config, proposed;
1414 memset(&proposed, 0, sizeof(proposed));
1415 proposed.sample_rate = sampleRate;
1416 proposed.channel_mask = channelMask;
1417 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001418
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001419 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001420 size_t frames;
1421 for (;;) {
1422 // Note: config is currently a const parameter for get_input_buffer_size()
1423 // but we use a copy from proposed in case config changes from the call.
1424 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001425 status_t result = dev->getInputBufferSize(&config, &frames);
1426 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001427 break; // hal success, config is the result
1428 }
1429 // change one parameter of the configuration each iteration to a more "common" value
1430 // to see if the device will support it.
1431 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1432 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1433 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1434 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1435 } else {
1436 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1437 "format %#x, channelMask 0x%X",
1438 sampleRate, format, channelMask);
1439 break; // retries failed, break out of loop with frames == 0.
1440 }
1441 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001442 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001443 if (frames > 0 && config.sample_rate != sampleRate) {
1444 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1445 }
1446 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447}
1448
Glenn Kasten5f972c02014-01-13 09:59:31 -08001449uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451 Mutex::Autolock _l(mLock);
1452
1453 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1454 if (recordThread != NULL) {
1455 return recordThread->getInputFramesLost();
1456 }
1457 return 0;
1458}
1459
1460status_t AudioFlinger::setVoiceVolume(float value)
1461{
Eric Laurenta1884f92011-08-23 08:25:03 -07001462 status_t ret = initCheck();
1463 if (ret != NO_ERROR) {
1464 return ret;
1465 }
1466
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467 // check calling permissions
1468 if (!settingsAllowed()) {
1469 return PERMISSION_DENIED;
1470 }
1471
1472 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001473 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001474 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001475 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476 mHardwareStatus = AUDIO_HW_IDLE;
1477
1478 return ret;
1479}
1480
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001481status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001482 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 Mutex::Autolock _l(mLock);
1485
1486 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1487 if (playbackThread != NULL) {
1488 return playbackThread->getRenderPosition(halFrames, dspFrames);
1489 }
1490
1491 return BAD_VALUE;
1492}
1493
1494void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1495{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001497 if (client == 0) {
1498 return;
1499 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001500 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001501 {
1502 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001503 if (mNotificationClients.indexOfKey(pid) < 0) {
1504 sp<NotificationClient> notificationClient = new NotificationClient(this,
1505 client,
1506 pid);
1507 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508
Eric Laurent021cf962014-05-13 10:18:14 -07001509 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510
Marco Nelissen06b46062014-11-14 07:58:25 -08001511 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001512 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001513 }
1514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515
Eric Laurent021cf962014-05-13 10:18:14 -07001516 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001517 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001518 // the config change is always sent from playback or record threads to avoid deadlock
1519 // with AudioSystem::gLock
1520 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001521 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001522 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001524 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001525 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 }
1527}
1528
1529void AudioFlinger::removeNotificationClient(pid_t pid)
1530{
1531 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001532 {
1533 Mutex::Autolock _cl(mClientLock);
1534 mNotificationClients.removeItem(pid);
1535 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001536
Steve Block3856b092011-10-20 11:56:00 +01001537 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001538 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001539 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001540 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001541 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001542 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001543 if (ref->mPid == pid) {
1544 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001545 mAudioSessionRefs.removeAt(i);
1546 delete ref;
1547 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001548 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001549 } else {
1550 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001551 }
1552 }
1553 if (removed) {
1554 purgeStaleEffects_l();
1555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556}
1557
Eric Laurent73e26b62015-04-27 16:55:58 -07001558void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001559 const sp<AudioIoDescriptor>& ioDesc,
1560 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561{
Eric Laurent021cf962014-05-13 10:18:14 -07001562 Mutex::Autolock _l(mClientLock);
1563 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001565 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1566 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
1569}
1570
Eric Laurent021cf962014-05-13 10:18:14 -07001571// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572void AudioFlinger::removeClient_l(pid_t pid)
1573{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001574 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001575 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 mClients.removeItem(pid);
1577}
1578
Eric Laurent717e1282012-06-29 16:36:52 -07001579// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001580sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1581 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001582{
1583 sp<PlaybackThread> thread;
1584
1585 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1586 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1587 ALOG_ASSERT(thread == 0);
1588 thread = mPlaybackThreads.valueAt(i);
1589 }
1590 }
1591
1592 return thread;
1593}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596
1597// ----------------------------------------------------------------------------
1598
1599AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1600 : RefBase(),
1601 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001602 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603{
Andy Hung6f248bb2018-01-23 14:04:37 -08001604 mMemoryDealer = new MemoryDealer(
1605 audioFlinger->getClientSharedHeapSize(),
1606 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607}
1608
Eric Laurent021cf962014-05-13 10:18:14 -07001609// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610AudioFlinger::Client::~Client()
1611{
1612 mAudioFlinger->removeClient_l(mPid);
1613}
1614
Glenn Kasten435dbe62012-01-30 10:15:48 -08001615sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616{
1617 return mMemoryDealer;
1618}
1619
1620// ----------------------------------------------------------------------------
1621
1622AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1623 const sp<IAudioFlingerClient>& client,
1624 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001625 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626{
1627}
1628
1629AudioFlinger::NotificationClient::~NotificationClient()
1630{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631}
1632
Glenn Kasten0f11b512014-01-31 16:18:54 -08001633void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634{
1635 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001636 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637}
1638
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001639// ----------------------------------------------------------------------------
1640AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1641 : mPendingRequests(false) {}
1642
1643
1644void AudioFlinger::MediaLogNotifier::requestMerge() {
1645 AutoMutex _l(mMutex);
1646 mPendingRequests = true;
1647 mCond.signal();
1648}
1649
1650bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001651 // Should already have been checked, but just in case
1652 if (sMediaLogService == 0) {
1653 return false;
1654 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001655 // Wait until there are pending requests
1656 {
1657 AutoMutex _l(mMutex);
1658 mPendingRequests = false; // to ignore past requests
1659 while (!mPendingRequests) {
1660 mCond.wait(mMutex);
1661 // TODO may also need an exitPending check
1662 }
1663 mPendingRequests = false;
1664 }
1665 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001666 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001667 usleep(kPostTriggerSleepPeriod);
1668 return true;
1669}
1670
1671void AudioFlinger::requestLogMerge() {
1672 mMediaLogNotifier->requestMerge();
1673}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674
1675// ----------------------------------------------------------------------------
1676
Eric Laurentf14db3c2017-12-08 14:20:36 -08001677sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1678 CreateRecordOutput& output,
1679 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680{
1681 sp<RecordThread::RecordTrack> recordTrack;
1682 sp<RecordHandle> recordHandle;
1683 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001685 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001686 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687
Eric Laurentf14db3c2017-12-08 14:20:36 -08001688 output.cblk.clear();
1689 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001690 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001691
Eric Laurentf14db3c2017-12-08 14:20:36 -08001692 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001693 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001694 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001695 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001696 ALOGW_IF(clientUid != callingUid,
1697 "%s uid %d tried to pass itself off as %d",
1698 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001699 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001700 updatePid = true;
1701 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001702 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001703 if (updatePid) {
1704 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001705 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001706 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001707 __func__, callingUid, callingPid, clientPid);
1708 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001709 }
1710
Andy Hung6770c6f2015-04-07 13:43:36 -07001711 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001712 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1713 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001714 lStatus = BAD_VALUE;
1715 goto Exit;
1716 }
1717
Glenn Kasten53b5d092014-02-05 10:00:23 -08001718 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001719 if (!audio_is_input_channel(input.config.channel_mask)) {
1720 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001721 lStatus = BAD_VALUE;
1722 goto Exit;
1723 }
1724
Eric Laurentf14db3c2017-12-08 14:20:36 -08001725 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1726 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1727 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1728 lStatus = BAD_VALUE;
1729 goto Exit;
1730 }
1731
1732 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001733 output.selectedDeviceId = input.selectedDeviceId;
1734 output.flags = input.flags;
1735
1736 client = registerPid(clientPid);
1737
1738 // Not a conventional loop, but a retry loop for at most two iterations total.
1739 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1740 // Exits loop via break on no error of got exit on error
1741 // The sp<> references will be dropped when re-entering scope.
1742 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1743 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001744 // release previously opened input if retrying.
1745 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1746 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001747 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001748 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001749 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001750 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001751 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001752 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1753 sessionId,
1754 // FIXME compare to AudioTrack
1755 clientPid,
1756 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001757 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001758 &input.config,
1759 output.flags, &output.selectedDeviceId, &portId);
1760
Glenn Kasten05997e22014-03-13 15:08:33 -07001761 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001763 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001765 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 lStatus = BAD_VALUE;
1767 goto Exit;
1768 }
1769
Eric Laurentf14db3c2017-12-08 14:20:36 -08001770 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771
Eric Laurentf14db3c2017-12-08 14:20:36 -08001772 output.sampleRate = input.config.sample_rate;
1773 output.frameCount = input.frameCount;
1774 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001775
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001776 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001777 input.config.format, input.config.channel_mask,
1778 &output.frameCount, sessionId,
1779 &output.notificationFrameCount,
1780 clientUid, &output.flags,
1781 input.clientInfo.clientTid,
1782 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001783 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001784
Eric Laurentf14db3c2017-12-08 14:20:36 -08001785 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1786 // audio policy manager without FAST constraint
1787 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001788 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001789 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001790
1791 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001792 goto Exit;
1793 }
1794
1795 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1796 // session and move it to this thread.
1797 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1798 if (chain != 0) {
1799 Mutex::Autolock _l(thread->mLock);
1800 thread->addEffectChain_l(chain);
1801 }
1802 break;
1803 }
1804 // End of retry loop.
1805 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 }
Glenn Kastene198c362013-08-13 09:13:36 -07001807
Eric Laurentf14db3c2017-12-08 14:20:36 -08001808 output.cblk = recordTrack->getCblk();
1809 output.buffers = recordTrack->getBuffers();
Andy Hung6b1c6122018-09-12 19:09:07 -07001810 output.trackId = recordTrack->id();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001811
1812 // return handle to client
1813 recordHandle = new RecordHandle(recordTrack);
1814
1815Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001816 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001817 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001818 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001819 // Don't hold mClientLock when releasing the reference on the track as the
1820 // destructor will acquire it.
1821 {
1822 Mutex::Autolock _cl(mClientLock);
1823 client.clear();
1824 }
Eric Laurent896c9672017-12-08 14:08:45 -08001825 recordTrack.clear();
1826 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001827 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001828 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829 }
1830
Glenn Kasten9156ef32013-08-06 15:39:08 -07001831 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 return recordHandle;
1833}
1834
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001835
1836
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837// ----------------------------------------------------------------------------
1838
Eric Laurenta4c5a552012-03-29 10:12:40 -07001839audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1840{
Eric Laurent44622db2014-08-01 19:00:33 -07001841 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001842 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001843 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001844 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001845 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001846 }
1847 Mutex::Autolock _l(mLock);
1848 return loadHwModule_l(name);
1849}
1850
1851// loadHwModule_l() must be called with AudioFlinger::mLock held
1852audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1853{
1854 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1855 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1856 ALOGW("loadHwModule() module %s already loaded", name);
1857 return mAudioHwDevs.keyAt(i);
1858 }
1859 }
1860
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001861 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001862
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001863 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001864 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001865 ALOGE("loadHwModule() error %d loading 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
1869 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001870 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001871 mHardwareStatus = AUDIO_HW_IDLE;
1872 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001873 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001874 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001875 }
1876
John Grossmanee578c02012-07-23 17:05:46 -07001877 // Check and cache this HAL's level of support for master mute and master
1878 // volume. If this is the first HAL opened, and it supports the get
1879 // methods, use the initial values provided by the HAL as the current
1880 // master mute and volume settings.
1881
1882 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1883 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001884 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001885
1886 if (0 == mAudioHwDevs.size()) {
1887 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001888 float mv;
1889 if (OK == dev->getMasterVolume(&mv)) {
1890 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001891 }
1892
1893 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001894 bool mm;
1895 if (OK == dev->getMasterMute(&mm)) {
1896 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001897 }
1898 }
1899
Eric Laurenta4c5a552012-03-29 10:12:40 -07001900 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001901 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001902 flags = static_cast<AudioHwDevice::Flags>(flags |
1903 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1904 }
1905
1906 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001907 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001908 flags = static_cast<AudioHwDevice::Flags>(flags |
1909 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1910 }
1911
Eric Laurenta4c5a552012-03-29 10:12:40 -07001912 mHardwareStatus = AUDIO_HW_IDLE;
1913 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07001914 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07001915 // An MSD module is inserted before hardware modules in order to mix encoded streams.
1916 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
1917 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001918
Glenn Kastena13cde92016-03-28 15:26:02 -07001919 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001920 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001921
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001922 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001923
1924 return handle;
1925
1926}
1927
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001928// ----------------------------------------------------------------------------
1929
Glenn Kasten3b16c762012-11-14 08:44:39 -08001930uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001931{
1932 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001933 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001934 return thread != NULL ? thread->sampleRate() : 0;
1935}
1936
Glenn Kastene33054e2012-11-14 12:54:39 -08001937size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001938{
1939 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001940 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001941 return thread != NULL ? thread->frameCountHAL() : 0;
1942}
1943
1944// ----------------------------------------------------------------------------
1945
Andy Hung6f248bb2018-01-23 14:04:37 -08001946status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001947{
1948 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001949 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001950 return PERMISSION_DENIED;
1951 }
1952 Mutex::Autolock _l(mLock);
1953 if (mIsDeviceTypeKnown) {
1954 return INVALID_OPERATION;
1955 }
1956 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001957 mTotalMemory = totalMemory;
1958 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1959 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1960 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1961 // though actual setting is determined through device configuration.
1962 constexpr int64_t GB = 1024 * 1024 * 1024;
1963 mClientSharedHeapSize =
1964 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1965 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1966 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1967 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1968 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001969 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001970
1971 // TODO: Cache the client shared heap size in a persistent property.
1972 // It's possible that a native process or Java service or app accesses audioserver
1973 // after it is registered by system server, but before AudioService updates
1974 // the memory info. This would occur immediately after boot or an audioserver
1975 // crash and restore. Before update from AudioService, the client would get the
1976 // minimum heap size.
1977
1978 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1979 (isLowRamDevice ? "true" : "false"),
1980 (long long)mTotalMemory,
1981 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001982 return NO_ERROR;
1983}
1984
Andy Hung6f248bb2018-01-23 14:04:37 -08001985size_t AudioFlinger::getClientSharedHeapSize() const
1986{
1987 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1988 if (heapSizeInBytes != 0) { // read-only property overrides all.
1989 return heapSizeInBytes;
1990 }
1991 return mClientSharedHeapSize;
1992}
1993
Mikhail Naganovdea53042018-04-26 13:10:21 -07001994status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1995{
1996 ALOGV(__func__);
1997
1998 audio_module_handle_t module;
1999 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2000 module = config->ext.device.hw_module;
2001 } else {
2002 module = config->ext.mix.hw_module;
2003 }
2004
2005 Mutex::Autolock _l(mLock);
2006 ssize_t index = mAudioHwDevs.indexOfKey(module);
2007 if (index < 0) {
2008 ALOGW("%s() bad hw module %d", __func__, module);
2009 return BAD_VALUE;
2010 }
2011
2012 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2013 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2014}
2015
Eric Laurent93c3d412014-08-01 14:48:35 -07002016audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2017{
2018 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002019
2020 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2021 if (index >= 0) {
2022 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2023 mHwAvSyncIds.valueAt(index), sessionId);
2024 return mHwAvSyncIds.valueAt(index);
2025 }
2026
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002027 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002028 if (dev == NULL) {
2029 return AUDIO_HW_SYNC_INVALID;
2030 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002031 String8 reply;
2032 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002033 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002034 param = AudioParameter(reply);
2035 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002036
2037 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002038 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002039 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2040 return AUDIO_HW_SYNC_INVALID;
2041 }
2042
2043 // allow only one session for a given HW A/V sync ID.
2044 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2045 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2046 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2047 value, mHwAvSyncIds.keyAt(i));
2048 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002049 break;
2050 }
2051 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002052
2053 mHwAvSyncIds.add(sessionId, value);
2054
2055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2056 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2057 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002058 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002059 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002060 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002061 String8 keyValuePairs = param.toString();
2062 thread->setParameters(keyValuePairs);
2063 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2064 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002065 break;
2066 }
2067 }
2068
2069 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2070 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002071}
2072
Eric Laurent72e3f392015-05-20 14:43:50 -07002073status_t AudioFlinger::systemReady()
2074{
2075 Mutex::Autolock _l(mLock);
2076 ALOGI("%s", __FUNCTION__);
2077 if (mSystemReady) {
2078 ALOGW("%s called twice", __FUNCTION__);
2079 return NO_ERROR;
2080 }
2081 mSystemReady = true;
2082 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2083 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2084 thread->systemReady();
2085 }
2086 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2087 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2088 thread->systemReady();
2089 }
2090 return NO_ERROR;
2091}
2092
jiabin46a76fa2018-01-05 10:18:21 -08002093status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2094{
jiabin9ff780e2018-03-19 18:19:52 -07002095 AutoMutex lock(mHardwareLock);
2096 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2097 status_t status = dev->getMicrophones(microphones);
2098 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002099}
2100
Eric Laurentfa90e842014-10-17 18:12:31 -07002101// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2102void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2103{
2104 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2105 if (index >= 0) {
2106 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2107 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2108 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002109 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002110 String8 keyValuePairs = param.toString();
2111 thread->setParameters(keyValuePairs);
2112 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2113 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002114 }
2115}
2116
2117
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002118// ----------------------------------------------------------------------------
2119
Eric Laurent83b88082014-06-20 18:31:16 -07002120
Eric Laurent6acd1d42017-01-04 14:23:29 -08002121sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002122 audio_io_handle_t *output,
2123 audio_config_t *config,
2124 audio_devices_t devices,
2125 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002126 audio_output_flags_t flags)
2127{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002128 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002129 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002130 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002131 }
2132
Eric Laurentcf2c0212014-07-25 16:20:43 -07002133 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002134 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2135 } else {
2136 // Audio Policy does not currently request a specific output handle.
2137 // If this is ever needed, see openInput_l() for example code.
2138 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2139 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002140 }
Eric Laurent83b88082014-06-20 18:31:16 -07002141
2142 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2143
Eric Laurent83b88082014-06-20 18:31:16 -07002144 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002145 // This if statement allows overriding the audio policy settings
2146 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2147 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2148 // Check only for Normal Mixing mode
2149 if (kEnableExtendedPrecision) {
2150 // Specify format (uncomment one below to choose)
2151 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2152 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2153 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2154 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002155 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002156 }
2157 if (kEnableExtendedChannels) {
2158 // Specify channel mask (uncomment one below to choose)
2159 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2160 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2161 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2162 }
Eric Laurent83b88082014-06-20 18:31:16 -07002163 }
2164
Phil Burk062e67a2015-02-11 13:40:50 -08002165 AudioStreamOut *outputStream = NULL;
2166 status_t status = outHwDev->openOutputStream(
2167 &outputStream,
2168 *output,
2169 devices,
2170 flags,
2171 config,
2172 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002173
2174 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002175
Phil Burk062e67a2015-02-11 13:40:50 -08002176 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002177 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2178 sp<MmapPlaybackThread> thread =
2179 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2180 devices, AUDIO_DEVICE_NONE, mSystemReady);
2181 mMmapThreads.add(*output, thread);
2182 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2183 *output, thread.get());
2184 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002185 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002186 sp<PlaybackThread> thread;
2187 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2188 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2189 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2190 *output, thread.get());
2191 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2192 || !isValidPcmSinkFormat(config->format)
2193 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2194 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2195 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2196 *output, thread.get());
2197 } else {
2198 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2199 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2200 *output, thread.get());
2201 }
2202 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002203 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002204 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002205 }
Eric Laurent83b88082014-06-20 18:31:16 -07002206 }
2207
2208 return 0;
2209}
2210
Eric Laurentcf2c0212014-07-25 16:20:43 -07002211status_t AudioFlinger::openOutput(audio_module_handle_t module,
2212 audio_io_handle_t *output,
2213 audio_config_t *config,
2214 audio_devices_t *devices,
2215 const String8& address,
2216 uint32_t *latencyMs,
2217 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002219 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2220 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002221 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002222 (devices != NULL) ? *devices : 0,
2223 config->sample_rate,
2224 config->format,
2225 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002226 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002228 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002229 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002231
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 Mutex::Autolock _l(mLock);
2233
Eric Laurent6acd1d42017-01-04 14:23:29 -08002234 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002235 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002236 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2237 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2238 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239
Eric Laurent6acd1d42017-01-04 14:23:29 -08002240 // notify client processes of the new output creation
2241 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002242
Eric Laurent6acd1d42017-01-04 14:23:29 -08002243 // the first primary output opened designates the primary hw device
2244 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002245 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002246 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002247
Eric Laurent6acd1d42017-01-04 14:23:29 -08002248 AutoMutex lock(mHardwareLock);
2249 mHardwareStatus = AUDIO_HW_SET_MODE;
2250 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2251 mHardwareStatus = AUDIO_HW_IDLE;
2252 }
2253 } else {
2254 MmapThread *mmapThread = (MmapThread *)thread.get();
2255 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002256 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002257 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 }
2259
Eric Laurentcf2c0212014-07-25 16:20:43 -07002260 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261}
2262
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002263audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2264 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265{
2266 Mutex::Autolock _l(mLock);
2267 MixerThread *thread1 = checkMixerThread_l(output1);
2268 MixerThread *thread2 = checkMixerThread_l(output2);
2269
2270 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002271 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2272 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002273 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 }
2275
Glenn Kasteneeecb982016-02-26 10:44:04 -08002276 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002277 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 thread->addOutputTrack(thread2);
2279 mPlaybackThreads.add(id, thread);
2280 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002281 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 return id;
2283}
2284
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002285status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286{
Glenn Kastend96c5722012-04-25 13:44:49 -07002287 return closeOutput_nonvirtual(output);
2288}
2289
2290status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2291{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 // keep strong reference on the playback thread so that
2293 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002294 sp<PlaybackThread> playbackThread;
2295 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 {
2297 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002298 playbackThread = checkPlaybackThread_l(output);
2299 if (playbackThread != NULL) {
2300 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301
Andy Hungdc099c22018-09-18 13:46:39 -07002302 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002303
Eric Laurent6acd1d42017-01-04 14:23:29 -08002304 if (playbackThread->type() == ThreadBase::MIXER) {
2305 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2306 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2307 DuplicatingThread *dupThread =
2308 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2309 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2310 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002311 }
2312 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002313
2314
Eric Laurent6acd1d42017-01-04 14:23:29 -08002315 mPlaybackThreads.removeItem(output);
2316 // save all effects to the default thread
2317 if (mPlaybackThreads.size()) {
2318 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2319 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002320 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002321 Mutex::Autolock _dl(dstThread->mLock);
2322 Mutex::Autolock _sl(playbackThread->mLock);
2323 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2324 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002325 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2326 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 }
2329 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002330 } else {
2331 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2332 if (mmapThread == 0) {
2333 return BAD_VALUE;
2334 }
Andy Hungdc099c22018-09-18 13:46:39 -07002335 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002336 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002337 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002339 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2340 ioDesc->mIoHandle = output;
2341 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002342 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002344 // The thread entity (active unit of execution) is no longer running here,
2345 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346
Eric Laurent6acd1d42017-01-04 14:23:29 -08002347 if (playbackThread != 0) {
2348 playbackThread->exit();
2349 if (!playbackThread->isDuplicating()) {
2350 closeOutputFinish(playbackThread);
2351 }
2352 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002353 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002354 mmapThread->exit();
2355 AudioStreamOut *out = mmapThread->clearOutput();
2356 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2357 // from now on thread->mOutput is NULL
2358 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 }
2360 return NO_ERROR;
2361}
2362
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002363void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002364{
2365 AudioStreamOut *out = thread->clearOutput();
2366 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2367 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002368 delete out;
2369}
2370
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002371void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002372{
2373 mPlaybackThreads.removeItem(thread->mId);
2374 thread->exit();
2375 closeOutputFinish(thread);
2376}
2377
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002378status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379{
2380 Mutex::Autolock _l(mLock);
2381 PlaybackThread *thread = checkPlaybackThread_l(output);
2382
2383 if (thread == NULL) {
2384 return BAD_VALUE;
2385 }
2386
Steve Block3856b092011-10-20 11:56:00 +01002387 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 thread->suspend();
2389
2390 return NO_ERROR;
2391}
2392
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002393status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394{
2395 Mutex::Autolock _l(mLock);
2396 PlaybackThread *thread = checkPlaybackThread_l(output);
2397
2398 if (thread == NULL) {
2399 return BAD_VALUE;
2400 }
2401
Steve Block3856b092011-10-20 11:56:00 +01002402 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403
2404 thread->restore();
2405
2406 return NO_ERROR;
2407}
2408
Eric Laurentcf2c0212014-07-25 16:20:43 -07002409status_t AudioFlinger::openInput(audio_module_handle_t module,
2410 audio_io_handle_t *input,
2411 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002412 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002413 const String8& address,
2414 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002415 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416{
Eric Laurent83b88082014-06-20 18:31:16 -07002417 Mutex::Autolock _l(mLock);
2418
Glenn Kastene7d66712015-03-05 13:46:52 -08002419 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002420 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002421 }
2422
Eric Laurent6acd1d42017-01-04 14:23:29 -08002423 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002424
2425 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002426 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002427 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002428 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002430 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002431}
Dima Zavin799a70e2011-04-18 16:57:27 -07002432
Eric Laurent6acd1d42017-01-04 14:23:29 -08002433sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002434 audio_io_handle_t *input,
2435 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002436 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002437 const String8& address,
2438 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002439 audio_input_flags_t flags)
2440{
Glenn Kastene7d66712015-03-05 13:46:52 -08002441 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002442 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002443 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002444 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002445 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002446
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002447 // Some flags are specific to framework and must not leak to the HAL.
2448 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2449
Glenn Kasteneeecb982016-02-26 10:44:04 -08002450 // Audio Policy can request a specific handle for hardware hotword.
2451 // The goal here is not to re-open an already opened input.
2452 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002453 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002454 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2455 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2456 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2457 return 0;
2458 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2459 // This should not happen in a transient state with current design.
2460 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2461 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002462 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002463
Eric Laurentcf2c0212014-07-25 16:20:43 -07002464 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002465 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002466 sp<StreamInHalInterface> inStream;
2467 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002468 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002469 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2470 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002471 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002472 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002473 halconfig.sample_rate,
2474 halconfig.format,
2475 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002476 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002477 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002479 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002480 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002481 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002482 audio_is_linear_pcm(config->format) &&
2483 audio_is_linear_pcm(halconfig.format) &&
2484 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002485 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2486 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002487 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002488 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002489 inStream.clear();
2490 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002491 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002492 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 }
2494
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002495 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002496 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002497 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2498 sp<MmapCaptureThread> thread =
2499 new MmapCaptureThread(this, *input,
2500 inHwDev, inputStream,
2501 primaryOutputDevice_l(), devices, mSystemReady);
2502 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002503 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2504 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002505 return thread;
2506 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002507 // Start record thread
2508 // RecordThread requires both input and output device indication to forward to audio
2509 // pre processing modules
2510 sp<RecordThread> thread = new RecordThread(this,
2511 inputStream,
2512 *input,
2513 primaryOutputDevice_l(),
2514 devices,
2515 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002516 );
2517 mRecordThreads.add(*input, thread);
2518 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2519 return thread;
2520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 }
2522
Eric Laurentcf2c0212014-07-25 16:20:43 -07002523 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 return 0;
2525}
2526
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002527status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528{
Glenn Kastend96c5722012-04-25 13:44:49 -07002529 return closeInput_nonvirtual(input);
2530}
2531
2532status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2533{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 // keep strong reference on the record thread so that
2535 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002536 sp<RecordThread> recordThread;
2537 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 {
2539 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002540 recordThread = checkRecordThread_l(input);
2541 if (recordThread != 0) {
2542 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543
Andy Hungdc099c22018-09-18 13:46:39 -07002544 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002545
Eric Laurent6acd1d42017-01-04 14:23:29 -08002546 // If we still have effect chains, it means that a client still holds a handle
2547 // on at least one effect. We must either move the chain to an existing thread with the
2548 // same session ID or put it aside in case a new record thread is opened for a
2549 // new capture on the same session
2550 sp<EffectChain> chain;
2551 {
2552 Mutex::Autolock _sl(recordThread->mLock);
2553 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2554 // Note: maximum one chain per record thread
2555 if (effectChains.size() != 0) {
2556 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002557 }
2558 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002559 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002560 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002561 // This should only happen in case of overlap between one thread tear down and the
2562 // creation of its replacement
2563 size_t i;
2564 for (i = 0; i < mRecordThreads.size(); i++) {
2565 sp<RecordThread> t = mRecordThreads.valueAt(i);
2566 if (t == recordThread) {
2567 continue;
2568 }
2569 if (t->hasAudioSession(chain->sessionId()) != 0) {
2570 Mutex::Autolock _l(t->mLock);
2571 ALOGV("closeInput() found thread %d for effect session %d",
2572 t->id(), chain->sessionId());
2573 t->addEffectChain_l(chain);
2574 break;
2575 }
2576 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002577 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002578 if (i == mRecordThreads.size()) {
2579 putOrphanEffectChain_l(chain);
2580 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002581 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002582 mRecordThreads.removeItem(input);
2583 } else {
2584 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2585 if (mmapThread == 0) {
2586 return BAD_VALUE;
2587 }
Andy Hungdc099c22018-09-18 13:46:39 -07002588 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002589 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002590 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002591 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2592 ioDesc->mIoHandle = input;
2593 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594 }
Eric Laurent83b88082014-06-20 18:31:16 -07002595 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2596 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002597 if (recordThread != 0) {
2598 closeInputFinish(recordThread);
2599 } else if (mmapThread != 0) {
2600 mmapThread->exit();
2601 AudioStreamIn *in = mmapThread->clearInput();
2602 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2603 // from now on thread->mInput is NULL
2604 delete in;
2605 }
Eric Laurent83b88082014-06-20 18:31:16 -07002606 return NO_ERROR;
2607}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002609void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002610{
2611 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002612 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002613 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002614 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002615 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002616}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002618void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002619{
2620 mRecordThreads.removeItem(thread->mId);
2621 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622}
2623
Glenn Kastend2304db2014-02-03 07:40:31 -08002624status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625{
2626 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002627 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628
2629 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2630 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002631 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002632 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002633 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2634 mMmapThreads[i]->invalidateTracks(stream);
2635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 return NO_ERROR;
2637}
2638
2639
Glenn Kasteneeecb982016-02-26 10:44:04 -08002640audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641{
Glenn Kasten9d003132016-04-06 14:38:09 -07002642 // This is a binder API, so a malicious client could pass in a bad parameter.
2643 // Check for that before calling the internal API nextUniqueId().
2644 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2645 ALOGE("newAudioUniqueId invalid use %d", use);
2646 return AUDIO_UNIQUE_ID_ALLOCATE;
2647 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002648 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649}
2650
Glenn Kastend848eb42016-03-08 13:42:11 -08002651void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002652{
2653 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002654 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002655 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002656 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2657 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002658 caller = pid;
2659 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002660
Eric Laurent021cf962014-05-13 10:18:14 -07002661 {
2662 Mutex::Autolock _cl(mClientLock);
2663 // Ignore requests received from processes not known as notification client. The request
2664 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2665 // called from a different pid leaving a stale session reference. Also we don't know how
2666 // to clear this reference if the client process dies.
2667 if (mNotificationClients.indexOfKey(caller) < 0) {
2668 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2669 return;
2670 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002671 }
2672
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002673 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002674 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002675 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002676 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2677 ref->mCnt++;
2678 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002679 return;
2680 }
2681 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002682 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2683 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002684}
2685
Glenn Kastend848eb42016-03-08 13:42:11 -08002686void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002687{
2688 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002689 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002690 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002691 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2692 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002693 caller = pid;
2694 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002695 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002696 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002697 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002698 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2699 ref->mCnt--;
2700 ALOGV(" decremented refcount to %d", ref->mCnt);
2701 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002702 mAudioSessionRefs.removeAt(i);
2703 delete ref;
2704 purgeStaleEffects_l();
2705 }
2706 return;
2707 }
2708 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002709 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002710 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002711 ALOGW_IF(!isAudioServerUid(callerUid),
2712 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002713}
2714
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002715bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2716{
2717 size_t num = mAudioSessionRefs.size();
2718 for (size_t i = 0; i < num; i++) {
2719 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2720 if (ref->mSessionid == audioSession) {
2721 return true;
2722 }
2723 }
2724 return false;
2725}
2726
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002727void AudioFlinger::purgeStaleEffects_l() {
2728
Steve Block3856b092011-10-20 11:56:00 +01002729 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002730
2731 Vector< sp<EffectChain> > chains;
2732
2733 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2734 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002735 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002736 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2737 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002738 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2739 chains.push(ec);
2740 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002741 }
2742 }
2743 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2744 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002745 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002746 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2747 sp<EffectChain> ec = t->mEffectChains[j];
2748 chains.push(ec);
2749 }
2750 }
2751
2752 for (size_t i = 0; i < chains.size(); i++) {
2753 sp<EffectChain> ec = chains[i];
2754 int sessionid = ec->sessionId();
2755 sp<ThreadBase> t = ec->mThread.promote();
2756 if (t == 0) {
2757 continue;
2758 }
2759 size_t numsessionrefs = mAudioSessionRefs.size();
2760 bool found = false;
2761 for (size_t k = 0; k < numsessionrefs; k++) {
2762 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002763 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002764 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002765 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002766 found = true;
2767 break;
2768 }
2769 }
2770 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002771 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002772 // remove all effects from the chain
2773 while (ec->mEffects.size()) {
2774 sp<EffectModule> effect = ec->mEffects[0];
2775 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002776 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002777 if (effect->purgeHandles()) {
2778 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002779 }
2780 AudioSystem::unregisterEffect(effect->id());
2781 }
2782 }
2783 }
2784 return;
2785}
2786
Andy Hungdc099c22018-09-18 13:46:39 -07002787// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2788void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2789{
2790 audio_utils::FdToString fdToString;
2791 const int fd = fdToString.fd();
2792 if (fd >= 0) {
2793 thread->dump(fd, {} /* args */);
2794 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2795 }
2796}
2797
Glenn Kasteneeecb982016-02-26 10:44:04 -08002798// checkThread_l() must be called with AudioFlinger::mLock held
2799AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2800{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002801 ThreadBase *thread = checkMmapThread_l(ioHandle);
2802 if (thread == 0) {
2803 switch (audio_unique_id_get_use(ioHandle)) {
2804 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2805 thread = checkPlaybackThread_l(ioHandle);
2806 break;
2807 case AUDIO_UNIQUE_ID_USE_INPUT:
2808 thread = checkRecordThread_l(ioHandle);
2809 break;
2810 default:
2811 break;
2812 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002813 }
2814 return thread;
2815}
2816
Mathias Agopian65ab4712010-07-14 17:59:35 -07002817// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002818AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819{
Glenn Kastena1117922012-01-26 10:53:32 -08002820 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821}
2822
2823// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002824AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825{
2826 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002827 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828}
2829
2830// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002831AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832{
Glenn Kastena1117922012-01-26 10:53:32 -08002833 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834}
2835
Eric Laurent6acd1d42017-01-04 14:23:29 -08002836// checkMmapThread_l() must be called with AudioFlinger::mLock held
2837AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2838{
2839 return mMmapThreads.valueFor(io).get();
2840}
2841
2842
2843// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2844AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2845{
Eric Laurent7459b902017-04-19 18:10:41 -07002846 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002847 if (volumeInterface == nullptr) {
2848 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2849 if (mmapThread != nullptr) {
2850 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002851 MmapPlaybackThread *mmapPlaybackThread =
2852 static_cast<MmapPlaybackThread *>(mmapThread);
2853 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002854 }
2855 }
2856 }
2857 return volumeInterface;
2858}
2859
2860Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2861{
2862 Vector <VolumeInterface *> volumeInterfaces;
2863 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002864 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002865 }
2866 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2867 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002868 MmapPlaybackThread *mmapPlaybackThread =
2869 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2870 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002871 }
2872 }
2873 return volumeInterfaces;
2874}
2875
Glenn Kasteneeecb982016-02-26 10:44:04 -08002876audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877{
Glenn Kasten9d003132016-04-06 14:38:09 -07002878 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002879 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002880 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2881 for (int retry = 0; retry < maxRetries; retry++) {
2882 // The cast allows wraparound from max positive to min negative instead of abort
2883 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2884 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2885 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2886 // allow wrap by skipping 0 and -1 for session ids
2887 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2888 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2889 return (audio_unique_id_t) (base | use);
2890 }
2891 }
2892 // We have no way of recovering from wraparound
2893 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2894 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895}
2896
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002897AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002898{
2899 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2900 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002901 if(thread->isDuplicating()) {
2902 continue;
2903 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002904 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002905 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002906 return thread;
2907 }
2908 }
2909 return NULL;
2910}
2911
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002912audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002913{
2914 PlaybackThread *thread = primaryPlaybackThread_l();
2915
2916 if (thread == NULL) {
2917 return 0;
2918 }
2919
Eric Laurentf1c04f92012-08-28 14:26:53 -07002920 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002921}
2922
Glenn Kastena7335632016-06-09 17:09:53 -07002923AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2924{
2925 size_t minFrameCount = 0;
2926 PlaybackThread *minThread = NULL;
2927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2928 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2929 if (!thread->isDuplicating()) {
2930 size_t frameCount = thread->frameCountHAL();
2931 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2932 (frameCount == minFrameCount && thread->hasFastMixer() &&
2933 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2934 minFrameCount = frameCount;
2935 minThread = thread;
2936 }
2937 }
2938 }
2939 return minThread;
2940}
2941
Eric Laurenta011e352012-03-29 15:51:43 -07002942sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002943 audio_session_t triggerSession,
2944 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002945 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002946 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002947{
2948 Mutex::Autolock _l(mLock);
2949
2950 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2951 status_t playStatus = NAME_NOT_FOUND;
2952 status_t recStatus = NAME_NOT_FOUND;
2953 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2954 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2955 if (playStatus == NO_ERROR) {
2956 return event;
2957 }
2958 }
2959 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2960 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2961 if (recStatus == NO_ERROR) {
2962 return event;
2963 }
2964 }
2965 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2966 mPendingSyncEvents.add(event);
2967 } else {
2968 ALOGV("createSyncEvent() invalid event %d", event->type());
2969 event.clear();
2970 }
2971 return event;
2972}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002973
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974// ----------------------------------------------------------------------------
2975// Effect management
2976// ----------------------------------------------------------------------------
2977
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002978sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2979 return mEffectsFactoryHal;
2980}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981
Glenn Kastenf587ba52012-01-26 16:25:10 -08002982status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983{
2984 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002985 if (mEffectsFactoryHal.get()) {
2986 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2987 } else {
2988 return -ENODEV;
2989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990}
2991
Glenn Kastenf587ba52012-01-26 16:25:10 -08002992status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993{
2994 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002995 if (mEffectsFactoryHal.get()) {
2996 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2997 } else {
2998 return -ENODEV;
2999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000}
3001
Glenn Kasten5e92a782012-01-30 07:40:52 -08003002status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003003 const effect_uuid_t *pTypeUuid,
3004 uint32_t preferredTypeFlag,
3005 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003007 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3008 return BAD_VALUE;
3009 }
3010
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003012
3013 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003014 return -ENODEV;
3015 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003017 status_t status = NO_ERROR;
3018 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3019 // If uuid is specified, request effect descriptor from that.
3020 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3021 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3022 // If uuid is not specified, look for an available implementation
3023 // of the required type instead.
3024
3025 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3026 effect_descriptor_t desc;
3027 desc.flags = 0; // prevent compiler warning
3028
3029 uint32_t numEffects = 0;
3030 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3031 if (status < 0) {
3032 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3033 return status;
3034 }
3035
3036 bool found = false;
3037 for (uint32_t i = 0; i < numEffects; i++) {
3038 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3039 if (status < 0) {
3040 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3041 continue;
3042 }
3043 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3044 // If matching type found save effect descriptor.
3045 found = true;
3046 *descriptor = desc;
3047
3048 // If there's no preferred flag or this descriptor matches the preferred
3049 // flag, success! If this descriptor doesn't match the preferred
3050 // flag, continue enumeration in case a better matching version of this
3051 // effect type is available. Note that this means if no effect with a
3052 // correct flag is found, the descriptor returned will correspond to the
3053 // last effect that at least had a matching type uuid (if any).
3054 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3055 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3056 break;
3057 }
3058 }
3059 }
3060
3061 if (!found) {
3062 status = NAME_NOT_FOUND;
3063 ALOGW("getEffectDescriptor(): Effect not found by type.");
3064 }
3065 } else {
3066 status = BAD_VALUE;
3067 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3068 }
3069 return status;
3070}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003071
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003072sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 effect_descriptor_t *pDesc,
3074 const sp<IEffectClient>& effectClient,
3075 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003076 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003077 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003078 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003079 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080 status_t *status,
3081 int *id,
3082 int *enabled)
3083{
3084 status_t lStatus = NO_ERROR;
3085 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087
Eric Laurentb6436272016-12-07 19:24:50 -08003088 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003089 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003090 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3091 ALOGW_IF(pid != -1 && pid != callingPid,
3092 "%s uid %d pid %d tried to pass itself off as pid %d",
3093 __func__, callingUid, callingPid, pid);
3094 pid = callingPid;
3095 }
3096
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003097 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3098 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099
3100 if (pDesc == NULL) {
3101 lStatus = BAD_VALUE;
3102 goto Exit;
3103 }
3104
Eric Laurent84e9a102010-09-23 16:10:16 -07003105 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003106 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003107 lStatus = PERMISSION_DENIED;
3108 goto Exit;
3109 }
3110
Dima Zavinfce7a472011-04-19 22:30:36 -07003111 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003112 // that can only be created by audio policy manager
3113 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003114 lStatus = PERMISSION_DENIED;
3115 goto Exit;
3116 }
3117
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003118 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003119 lStatus = NO_INIT;
3120 goto Exit;
3121 }
3122
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003124 // Get the full effect descriptor from the uuid/type.
3125 // If the session is the output mix, prefer an auxiliary effect,
3126 // otherwise no preference.
3127 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3128 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3129 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3130 if (lStatus < 0) {
3131 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3132 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 }
3134
3135 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003136 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3138 lStatus = INVALID_OPERATION;
3139 goto Exit;
3140 }
3141
Eric Laurent59255e42011-07-27 19:49:51 -07003142 // check recording permission for visualizer
3143 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003144 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003145 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003146 lStatus = PERMISSION_DENIED;
3147 goto Exit;
3148 }
3149
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003151 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003152 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003153 // if the output returned by getOutputForEffect() is removed before we lock the
3154 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3155 // and we will exit safely
3156 io = AudioSystem::getOutputForEffect(&desc);
3157 ALOGV("createEffect got output %d", io);
3158 }
3159
3160 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161
3162 // If output is not specified try to find a matching audio session ID in one of the
3163 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003164 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3165 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003166 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003167 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003168 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3169 // output must be specified by AudioPolicyManager when using session
3170 // AUDIO_SESSION_OUTPUT_STAGE
3171 lStatus = BAD_VALUE;
3172 goto Exit;
3173 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003174 // look for the thread where the specified audio session is present
3175 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3176 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3177 io = mPlaybackThreads.keyAt(i);
3178 break;
3179 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003181 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003182 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3183 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3184 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003185 break;
3186 }
3187 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003188 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003189 if (io == AUDIO_IO_HANDLE_NONE) {
3190 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3191 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3192 io = mMmapThreads.keyAt(i);
3193 break;
3194 }
3195 }
3196 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003197 // If no output thread contains the requested session ID, default to
3198 // first output. The effect chain will be moved to the correct output
3199 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003200 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003201 io = mPlaybackThreads.keyAt(0);
3202 }
Steve Block3856b092011-10-20 11:56:00 +01003203 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003204 }
3205 ThreadBase *thread = checkRecordThread_l(io);
3206 if (thread == NULL) {
3207 thread = checkPlaybackThread_l(io);
3208 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003209 thread = checkMmapThread_l(io);
3210 if (thread == NULL) {
3211 ALOGE("createEffect() unknown output thread");
3212 lStatus = BAD_VALUE;
3213 goto Exit;
3214 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003215 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003216 } else {
3217 // Check if one effect chain was awaiting for an effect to be created on this
3218 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003219 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003220 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003221 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003222 thread->addEffectChain_l(chain);
3223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003225
Eric Laurent021cf962014-05-13 10:18:14 -07003226 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003228 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003229 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003230 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003231 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003232 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003233 // remove local strong reference to Client with mClientLock held
3234 Mutex::Autolock _cl(mClientLock);
3235 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003236 } else {
3237 // handle must be valid here, but check again to be safe.
3238 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 }
3241
haobo101735295ff7b0d2017-03-17 17:44:03 +08003242 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3243 // handle must be cleared outside lock.
3244 handle.clear();
3245 }
3246
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003248 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 return handle;
3250}
3251
Glenn Kastend848eb42016-03-08 13:42:11 -08003252status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003253 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003254{
Steve Block3856b092011-10-20 11:56:00 +01003255 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003256 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003257 Mutex::Autolock _l(mLock);
3258 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003259 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003260 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 }
Eric Laurentde070132010-07-13 04:45:46 -07003262 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3263 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003264 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003265 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 }
Eric Laurentde070132010-07-13 04:45:46 -07003267 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3268 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003269 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003270 return BAD_VALUE;
3271 }
3272
3273 Mutex::Autolock _dl(dstThread->mLock);
3274 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003275 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276}
3277
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003278// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003279status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003280 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003281 AudioFlinger::PlaybackThread *dstThread,
3282 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003283{
Steve Block3856b092011-10-20 11:56:00 +01003284 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003285 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003286
Eric Laurent59255e42011-07-27 19:49:51 -07003287 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003288 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003289 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003290 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003291 return INVALID_OPERATION;
3292 }
3293
Eric Laurent4c415062016-06-17 16:14:16 -07003294 // Check whether the destination thread and all effects in the chain are compatible
3295 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003296 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003297 " destination thread %p is not compatible with effects in the chain",
3298 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003299 return INVALID_OPERATION;
3300 }
3301
Eric Laurent39e94f82010-07-28 01:32:47 -07003302 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003303 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003304 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003305 // removed.
3306 srcThread->removeEffectChain_l(chain);
3307
3308 // transfer all effects one by one so that new effect chain is created on new thread with
3309 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003310 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003311 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003312 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003313 Vector< sp<EffectModule> > removed;
3314 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003315 while (effect != 0) {
3316 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003317 removed.add(effect);
3318 status = dstThread->addEffect_l(effect);
3319 if (status != NO_ERROR) {
3320 break;
3321 }
Eric Laurentec35a142011-10-05 17:42:25 -07003322 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3323 if (effect->state() == EffectModule::ACTIVE ||
3324 effect->state() == EffectModule::STOPPING) {
3325 effect->start();
3326 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003327 // if the move request is not received from audio policy manager, the effect must be
3328 // re-registered with the new strategy and output
3329 if (dstChain == 0) {
3330 dstChain = effect->chain().promote();
3331 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003332 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003333 status = NO_INIT;
3334 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003335 }
3336 strategy = dstChain->strategy();
3337 }
3338 if (reRegister) {
3339 AudioSystem::unregisterEffect(effect->id());
3340 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003341 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003342 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003343 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003344 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003345 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003346 }
Eric Laurentde070132010-07-13 04:45:46 -07003347 effect = chain->getEffectFromId_l(0);
3348 }
3349
Eric Laurent5baf2af2013-09-12 17:37:00 -07003350 if (status != NO_ERROR) {
3351 for (size_t i = 0; i < removed.size(); i++) {
3352 srcThread->addEffect_l(removed[i]);
3353 if (dstChain != 0 && reRegister) {
3354 AudioSystem::unregisterEffect(removed[i]->id());
3355 AudioSystem::registerEffect(&removed[i]->desc(),
3356 srcThread->id(),
3357 strategy,
3358 sessionId,
3359 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003360 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003361 }
3362 }
3363 }
3364
3365 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366}
3367
Eric Laurent5baf2af2013-09-12 17:37:00 -07003368bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003369{
3370 if (mGlobalEffectEnableTime != 0 &&
3371 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3372 return true;
3373 }
3374
3375 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3376 sp<EffectChain> ec =
3377 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003378 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003379 return true;
3380 }
3381 }
3382 return false;
3383}
3384
Eric Laurent5baf2af2013-09-12 17:37:00 -07003385void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003386{
3387 Mutex::Autolock _l(mLock);
3388
3389 mGlobalEffectEnableTime = systemTime();
3390
3391 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3392 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3393 if (t->mType == ThreadBase::OFFLOAD) {
3394 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3395 }
3396 }
3397
3398}
3399
Eric Laurentaaa44472014-09-12 17:41:50 -07003400status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3401{
Eric Laurentd8365c52017-07-16 15:27:05 -07003402 // clear possible suspended state before parking the chain so that it starts in default state
3403 // when attached to a new record thread
3404 chain->setEffectSuspended_l(FX_IID_AEC, false);
3405 chain->setEffectSuspended_l(FX_IID_NS, false);
3406
Glenn Kastend848eb42016-03-08 13:42:11 -08003407 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003408 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003409 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003410 if (index >= 0) {
3411 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3412 return ALREADY_EXISTS;
3413 }
3414 mOrphanEffectChains.add(session, chain);
3415 return NO_ERROR;
3416}
3417
3418sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3419{
3420 sp<EffectChain> chain;
3421 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003422 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003423 if (index >= 0) {
3424 chain = mOrphanEffectChains.valueAt(index);
3425 mOrphanEffectChains.removeItemsAt(index);
3426 }
3427 return chain;
3428}
3429
3430bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3431{
3432 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003433 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003434 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003435 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003436 if (index >= 0) {
3437 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003438 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003439 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003440 mOrphanEffectChains.removeItemsAt(index);
3441 }
3442 return true;
3443 }
3444 return false;
3445}
3446
3447
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448// ----------------------------------------------------------------------------
3449
3450status_t AudioFlinger::onTransact(
3451 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3452{
3453 return BnAudioFlinger::onTransact(code, data, reply, flags);
3454}
3455
Glenn Kasten63238ef2015-03-02 15:50:29 -08003456} // namespace android