blob: 8591efd77189f81ee10ccffdaa4889fe0ce2f740 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/time.h>
28#include <sys/resource.h>
29
jiabin57303cc2018-12-18 15:45:57 -080030#include <android/os/IExternalVibratorService.h>
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>
Mikhail Naganov2996f672019-04-18 12:29:59 -070049#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070052#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Andy Hung6770c6f2015-04-07 13:43:36 -070054#include <media/AudioResamplerPublic.h>
55
Mikhail Naganov9fe94012016-10-14 14:57:40 -070056#include <system/audio_effects/effect_visualizer.h>
57#include <system/audio_effects/effect_ns.h>
58#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Glenn Kasten3b21c502011-12-15 09:52:39 -080060#include <audio_utils/primitives.h>
61
Eric Laurentfeb0db62011-07-22 09:04:31 -070062#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080063
Glenn Kasten9e58b552013-01-18 15:09:48 -080064#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070065#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080066#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070069#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070070#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080071
rago3bd1c872016-09-26 12:58:14 -070072//#define BUFLOG_NDEBUG 0
73#include <BufLog.h>
74
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080075#include "TypedLogger.h"
76
Mathias Agopian65ab4712010-07-14 17:59:35 -070077// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
John Grossman1c345192012-03-27 14:00:17 -070079// Note: the following macro is used for extremely verbose logging message. In
80// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
81// 0; but one side effect of this is to turn all LOGV's as well. Some messages
82// are so verbose that we want to suppress them even when we have ALOG_ASSERT
83// turned on. Do not uncomment the #def below unless you really know what you
84// are doing and want to see all of the extremely verbose messages.
85//#define VERY_VERY_VERBOSE_LOGGING
86#ifdef VERY_VERY_VERBOSE_LOGGING
87#define ALOGVV ALOGV
88#else
89#define ALOGVV(a...) do { } while(0)
90#endif
Eric Laurentde070132010-07-13 04:45:46 -070091
Mathias Agopian65ab4712010-07-14 17:59:35 -070092namespace android {
93
Glenn Kastenec1d6b52011-12-12 09:04:45 -080094static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
95static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070096static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070097static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070098
Glenn Kasten58912562012-04-03 10:45:00 -070099
John Grossman4ff14ba2012-02-08 16:37:41 -0800100nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700103
Eric Laurent813e2a72013-08-31 12:59:48 -0700104// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
105// we define a minimum time during which a global effect is considered enabled.
106static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
107
Eric Laurentfc235202016-12-20 18:48:17 -0800108Mutex gLock;
109wp<AudioFlinger> gAudioFlinger;
110
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700111// Keep a strong reference to media.log service around forever.
112// The service is within our parent process so it can never die in a way that we could observe.
113// These two variables are const after initialization.
114static sp<IBinder> sMediaLogServiceAsBinder;
115static sp<IMediaLogService> sMediaLogService;
116
117static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
118
119static void sMediaLogInit()
120{
121 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
122 if (sMediaLogServiceAsBinder != 0) {
123 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
124 }
125}
126
jiabin57303cc2018-12-18 15:45:57 -0800127// Keep a strong reference to external vibrator service
128static sp<os::IExternalVibratorService> sExternalVibratorService;
129
130static sp<os::IExternalVibratorService> getExternalVibratorService() {
131 if (sExternalVibratorService == 0) {
132 sp <IBinder> binder = defaultServiceManager()->getService(
133 String16("external_vibrator_service"));
134 if (binder != 0) {
135 sExternalVibratorService =
136 interface_cast<os::IExternalVibratorService>(binder);
137 }
138 }
139 return sExternalVibratorService;
140}
141
Mathias Agopian65ab4712010-07-14 17:59:35 -0700142// ----------------------------------------------------------------------------
143
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700144std::string formatToString(audio_format_t format) {
145 std::string result;
146 FormatConverter::toString(format, result);
147 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800148}
149
Mathias Agopian65ab4712010-07-14 17:59:35 -0700150// ----------------------------------------------------------------------------
151
152AudioFlinger::AudioFlinger()
153 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800154 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800155 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800156 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700157 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800159 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700160 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800161 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700162 mBtNrecIsOff(false),
163 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700164 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800165 mTotalMemory(0),
166 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700167 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700168 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700169 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700171 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
172 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
173 // zero ID has a special meaning, so unavailable
174 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
175 }
176
Glenn Kastenae0cff12016-02-24 13:57:49 -0800177 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800178 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800179 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
180 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700181 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800182 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700183
Wei Jia3f273d12015-11-24 09:06:49 -0800184 // reset battery stats.
185 // if the audio service has crashed, battery stats could be left
186 // in bad state, reset the state upon service start.
187 BatteryNotifier::getInstance().noteResetAudio();
188
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700189 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700190 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
191
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800192 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700193}
194
195void AudioFlinger::onFirstRef()
196{
Eric Laurent93575202011-01-18 18:39:02 -0800197 Mutex::Autolock _l(mLock);
198
Dima Zavin799a70e2011-04-18 16:57:27 -0700199 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800200 char val_str[PROPERTY_VALUE_MAX] = { 0 };
201 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
202 uint32_t int_val;
203 if (1 == sscanf(val_str, "%u", &int_val)) {
204 mStandbyTimeInNsecs = milliseconds(int_val);
205 ALOGI("Using %u mSec as standby time.", int_val);
206 } else {
207 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
208 ALOGI("Using default %u mSec as standby time.",
209 (uint32_t)(mStandbyTimeInNsecs / 1000000));
210 }
211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212
Eric Laurenta4c5a552012-03-29 10:12:40 -0700213 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800214
215 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700216}
217
218AudioFlinger::~AudioFlinger()
219{
220 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700221 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700222 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223 }
224 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700225 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700226 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227 }
Andy Hungb4946b62019-03-14 11:19:28 -0700228 while (!mMmapThreads.isEmpty()) {
229 const audio_io_handle_t io = mMmapThreads.keyAt(0);
230 if (mMmapThreads.valueAt(0)->isOutput()) {
231 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
232 } else {
233 closeInput_nonvirtual(io); // removes entry from mMmapThreads
234 }
235 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700236
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800237 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
238 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700239 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700241
242 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700243 if (sMediaLogService != 0) {
244 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
245 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
246 mUnregisteredWriters.pop();
247 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700248 }
249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250}
251
Eric Laurentfc235202016-12-20 18:48:17 -0800252//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800253__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800254status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
255 const audio_attributes_t *attr,
256 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700257 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800258 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800259 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800260 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700261 sp<MmapStreamInterface>& interface,
262 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800263{
264 sp<AudioFlinger> af;
265 {
266 Mutex::Autolock _l(gLock);
267 af = gAudioFlinger.promote();
268 }
269 status_t ret = NO_INIT;
270 if (af != 0) {
271 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800272 direction, attr, config, client, deviceId,
273 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800274 }
275 return ret;
276}
277
Eric Laurent6acd1d42017-01-04 14:23:29 -0800278status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
279 const audio_attributes_t *attr,
280 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700281 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800282 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800283 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800284 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700285 sp<MmapStreamInterface>& interface,
286 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800287{
288 status_t ret = initCheck();
289 if (ret != NO_ERROR) {
290 return ret;
291 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800292 audio_session_t actualSessionId = *sessionId;
293 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
294 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
295 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800296 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700297 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800298 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700299 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800300 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
301 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
302 fullConfig.sample_rate = config->sample_rate;
303 fullConfig.channel_mask = config->channel_mask;
304 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800305 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700306
307 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800308 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200309 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800310 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800311 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
312 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800313 deviceId, &portId, &secondaryOutputs);
314 ALOGW_IF(!secondaryOutputs.empty(),
315 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800316 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700317 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700318 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800319 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800320 client.clientPid,
321 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800322 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800323 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700324 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800325 }
326 if (ret != NO_ERROR) {
327 return ret;
328 }
329
330 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
331 // audio policy manager and we can retrieve it
332 sp<MmapThread> thread = mMmapThreads.valueFor(io);
333 if (thread != 0) {
334 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700335 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700336 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800337 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800338 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700339 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700340 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700341 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800342 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700343 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800344 ret = NO_INIT;
345 }
346
347 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
348
Eric Laurentfc235202016-12-20 18:48:17 -0800349 return ret;
350}
351
jiabin57303cc2018-12-18 15:45:57 -0800352/* static */
353int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
354 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
355 if (evs != 0) {
356 int32_t ret;
357 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
358 if (status.isOk()) {
359 return ret;
360 }
361 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800362 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800363}
364
365/* static */
366void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
367 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
368 if (evs != 0) {
369 evs->onExternalVibrationStop(*externalVibration);
370 }
371}
372
Eric Laurenta4c5a552012-03-29 10:12:40 -0700373static const char * const audio_interfaces[] = {
374 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
375 AUDIO_HARDWARE_MODULE_ID_A2DP,
376 AUDIO_HARDWARE_MODULE_ID_USB,
377};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700378
Phil Burk062e67a2015-02-11 13:40:50 -0800379AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700380 audio_module_handle_t module,
381 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700382{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700383 // if module is 0, the request comes from an old policy manager and we should load
384 // well known modules
385 if (module == 0) {
386 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700387 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700388 loadHwModule_l(audio_interfaces[i]);
389 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700390 // then try to find a module supporting the requested device.
391 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
392 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700393 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
394 uint32_t supportedDevices;
395 if (dev->getSupportedDevices(&supportedDevices) == OK &&
396 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700397 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700398 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700399 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700400 } else {
401 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700402 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
403 if (audioHwDevice != NULL) {
404 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700405 }
406 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700407
Dima Zavin799a70e2011-04-18 16:57:27 -0700408 return NULL;
409}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410
Glenn Kasten0f11b512014-01-31 16:18:54 -0800411void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412{
413 const size_t SIZE = 256;
414 char buffer[SIZE];
415 String8 result;
416
417 result.append("Clients:\n");
418 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800419 sp<Client> client = mClients.valueAt(i).promote();
420 if (client != 0) {
421 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
422 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700423 }
424 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700425
Eric Laurentd1b28d42013-09-18 18:47:13 -0700426 result.append("Notification Clients:\n");
427 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
428 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
429 result.append(buffer);
430 }
431
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700432 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800433 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700434 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
435 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800436 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700437 result.append(buffer);
438 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440}
441
442
Glenn Kasten0f11b512014-01-31 16:18:54 -0800443void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444{
445 const size_t SIZE = 256;
446 char buffer[SIZE];
447 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800448 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449
John Grossman4ff14ba2012-02-08 16:37:41 -0800450 snprintf(buffer, SIZE, "Hardware status: %d\n"
451 "Standby Time mSec: %u\n",
452 hardwareStatus,
453 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 result.append(buffer);
455 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700456}
457
Glenn Kasten0f11b512014-01-31 16:18:54 -0800458void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459{
460 const size_t SIZE = 256;
461 char buffer[SIZE];
462 String8 result;
463 snprintf(buffer, SIZE, "Permission Denial: "
464 "can't dump AudioFlinger from pid=%d, uid=%d\n",
465 IPCThreadState::self()->getCallingPid(),
466 IPCThreadState::self()->getCallingUid());
467 result.append(buffer);
468 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469}
470
Eric Laurent81784c32012-11-19 14:55:58 -0800471bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700473 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
474 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475}
476
477status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
478{
Glenn Kasten44deb052012-02-05 18:09:08 -0800479 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480 dumpPermissionDenial(fd, args);
481 } else {
482 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800483 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484 if (!hardwareLocked) {
485 String8 result(kHardwareLockedString);
486 write(fd, result.string(), result.size());
487 } else {
488 mHardwareLock.unlock();
489 }
490
Eric Tan7b651152018-07-13 10:17:19 -0700491 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492
493 // failed to lock - AudioFlinger is probably deadlocked
494 if (!locked) {
495 String8 result(kDeadlockedString);
496 write(fd, result.string(), result.size());
497 }
498
Eric Laurent021cf962014-05-13 10:18:14 -0700499 bool clientLocked = dumpTryLock(mClientLock);
500 if (!clientLocked) {
501 String8 result(kClientLockedString);
502 write(fd, result.string(), result.size());
503 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700504
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700505 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700506 mEffectsFactoryHal->dumpEffects(fd);
507 } else {
508 String8 result(kNoEffectsFactory);
509 write(fd, result.string(), result.size());
510 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700511
Mathias Agopian65ab4712010-07-14 17:59:35 -0700512 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700513 if (clientLocked) {
514 mClientLock.unlock();
515 }
516
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517 dumpInternals(fd, args);
518
519 // dump playback threads
520 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
521 mPlaybackThreads.valueAt(i)->dump(fd, args);
522 }
523
524 // dump record threads
525 for (size_t i = 0; i < mRecordThreads.size(); i++) {
526 mRecordThreads.valueAt(i)->dump(fd, args);
527 }
528
Eric Laurent6acd1d42017-01-04 14:23:29 -0800529 // dump mmap threads
530 for (size_t i = 0; i < mMmapThreads.size(); i++) {
531 mMmapThreads.valueAt(i)->dump(fd, args);
532 }
533
Eric Laurentaaa44472014-09-12 17:41:50 -0700534 // dump orphan effect chains
535 if (mOrphanEffectChains.size() != 0) {
536 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
537 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
538 mOrphanEffectChains.valueAt(i)->dump(fd, args);
539 }
540 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700541 // dump all hardware devs
542 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700543 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
544 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700546
Mikhail Naganov201369b2018-05-16 16:52:32 -0700547 mPatchPanel.dump(fd);
548
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700549 // dump external setParameters
550 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
551 dprintf(fd, "\n%s setParameters:\n", name);
552 logger.dump(fd, " " /* prefix */);
553 };
554 dumpLogger(mRejectedSetParameterLog, "Rejected");
555 dumpLogger(mAppSetParameterLog, "App");
556 dumpLogger(mSystemSetParameterLog, "System");
557
Andy Hunga8115dc2018-08-24 15:51:59 -0700558 // dump historical threads in the last 10 seconds
559 const std::string threadLog = mThreadLog.dumpToString(
560 "Historical Thread Log ", 0 /* lines */,
561 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
562 write(fd, threadLog.c_str(), threadLog.size());
563
rago3bd1c872016-09-26 12:58:14 -0700564 BUFLOG_RESET;
565
Glenn Kastend65d73c2012-06-22 17:21:07 -0700566 if (locked) {
567 mLock.unlock();
568 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800569
Andy Hung8946a282018-04-19 20:04:56 -0700570#ifdef TEE_SINK
571 // NBAIO_Tee dump is safe to call outside of AF lock.
572 NBAIO_Tee::dumpAll(fd, "_DUMP");
573#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800574 // append a copy of media.log here by forwarding fd to it, but don't attempt
575 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700576 if (sMediaLogServiceAsBinder != 0) {
577 dprintf(fd, "\nmedia.log:\n");
578 Vector<String16> args;
579 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800580 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700581
582 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700583 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700584 bool unreachableMemory = false;
585 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700586 if (arg == String16("-m")) {
587 dumpMem = true;
588 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700589 unreachableMemory = true;
590 }
591 }
592
Andy Hung07b745e2016-05-23 16:21:07 -0700593 if (dumpMem) {
594 dprintf(fd, "\nDumping memory:\n");
595 std::string s = dumpMemoryAddresses(100 /* limit */);
596 write(fd, s.c_str(), s.size());
597 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700598 if (unreachableMemory) {
599 dprintf(fd, "\nDumping unreachable memory:\n");
600 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700601 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700602 write(fd, s.c_str(), s.size());
603 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604 }
605 return NO_ERROR;
606}
607
Eric Laurent021cf962014-05-13 10:18:14 -0700608sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800609{
Eric Laurent021cf962014-05-13 10:18:14 -0700610 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800611 // If pid is already in the mClients wp<> map, then use that entry
612 // (for which promote() is always != 0), otherwise create a new entry and Client.
613 sp<Client> client = mClients.valueFor(pid).promote();
614 if (client == 0) {
615 client = new Client(this, pid);
616 mClients.add(pid, client);
617 }
618
619 return client;
620}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700621
Glenn Kasten9e58b552013-01-18 15:09:48 -0800622sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
623{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700624 // If there is no memory allocated for logs, return a dummy writer that does nothing.
625 // Similarly if we can't contact the media.log service, also return a dummy writer.
626 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800627 return new NBLog::Writer();
628 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700629 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
630 // If allocation fails, consult the vector of previously unregistered writers
631 // and garbage-collect one or more them until an allocation succeeds
632 if (shared == 0) {
633 Mutex::Autolock _l(mUnregisteredWritersLock);
634 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
635 {
636 // Pick the oldest stale writer to garbage-collect
637 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
638 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700639 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700640 // Now the media.log remote reference to IMemory is gone. When our last local
641 // reference to IMemory also drops to zero at end of this block,
642 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
643 }
644 // Re-attempt the allocation
645 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
646 if (shared != 0) {
647 goto success;
648 }
649 }
650 // Even after garbage-collecting all old writers, there is still not enough memory,
651 // so return a dummy writer
652 return new NBLog::Writer();
653 }
654success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800655 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
656 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
657 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700658 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800659 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800660}
661
662void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
663{
Glenn Kasten685ef092013-02-04 08:15:34 -0800664 if (writer == 0) {
665 return;
666 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800667 sp<IMemory> iMemory(writer->getIMemory());
668 if (iMemory == 0) {
669 return;
670 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700671 // Rather than removing the writer immediately, append it to a queue of old writers to
672 // be garbage-collected later. This allows us to continue to view old logs for a while.
673 Mutex::Autolock _l(mUnregisteredWritersLock);
674 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800675}
676
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677// IAudioFlinger interface
678
Eric Laurent21da6472017-11-09 16:29:26 -0800679sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
680 CreateTrackOutput& output,
681 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682{
683 sp<PlaybackThread::Track> track;
684 sp<TrackHandle> trackHandle;
685 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800687 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800688 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800689 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690
Eric Laurent21da6472017-11-09 16:29:26 -0800691 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700692 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800693 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700694 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
695 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700696 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700697
Andy Hung4ef19fa2018-05-15 19:35:29 -0700698 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800699 ALOGW_IF(clientUid != callingUid,
700 "%s uid %d tried to pass itself off as %d",
701 __FUNCTION__, callingUid, clientUid);
702 clientUid = callingUid;
703 updatePid = true;
704 }
705 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700706 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800707 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800708 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700709 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800710 __func__, callingUid, callingPid, clientPid);
711 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700712 }
713
Eric Laurent21da6472017-11-09 16:29:26 -0800714 audio_session_t sessionId = input.sessionId;
715 if (sessionId == AUDIO_SESSION_ALLOCATE) {
716 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800717 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
718 lStatus = BAD_VALUE;
719 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800720 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800721
Eric Laurent21da6472017-11-09 16:29:26 -0800722 output.sessionId = sessionId;
723 output.outputId = AUDIO_IO_HANDLE_NONE;
724 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700725 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200726 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800727 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800728
729 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
730 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
731 goto Exit;
732 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800733 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
734 // but if someone uses binder directly they could bypass that and cause us to crash
735 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000736 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 lStatus = BAD_VALUE;
738 goto Exit;
739 }
740
Glenn Kasten53b5d092014-02-05 10:00:23 -0800741 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800742 if (!audio_is_output_channel(input.config.channel_mask)) {
743 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800744 lStatus = BAD_VALUE;
745 goto Exit;
746 }
747
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700748 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800749 if (!audio_is_valid_format(input.config.format)) {
750 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700751 lStatus = BAD_VALUE;
752 goto Exit;
753 }
754
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 {
756 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800757 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800759 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 lStatus = BAD_VALUE;
761 goto Exit;
762 }
763
Eric Laurent21da6472017-11-09 16:29:26 -0800764 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765
Glenn Kastene848bd92014-03-13 15:00:32 -0700766 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800767 // check if an effect chain with the same session ID is present on another
768 // output thread and move it here.
769 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
770 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
771 if (mPlaybackThreads.keyAt(i) != output.outputId) {
772 uint32_t sessions = t->hasAudioSession(sessionId);
773 if (sessions & ThreadBase::EFFECT_SESSION) {
774 effectThread = t.get();
775 break;
Eric Laurentde070132010-07-13 04:45:46 -0700776 }
777 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778 }
Eric Laurent21da6472017-11-09 16:29:26 -0800779 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780
Eric Laurent21da6472017-11-09 16:29:26 -0800781 output.sampleRate = input.config.sample_rate;
782 output.frameCount = input.frameCount;
783 output.notificationFrameCount = input.notificationFrameCount;
784 output.flags = input.flags;
785
Eric Laurent42984412019-05-09 17:57:03 -0700786 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700787 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800788 &output.frameCount, &output.notificationFrameCount,
789 input.notificationsPerBuffer, input.speed,
790 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700791 callingPid, input.clientInfo.clientTid, clientUid,
792 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800793 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700794 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700795
Eric Laurent21da6472017-11-09 16:29:26 -0800796 output.afFrameCount = thread->frameCount();
797 output.afSampleRate = thread->sampleRate();
798 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800799 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800800
Kevin Rocard153f92d2018-12-18 18:33:28 -0800801 if (lStatus == NO_ERROR) {
802 // Connect secondary outputs. Failure on a secondary output must not imped the primary
803 // Any secondary output setup failure will lead to a desync between the AP and AF until
804 // the track is destroyed.
805 TeePatches teePatches;
806 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
807 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
808 if (secondaryThread == NULL) {
809 ALOGE("no playback thread found for secondary output %d", output.outputId);
810 continue;
811 }
812
Kevin Rocard20a44f82019-09-18 11:24:52 +0100813 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
814 / thread->sampleRate();
815 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
816 / secondaryThread->sampleRate();
817 // If the secondary output has just been opened, the first secondaryThread write
818 // will not block as it will fill the empty startup buffer of the HAL,
819 // so a second sink buffer needs to be ready for the immediate next blocking write.
820 // Additionally, have a margin of one main thread buffer as the scheduling jitter
821 // can reorder the writes (eg if thread A&B have the same write intervale,
822 // the scheduler could schedule AB...BA)
823 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
824 // Total secondary output buffer must be at least as the read frames plus
825 // the margin of a few buffers on both sides in case the
826 // threads scheduling has some jitter.
827 // That value should not impact latency as the secondary track is started before
828 // its buffer is full, see frameCountToBeReady.
829 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
830 // The frameCount should also not be smaller than the secondary thread min frame
831 // count
832 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
833 [&] { Mutex::Autolock _l(secondaryThread->mLock);
834 return secondaryThread->latency_l(); }(),
835 secondaryThread->mNormalFrameCount,
836 secondaryThread->mSampleRate,
837 output.sampleRate,
838 input.speed);
839 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800840
841 using namespace std::chrono_literals;
842 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
843 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
844 output.sampleRate,
845 inChannelMask,
846 input.config.format,
847 frameCount,
848 NULL /* buffer */,
849 (size_t)0 /* bufferSize */,
850 AUDIO_INPUT_FLAG_DIRECT,
851 0ns /* timeout */);
852 status_t status = patchRecord->initCheck();
853 if (status != NO_ERROR) {
854 ALOGE("Secondary output patchRecord init failed: %d", status);
855 continue;
856 }
Andy Hungae22b482019-05-09 15:38:55 -0700857
858 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
859 // for fast usage: thread has fast mixer, sample rate matches, etc.;
860 // for now, we exclude fast tracks by removing the Fast flag.
861 const audio_output_flags_t outputFlags =
862 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800863 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
864 streamType,
865 output.sampleRate,
866 input.config.channel_mask,
867 input.config.format,
868 frameCount,
869 patchRecord->buffer(),
870 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700871 outputFlags,
Kevin Rocard20a44f82019-09-18 11:24:52 +0100872 0ns /* timeout */,
873 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800874 status = patchTrack->initCheck();
875 if (status != NO_ERROR) {
876 ALOGE("Secondary output patchTrack init failed: %d", status);
877 continue;
878 }
879 teePatches.push_back({patchRecord, patchTrack});
880 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800881 // In case the downstream patchTrack on the secondaryThread temporarily outlives
882 // our created track, ensure the corresponding patchRecord is still alive.
883 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
884 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800885 }
886 track->setTeePatches(std::move(teePatches));
887 }
888
Eric Laurent39e94f82010-07-28 01:32:47 -0700889 // move effect chain to this output thread if an effect on same session was waiting
890 // for a track to be created
891 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700892 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700893 Mutex::Autolock _dl(thread->mLock);
894 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700895 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
896 effectThreadId = thread->id();
897 effectIds = thread->getEffectIds_l(sessionId);
898 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700899 }
Eric Laurenta011e352012-03-29 15:51:43 -0700900
901 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700902 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800903 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700904 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700905 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700906 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700907 } else {
908 mPendingSyncEvents[i]->cancel();
909 }
Eric Laurenta011e352012-03-29 15:51:43 -0700910 mPendingSyncEvents.removeAt(i);
911 i--;
912 }
913 }
914 }
Glenn Kastene198c362013-08-13 09:13:36 -0700915
Eric Laurent21da6472017-11-09 16:29:26 -0800916 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
Glenn Kastene198c362013-08-13 09:13:36 -0700918
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700919 if (lStatus != NO_ERROR) {
920 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700921 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700922 // Don't hold mClientLock when releasing the reference on the track as the
923 // destructor will acquire it.
924 {
925 Mutex::Autolock _cl(mClientLock);
926 client.clear();
927 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700929 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 }
931
Eric Laurent6c796322019-04-09 14:13:17 -0700932 // effectThreadId is not NONE if an effect chain corresponding to the track session
933 // was found on another thread and must be moved on this thread
934 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
935 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
936 }
937
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700938 // return handle to client
939 trackHandle = new TrackHandle(track);
940
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800942 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700943 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800944 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700945 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 return trackHandle;
947}
948
Glenn Kasten2c073da2016-02-26 09:14:08 -0800949uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950{
951 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800952 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800954 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 return 0;
956 }
957 return thread->sampleRate();
958}
959
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800960audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961{
962 Mutex::Autolock _l(mLock);
963 PlaybackThread *thread = checkPlaybackThread_l(output);
964 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000965 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800966 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 }
968 return thread->format();
969}
970
Glenn Kasten2c073da2016-02-26 09:14:08 -0800971size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972{
973 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800974 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800976 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977 return 0;
978 }
Glenn Kasten58912562012-04-03 10:45:00 -0700979 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
980 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 return thread->frameCount();
982}
983
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700984size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
985{
986 Mutex::Autolock _l(mLock);
987 ThreadBase *thread = checkThread_l(ioHandle);
988 if (thread == NULL) {
989 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
990 return 0;
991 }
992 return thread->frameCountHAL();
993}
994
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800995uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996{
997 Mutex::Autolock _l(mLock);
998 PlaybackThread *thread = checkPlaybackThread_l(output);
999 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001000 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 return 0;
1002 }
1003 return thread->latency();
1004}
1005
1006status_t AudioFlinger::setMasterVolume(float value)
1007{
Eric Laurenta1884f92011-08-23 08:25:03 -07001008 status_t ret = initCheck();
1009 if (ret != NO_ERROR) {
1010 return ret;
1011 }
1012
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 // check calling permissions
1014 if (!settingsAllowed()) {
1015 return PERMISSION_DENIED;
1016 }
1017
Eric Laurenta4c5a552012-03-29 10:12:40 -07001018 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001019 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001020
John Grossmanee578c02012-07-23 17:05:46 -07001021 // Set master volume in the HALs which support it.
1022 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1023 AutoMutex lock(mHardwareLock);
1024 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001025
John Grossmanee578c02012-07-23 17:05:46 -07001026 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1027 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001028 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -08001029 }
John Grossmanee578c02012-07-23 17:05:46 -07001030 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032
John Grossmanee578c02012-07-23 17:05:46 -07001033 // Now set the master volume in each playback thread. Playback threads
1034 // assigned to HALs which do not have master volume support will apply
1035 // master volume during the mix operation. Threads with HALs which do
1036 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001037 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1038 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1039 continue;
1040 }
John Grossmanee578c02012-07-23 17:05:46 -07001041 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001042 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043
1044 return NO_ERROR;
1045}
1046
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001047status_t AudioFlinger::setMasterBalance(float balance)
1048{
1049 status_t ret = initCheck();
1050 if (ret != NO_ERROR) {
1051 return ret;
1052 }
1053
1054 // check calling permissions
1055 if (!settingsAllowed()) {
1056 return PERMISSION_DENIED;
1057 }
1058
1059 // check range
1060 if (isnan(balance) || fabs(balance) > 1.f) {
1061 return BAD_VALUE;
1062 }
1063
1064 Mutex::Autolock _l(mLock);
1065
1066 // short cut.
1067 if (mMasterBalance == balance) return NO_ERROR;
1068
1069 mMasterBalance = balance;
1070
1071 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1072 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1073 continue;
1074 }
1075 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1076 }
1077
1078 return NO_ERROR;
1079}
1080
Glenn Kastenf78aee72012-01-04 11:00:47 -08001081status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082{
Eric Laurenta1884f92011-08-23 08:25:03 -07001083 status_t ret = initCheck();
1084 if (ret != NO_ERROR) {
1085 return ret;
1086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087
1088 // check calling permissions
1089 if (!settingsAllowed()) {
1090 return PERMISSION_DENIED;
1091 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001092 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001093 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 return BAD_VALUE;
1095 }
1096
1097 { // scope for the lock
1098 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001099 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001101 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 mHardwareStatus = AUDIO_HW_IDLE;
1103 }
1104
1105 if (NO_ERROR == ret) {
1106 Mutex::Autolock _l(mLock);
1107 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001108 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001109 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110 }
1111
1112 return ret;
1113}
1114
1115status_t AudioFlinger::setMicMute(bool state)
1116{
Eric Laurenta1884f92011-08-23 08:25:03 -07001117 status_t ret = initCheck();
1118 if (ret != NO_ERROR) {
1119 return ret;
1120 }
1121
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 // check calling permissions
1123 if (!settingsAllowed()) {
1124 return PERMISSION_DENIED;
1125 }
1126
1127 AutoMutex lock(mHardwareLock);
1128 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001129 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001130 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1131 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001132 if (result != NO_ERROR) {
1133 ret = result;
1134 }
1135 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 mHardwareStatus = AUDIO_HW_IDLE;
1137 return ret;
1138}
1139
1140bool AudioFlinger::getMicMute() const
1141{
Eric Laurenta1884f92011-08-23 08:25:03 -07001142 status_t ret = initCheck();
1143 if (ret != NO_ERROR) {
1144 return false;
1145 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001146 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001147 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001148 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001150 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001151 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1152 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001153 if (result == NO_ERROR) {
1154 mute = mute && state;
1155 }
1156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001158
1159 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160}
1161
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001162void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1163{
1164 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1165
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001166 AutoMutex lock(mLock);
1167 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001168 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1169 }
1170 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1171 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001172 }
1173}
1174
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175status_t AudioFlinger::setMasterMute(bool muted)
1176{
John Grossmand8f178d2012-07-20 14:51:35 -07001177 status_t ret = initCheck();
1178 if (ret != NO_ERROR) {
1179 return ret;
1180 }
1181
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 // check calling permissions
1183 if (!settingsAllowed()) {
1184 return PERMISSION_DENIED;
1185 }
1186
John Grossmanee578c02012-07-23 17:05:46 -07001187 Mutex::Autolock _l(mLock);
1188 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001189
John Grossmanee578c02012-07-23 17:05:46 -07001190 // Set master mute in the HALs which support it.
1191 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1192 AutoMutex lock(mHardwareLock);
1193 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001194
John Grossmanee578c02012-07-23 17:05:46 -07001195 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1196 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001197 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001198 }
John Grossmanee578c02012-07-23 17:05:46 -07001199 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001200 }
1201
John Grossmanee578c02012-07-23 17:05:46 -07001202 // Now set the master mute in each playback thread. Playback threads
1203 // assigned to HALs which do not have master mute support will apply master
1204 // mute during the mix operation. Threads with HALs which do support master
1205 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001206 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1207 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1208 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001209 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210
1211 return NO_ERROR;
1212}
1213
1214float AudioFlinger::masterVolume() const
1215{
Glenn Kasten98067102011-12-13 11:47:54 -08001216 Mutex::Autolock _l(mLock);
1217 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218}
1219
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001220status_t AudioFlinger::getMasterBalance(float *balance) const
1221{
1222 Mutex::Autolock _l(mLock);
1223 *balance = getMasterBalance_l();
1224 return NO_ERROR; // if called through binder, may return a transactional error
1225}
1226
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227bool AudioFlinger::masterMute() const
1228{
Glenn Kasten98067102011-12-13 11:47:54 -08001229 Mutex::Autolock _l(mLock);
1230 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231}
1232
John Grossman4ff14ba2012-02-08 16:37:41 -08001233float AudioFlinger::masterVolume_l() const
1234{
John Grossman4ff14ba2012-02-08 16:37:41 -08001235 return mMasterVolume;
1236}
1237
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001238float AudioFlinger::getMasterBalance_l() const
1239{
1240 return mMasterBalance;
1241}
1242
John Grossmand8f178d2012-07-20 14:51:35 -07001243bool AudioFlinger::masterMute_l() const
1244{
John Grossmanee578c02012-07-23 17:05:46 -07001245 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001246}
1247
Eric Laurent223fd5c2014-11-11 13:43:36 -08001248status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1249{
1250 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001251 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001252 return BAD_VALUE;
1253 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001254 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1255 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1256 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001257 return PERMISSION_DENIED;
1258 }
1259
1260 return NO_ERROR;
1261}
1262
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001263status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1264 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265{
1266 // check calling permissions
1267 if (!settingsAllowed()) {
1268 return PERMISSION_DENIED;
1269 }
1270
Eric Laurent223fd5c2014-11-11 13:43:36 -08001271 status_t status = checkStreamType(stream);
1272 if (status != NO_ERROR) {
1273 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 }
Eric Laurent98e38192018-02-15 18:31:53 -08001275 if (output == AUDIO_IO_HANDLE_NONE) {
1276 return BAD_VALUE;
1277 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001278 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1279 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280
1281 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001282 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1283 if (volumeInterface == NULL) {
1284 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 }
Eric Laurent98e38192018-02-15 18:31:53 -08001286 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287
1288 return NO_ERROR;
1289}
1290
Glenn Kastenfff6d712012-01-12 16:38:12 -08001291status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292{
1293 // check calling permissions
1294 if (!settingsAllowed()) {
1295 return PERMISSION_DENIED;
1296 }
1297
Eric Laurent223fd5c2014-11-11 13:43:36 -08001298 status_t status = checkStreamType(stream);
1299 if (status != NO_ERROR) {
1300 return status;
1301 }
1302 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1303
1304 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001305 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306 return BAD_VALUE;
1307 }
1308
Eric Laurent93575202011-01-18 18:39:02 -08001309 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001311 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1312 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1313 volumeInterfaces[i]->setStreamMute(stream, muted);
1314 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315
1316 return NO_ERROR;
1317}
1318
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001319float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001321 status_t status = checkStreamType(stream);
1322 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001323 return 0.0f;
1324 }
Eric Laurent98e38192018-02-15 18:31:53 -08001325 if (output == AUDIO_IO_HANDLE_NONE) {
1326 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001327 }
1328
Eric Laurent98e38192018-02-15 18:31:53 -08001329 AutoMutex lock(mLock);
1330 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1331 if (volumeInterface == NULL) {
1332 return 0.0f;
1333 }
1334
1335 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336}
1337
Glenn Kastenfff6d712012-01-12 16:38:12 -08001338bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001340 status_t status = checkStreamType(stream);
1341 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342 return true;
1343 }
1344
Glenn Kasten6637baa2012-01-09 09:40:36 -08001345 AutoMutex lock(mLock);
1346 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001347}
1348
Eric Laurent054d9d32015-04-24 08:48:48 -07001349
1350void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1351{
1352 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1353 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1354 }
1355}
1356
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001357// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1358void AudioFlinger::forwardParametersToDownstreamPatches_l(
1359 audio_io_handle_t upStream, const String8& keyValuePairs,
1360 std::function<bool(const sp<PlaybackThread>&)> useThread)
1361{
1362 std::vector<PatchPanel::SoftwarePatch> swPatches;
1363 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1364 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1365 __func__, swPatches.size(), upStream);
1366 for (const auto& swPatch : swPatches) {
1367 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1368 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1369 downStream->setParameters(keyValuePairs);
1370 }
1371 }
1372}
1373
Eric Laurentf1047e82018-04-16 19:18:20 -07001374// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1375// Some keys are used for audio routing and audio path configuration and should be reserved for use
1376// by audio policy and audio flinger for functional, privacy and security reasons.
1377void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1378{
1379 static const String8 kReservedParameters[] = {
1380 String8(AudioParameter::keyRouting),
1381 String8(AudioParameter::keySamplingRate),
1382 String8(AudioParameter::keyFormat),
1383 String8(AudioParameter::keyChannels),
1384 String8(AudioParameter::keyFrameCount),
1385 String8(AudioParameter::keyInputSource),
1386 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovbb3b1602019-07-08 15:28:43 -07001387 String8(AudioParameter::keyDeviceConnect),
1388 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001389 String8(AudioParameter::keyStreamSupportedFormats),
1390 String8(AudioParameter::keyStreamSupportedChannels),
1391 String8(AudioParameter::keyStreamSupportedSamplingRates),
1392 };
1393
Andy Hung4ef19fa2018-05-15 19:35:29 -07001394 if (isAudioServerUid(callingUid)) {
1395 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001396 }
1397
1398 AudioParameter param = AudioParameter(keyValuePairs);
1399 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001400 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001401 for (auto& key : kReservedParameters) {
1402 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001403 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001404 param.remove(key);
1405 }
1406 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001407 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1408 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001409 keyValuePairs = param.toString();
1410}
1411
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001412void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1413 size_t rejectedKVPSize, const String8& rejectedKVPs,
1414 uid_t callingUid) {
1415 auto prefix = String8::format("UID %5d", callingUid);
1416 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1417 if (rejectedKVPSize != 0) {
1418 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1419 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1420 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1421 } else {
1422 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1423 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1424 }
1425}
1426
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001427status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428{
Eric Laurentf1047e82018-04-16 19:18:20 -07001429 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1430 ioHandle, keyValuePairs.string(),
1431 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001432
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433 // check calling permissions
1434 if (!settingsAllowed()) {
1435 return PERMISSION_DENIED;
1436 }
1437
Eric Laurentf1047e82018-04-16 19:18:20 -07001438 String8 filteredKeyValuePairs = keyValuePairs;
1439 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1440
1441 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1442
Glenn Kasten142f5192014-03-25 17:44:59 -07001443 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1444 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001445 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001446 // result will remain NO_INIT if no audio device is present
1447 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001448 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001449 AutoMutex lock(mHardwareLock);
1450 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1451 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001452 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001453 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001454 // return success if at least one audio device accepts the parameters as not all
1455 // HALs are requested to support all parameters. If no audio device supports the
1456 // requested parameters, the last error is reported.
1457 if (final_result != NO_ERROR) {
1458 final_result = result;
1459 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001460 }
1461 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001462 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001463 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001464 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001465 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001466 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1467 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001468 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001469 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001470 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001471 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001472 }
1473 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001474 String8 screenState;
1475 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001476 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001477 if (isOff != (AudioFlinger::mScreenState & 1)) {
1478 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001479 }
1480 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001481 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 }
1483
1484 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1485 // and the thread is exited once the lock is released
1486 sp<ThreadBase> thread;
1487 {
1488 Mutex::Autolock _l(mLock);
1489 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001490 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001492 if (thread == 0) {
1493 thread = checkMmapThread_l(ioHandle);
1494 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001495 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001496 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001497 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001498 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001499 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1500 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001501 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001502 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 }
1504 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001505 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001506 status_t result = thread->setParameters(filteredKeyValuePairs);
1507 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1508 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 }
1510 return BAD_VALUE;
1511}
1512
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001513String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001515 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1516 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517
Eric Laurenta4c5a552012-03-29 10:12:40 -07001518 Mutex::Autolock _l(mLock);
1519
Glenn Kasten142f5192014-03-25 17:44:59 -07001520 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001521 String8 out_s8;
1522
Dima Zavin799a70e2011-04-18 16:57:27 -07001523 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001524 String8 s;
1525 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001526 {
1527 AutoMutex lock(mHardwareLock);
1528 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001529 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1530 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001531 mHardwareStatus = AUDIO_HW_IDLE;
1532 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001533 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001534 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001535 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536 }
1537
Eric Laurent6acd1d42017-01-04 14:23:29 -08001538 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1539 if (thread == NULL) {
1540 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1541 if (thread == NULL) {
1542 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1543 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001544 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001545 }
1546 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001548 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549}
1550
Glenn Kastendd8104c2012-07-02 12:42:44 -07001551size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1552 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553{
Eric Laurenta1884f92011-08-23 08:25:03 -07001554 status_t ret = initCheck();
1555 if (ret != NO_ERROR) {
1556 return 0;
1557 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001558 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001559 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001560 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001561 return 0;
1562 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001563
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001564 AutoMutex lock(mHardwareLock);
1565 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001566 audio_config_t config, proposed;
1567 memset(&proposed, 0, sizeof(proposed));
1568 proposed.sample_rate = sampleRate;
1569 proposed.channel_mask = channelMask;
1570 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001571
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001572 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Tao Wu1eb82df2019-11-05 10:20:18 -08001573 size_t frames = 0;
Andy Hung6770c6f2015-04-07 13:43:36 -07001574 for (;;) {
1575 // Note: config is currently a const parameter for get_input_buffer_size()
1576 // but we use a copy from proposed in case config changes from the call.
1577 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001578 status_t result = dev->getInputBufferSize(&config, &frames);
1579 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001580 break; // hal success, config is the result
1581 }
1582 // change one parameter of the configuration each iteration to a more "common" value
1583 // to see if the device will support it.
1584 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1585 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1586 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1587 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1588 } else {
1589 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1590 "format %#x, channelMask 0x%X",
1591 sampleRate, format, channelMask);
1592 break; // retries failed, break out of loop with frames == 0.
1593 }
1594 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001595 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001596 if (frames > 0 && config.sample_rate != sampleRate) {
1597 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1598 }
1599 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600}
1601
Glenn Kasten5f972c02014-01-13 09:59:31 -08001602uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 Mutex::Autolock _l(mLock);
1605
1606 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1607 if (recordThread != NULL) {
1608 return recordThread->getInputFramesLost();
1609 }
1610 return 0;
1611}
1612
1613status_t AudioFlinger::setVoiceVolume(float value)
1614{
Eric Laurenta1884f92011-08-23 08:25:03 -07001615 status_t ret = initCheck();
1616 if (ret != NO_ERROR) {
1617 return ret;
1618 }
1619
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 // check calling permissions
1621 if (!settingsAllowed()) {
1622 return PERMISSION_DENIED;
1623 }
1624
1625 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001626 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001627 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001628 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 mHardwareStatus = AUDIO_HW_IDLE;
1630
1631 return ret;
1632}
1633
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001634status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001635 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 Mutex::Autolock _l(mLock);
1638
1639 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1640 if (playbackThread != NULL) {
1641 return playbackThread->getRenderPosition(halFrames, dspFrames);
1642 }
1643
1644 return BAD_VALUE;
1645}
1646
1647void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1648{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001650 if (client == 0) {
1651 return;
1652 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001653 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001654 {
1655 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001656 if (mNotificationClients.indexOfKey(pid) < 0) {
1657 sp<NotificationClient> notificationClient = new NotificationClient(this,
1658 client,
1659 pid);
1660 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661
Eric Laurent021cf962014-05-13 10:18:14 -07001662 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663
Marco Nelissen06b46062014-11-14 07:58:25 -08001664 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001665 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001666 }
1667 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668
Eric Laurent021cf962014-05-13 10:18:14 -07001669 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001670 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001671 // the config change is always sent from playback or record threads to avoid deadlock
1672 // with AudioSystem::gLock
1673 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001674 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001675 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001677 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001678 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679 }
1680}
1681
1682void AudioFlinger::removeNotificationClient(pid_t pid)
1683{
Eric Laurent6c796322019-04-09 14:13:17 -07001684 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001685 {
Eric Laurent6c796322019-04-09 14:13:17 -07001686 Mutex::Autolock _l(mLock);
1687 {
1688 Mutex::Autolock _cl(mClientLock);
1689 mNotificationClients.removeItem(pid);
1690 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001691
Eric Laurent6c796322019-04-09 14:13:17 -07001692 ALOGV("%d died, releasing its sessions", pid);
1693 size_t num = mAudioSessionRefs.size();
1694 bool removed = false;
1695 for (size_t i = 0; i < num; ) {
1696 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1697 ALOGV(" pid %d @ %zu", ref->mPid, i);
1698 if (ref->mPid == pid) {
1699 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1700 mAudioSessionRefs.removeAt(i);
1701 delete ref;
1702 removed = true;
1703 num--;
1704 } else {
1705 i++;
1706 }
1707 }
1708 if (removed) {
1709 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001710 }
1711 }
Eric Laurent6c796322019-04-09 14:13:17 -07001712 for (auto& effect : removedEffects) {
1713 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715}
1716
Eric Laurent73e26b62015-04-27 16:55:58 -07001717void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001718 const sp<AudioIoDescriptor>& ioDesc,
1719 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720{
Eric Laurent021cf962014-05-13 10:18:14 -07001721 Mutex::Autolock _l(mClientLock);
1722 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001724 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1725 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1726 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 }
1728}
1729
Eric Laurent021cf962014-05-13 10:18:14 -07001730// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731void AudioFlinger::removeClient_l(pid_t pid)
1732{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001733 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001734 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 mClients.removeItem(pid);
1736}
1737
Eric Laurent717e1282012-06-29 16:36:52 -07001738// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001739sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1740 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001741{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001742 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001743
1744 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001745 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001746 ALOG_ASSERT(thread == 0);
1747 thread = mPlaybackThreads.valueAt(i);
1748 }
1749 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001750 if (thread != nullptr) {
1751 return thread;
1752 }
1753 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1754 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1755 ALOG_ASSERT(thread == 0);
1756 thread = mRecordThreads.valueAt(i);
1757 }
1758 }
1759 if (thread != nullptr) {
1760 return thread;
1761 }
1762 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1763 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1764 ALOG_ASSERT(thread == 0);
1765 thread = mMmapThreads.valueAt(i);
1766 }
1767 }
Eric Laurent717e1282012-06-29 16:36:52 -07001768 return thread;
1769}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772
1773// ----------------------------------------------------------------------------
1774
1775AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1776 : RefBase(),
1777 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001778 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779{
Andy Hung6f248bb2018-01-23 14:04:37 -08001780 mMemoryDealer = new MemoryDealer(
1781 audioFlinger->getClientSharedHeapSize(),
1782 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783}
1784
Eric Laurent021cf962014-05-13 10:18:14 -07001785// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786AudioFlinger::Client::~Client()
1787{
1788 mAudioFlinger->removeClient_l(mPid);
1789}
1790
Glenn Kasten435dbe62012-01-30 10:15:48 -08001791sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792{
1793 return mMemoryDealer;
1794}
1795
1796// ----------------------------------------------------------------------------
1797
1798AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1799 const sp<IAudioFlingerClient>& client,
1800 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001801 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802{
1803}
1804
1805AudioFlinger::NotificationClient::~NotificationClient()
1806{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807}
1808
Glenn Kasten0f11b512014-01-31 16:18:54 -08001809void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810{
1811 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001812 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813}
1814
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001815// ----------------------------------------------------------------------------
1816AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1817 : mPendingRequests(false) {}
1818
1819
1820void AudioFlinger::MediaLogNotifier::requestMerge() {
1821 AutoMutex _l(mMutex);
1822 mPendingRequests = true;
1823 mCond.signal();
1824}
1825
1826bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001827 // Should already have been checked, but just in case
1828 if (sMediaLogService == 0) {
1829 return false;
1830 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001831 // Wait until there are pending requests
1832 {
1833 AutoMutex _l(mMutex);
1834 mPendingRequests = false; // to ignore past requests
1835 while (!mPendingRequests) {
1836 mCond.wait(mMutex);
1837 // TODO may also need an exitPending check
1838 }
1839 mPendingRequests = false;
1840 }
1841 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001842 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001843 usleep(kPostTriggerSleepPeriod);
1844 return true;
1845}
1846
1847void AudioFlinger::requestLogMerge() {
1848 mMediaLogNotifier->requestMerge();
1849}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850
1851// ----------------------------------------------------------------------------
1852
Eric Laurentf14db3c2017-12-08 14:20:36 -08001853sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1854 CreateRecordOutput& output,
1855 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856{
1857 sp<RecordThread::RecordTrack> recordTrack;
1858 sp<RecordHandle> recordHandle;
1859 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001861 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001862 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863
Eric Laurentf14db3c2017-12-08 14:20:36 -08001864 output.cblk.clear();
1865 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001866 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001867
Eric Laurentf14db3c2017-12-08 14:20:36 -08001868 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001869 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001870 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001871 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001872 ALOGW_IF(clientUid != callingUid,
1873 "%s uid %d tried to pass itself off as %d",
1874 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001875 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001876 updatePid = true;
1877 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001878 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001879 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001880 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001881 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001882 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001883 __func__, callingUid, callingPid, clientPid);
1884 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001885 }
1886
Andy Hung6770c6f2015-04-07 13:43:36 -07001887 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001888 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1889 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001890 lStatus = BAD_VALUE;
1891 goto Exit;
1892 }
1893
Glenn Kasten53b5d092014-02-05 10:00:23 -08001894 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001895 if (!audio_is_input_channel(input.config.channel_mask)) {
1896 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001897 lStatus = BAD_VALUE;
1898 goto Exit;
1899 }
1900
Eric Laurentf14db3c2017-12-08 14:20:36 -08001901 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1902 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1903 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1904 lStatus = BAD_VALUE;
1905 goto Exit;
1906 }
1907
1908 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001909 output.selectedDeviceId = input.selectedDeviceId;
1910 output.flags = input.flags;
1911
1912 client = registerPid(clientPid);
1913
1914 // Not a conventional loop, but a retry loop for at most two iterations total.
1915 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1916 // Exits loop via break on no error of got exit on error
1917 // The sp<> references will be dropped when re-entering scope.
1918 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1919 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001920 // release previously opened input if retrying.
1921 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1922 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001923 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001924 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001925 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001926 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001927 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001928 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001929 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001930 sessionId,
1931 // FIXME compare to AudioTrack
1932 clientPid,
1933 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001934 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001935 &input.config,
1936 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07001937 if (lStatus != NO_ERROR) {
1938 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
1939 goto Exit;
1940 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001941
Glenn Kasten05997e22014-03-13 15:08:33 -07001942 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001944 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 if (thread == NULL) {
jiabinc1de2df2019-05-07 14:26:40 -07001946 ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 lStatus = BAD_VALUE;
1948 goto Exit;
1949 }
1950
Eric Laurentf14db3c2017-12-08 14:20:36 -08001951 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952
Eric Laurentf14db3c2017-12-08 14:20:36 -08001953 output.sampleRate = input.config.sample_rate;
1954 output.frameCount = input.frameCount;
1955 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001956
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001957 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001958 input.config.format, input.config.channel_mask,
1959 &output.frameCount, sessionId,
1960 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001961 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001962 input.clientInfo.clientTid,
Jean-Michel Trivi73072932019-08-20 15:42:04 -07001963 &lStatus, portId,
1964 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001965 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001966
Eric Laurentf14db3c2017-12-08 14:20:36 -08001967 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1968 // audio policy manager without FAST constraint
1969 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001970 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001971 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001972
1973 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001974 goto Exit;
1975 }
1976
1977 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1978 // session and move it to this thread.
1979 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1980 if (chain != 0) {
1981 Mutex::Autolock _l(thread->mLock);
1982 thread->addEffectChain_l(chain);
1983 }
1984 break;
1985 }
1986 // End of retry loop.
1987 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 }
Glenn Kastene198c362013-08-13 09:13:36 -07001989
Eric Laurentf14db3c2017-12-08 14:20:36 -08001990 output.cblk = recordTrack->getCblk();
1991 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001992 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001993
1994 // return handle to client
1995 recordHandle = new RecordHandle(recordTrack);
1996
1997Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001998 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001999 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002000 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002001 // Don't hold mClientLock when releasing the reference on the track as the
2002 // destructor will acquire it.
2003 {
2004 Mutex::Autolock _cl(mClientLock);
2005 client.clear();
2006 }
Eric Laurent896c9672017-12-08 14:08:45 -08002007 recordTrack.clear();
2008 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002009 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002010 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 }
2012
Glenn Kasten9156ef32013-08-06 15:39:08 -07002013 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 return recordHandle;
2015}
2016
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002017
2018
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019// ----------------------------------------------------------------------------
2020
Eric Laurenta4c5a552012-03-29 10:12:40 -07002021audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2022{
Eric Laurent44622db2014-08-01 19:00:33 -07002023 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002024 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002025 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002026 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002027 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002028 }
2029 Mutex::Autolock _l(mLock);
2030 return loadHwModule_l(name);
2031}
2032
2033// loadHwModule_l() must be called with AudioFlinger::mLock held
2034audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2035{
2036 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2037 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2038 ALOGW("loadHwModule() module %s already loaded", name);
2039 return mAudioHwDevs.keyAt(i);
2040 }
2041 }
2042
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002043 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002044
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002045 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002046 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002047 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002048 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002049 }
2050
2051 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002052 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002053 mHardwareStatus = AUDIO_HW_IDLE;
2054 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002055 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002056 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002057 }
2058
John Grossmanee578c02012-07-23 17:05:46 -07002059 // Check and cache this HAL's level of support for master mute and master
2060 // volume. If this is the first HAL opened, and it supports the get
2061 // methods, use the initial values provided by the HAL as the current
2062 // master mute and volume settings.
2063
2064 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2065 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002066 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002067
2068 if (0 == mAudioHwDevs.size()) {
2069 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002070 float mv;
2071 if (OK == dev->getMasterVolume(&mv)) {
2072 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002073 }
2074
2075 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002076 bool mm;
2077 if (OK == dev->getMasterMute(&mm)) {
2078 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002079 }
2080 }
2081
Eric Laurenta4c5a552012-03-29 10:12:40 -07002082 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002083 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002084 flags = static_cast<AudioHwDevice::Flags>(flags |
2085 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2086 }
2087
2088 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002089 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002090 flags = static_cast<AudioHwDevice::Flags>(flags |
2091 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2092 }
2093
Eric Laurenta4c5a552012-03-29 10:12:40 -07002094 mHardwareStatus = AUDIO_HW_IDLE;
2095 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002096 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002097 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2098 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2099 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002100
Glenn Kastena13cde92016-03-28 15:26:02 -07002101 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002102 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002103
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002104 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002105
2106 return handle;
2107
2108}
2109
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002110// ----------------------------------------------------------------------------
2111
Glenn Kasten3b16c762012-11-14 08:44:39 -08002112uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002113{
2114 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002115 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002116 return thread != NULL ? thread->sampleRate() : 0;
2117}
2118
Glenn Kastene33054e2012-11-14 12:54:39 -08002119size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002120{
2121 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002122 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002123 return thread != NULL ? thread->frameCountHAL() : 0;
2124}
2125
2126// ----------------------------------------------------------------------------
2127
Andy Hung6f248bb2018-01-23 14:04:37 -08002128status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002129{
2130 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002131 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002132 return PERMISSION_DENIED;
2133 }
2134 Mutex::Autolock _l(mLock);
2135 if (mIsDeviceTypeKnown) {
2136 return INVALID_OPERATION;
2137 }
2138 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002139 mTotalMemory = totalMemory;
2140 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2141 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2142 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2143 // though actual setting is determined through device configuration.
2144 constexpr int64_t GB = 1024 * 1024 * 1024;
2145 mClientSharedHeapSize =
2146 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2147 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2148 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2149 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2150 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002151 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002152
2153 // TODO: Cache the client shared heap size in a persistent property.
2154 // It's possible that a native process or Java service or app accesses audioserver
2155 // after it is registered by system server, but before AudioService updates
2156 // the memory info. This would occur immediately after boot or an audioserver
2157 // crash and restore. Before update from AudioService, the client would get the
2158 // minimum heap size.
2159
2160 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2161 (isLowRamDevice ? "true" : "false"),
2162 (long long)mTotalMemory,
2163 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002164 return NO_ERROR;
2165}
2166
Andy Hung6f248bb2018-01-23 14:04:37 -08002167size_t AudioFlinger::getClientSharedHeapSize() const
2168{
2169 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2170 if (heapSizeInBytes != 0) { // read-only property overrides all.
2171 return heapSizeInBytes;
2172 }
2173 return mClientSharedHeapSize;
2174}
2175
Mikhail Naganovdea53042018-04-26 13:10:21 -07002176status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2177{
2178 ALOGV(__func__);
2179
2180 audio_module_handle_t module;
2181 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2182 module = config->ext.device.hw_module;
2183 } else {
2184 module = config->ext.mix.hw_module;
2185 }
2186
2187 Mutex::Autolock _l(mLock);
2188 ssize_t index = mAudioHwDevs.indexOfKey(module);
2189 if (index < 0) {
2190 ALOGW("%s() bad hw module %d", __func__, module);
2191 return BAD_VALUE;
2192 }
2193
2194 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2195 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2196}
2197
Eric Laurent93c3d412014-08-01 14:48:35 -07002198audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2199{
2200 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002201
2202 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2203 if (index >= 0) {
2204 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2205 mHwAvSyncIds.valueAt(index), sessionId);
2206 return mHwAvSyncIds.valueAt(index);
2207 }
2208
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002209 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002210 if (dev == NULL) {
2211 return AUDIO_HW_SYNC_INVALID;
2212 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002213 String8 reply;
2214 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002215 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002216 param = AudioParameter(reply);
2217 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002218
2219 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002220 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002221 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2222 return AUDIO_HW_SYNC_INVALID;
2223 }
2224
2225 // allow only one session for a given HW A/V sync ID.
2226 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2227 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2228 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2229 value, mHwAvSyncIds.keyAt(i));
2230 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002231 break;
2232 }
2233 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002234
2235 mHwAvSyncIds.add(sessionId, value);
2236
2237 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2238 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2239 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002240 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002241 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002242 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002243 String8 keyValuePairs = param.toString();
2244 thread->setParameters(keyValuePairs);
2245 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2246 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002247 break;
2248 }
2249 }
2250
2251 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2252 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002253}
2254
Eric Laurent72e3f392015-05-20 14:43:50 -07002255status_t AudioFlinger::systemReady()
2256{
2257 Mutex::Autolock _l(mLock);
2258 ALOGI("%s", __FUNCTION__);
2259 if (mSystemReady) {
2260 ALOGW("%s called twice", __FUNCTION__);
2261 return NO_ERROR;
2262 }
2263 mSystemReady = true;
2264 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2265 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2266 thread->systemReady();
2267 }
2268 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2269 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2270 thread->systemReady();
2271 }
2272 return NO_ERROR;
2273}
2274
jiabin46a76fa2018-01-05 10:18:21 -08002275status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2276{
jiabin9ff780e2018-03-19 18:19:52 -07002277 AutoMutex lock(mHardwareLock);
2278 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2279 status_t status = dev->getMicrophones(microphones);
2280 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002281}
2282
Eric Laurentfa90e842014-10-17 18:12:31 -07002283// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2284void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2285{
2286 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2287 if (index >= 0) {
2288 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2289 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2290 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002291 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002292 String8 keyValuePairs = param.toString();
2293 thread->setParameters(keyValuePairs);
2294 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2295 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002296 }
2297}
2298
2299
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002300// ----------------------------------------------------------------------------
2301
Eric Laurent83b88082014-06-20 18:31:16 -07002302
Eric Laurent6acd1d42017-01-04 14:23:29 -08002303sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002304 audio_io_handle_t *output,
2305 audio_config_t *config,
2306 audio_devices_t devices,
2307 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002308 audio_output_flags_t flags)
2309{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002310 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002311 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002312 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002313 }
2314
Eric Laurentcf2c0212014-07-25 16:20:43 -07002315 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002316 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2317 } else {
2318 // Audio Policy does not currently request a specific output handle.
2319 // If this is ever needed, see openInput_l() for example code.
2320 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2321 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002322 }
Eric Laurent83b88082014-06-20 18:31:16 -07002323
2324 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2325
Eric Laurent83b88082014-06-20 18:31:16 -07002326 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002327 // This if statement allows overriding the audio policy settings
2328 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2329 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2330 // Check only for Normal Mixing mode
2331 if (kEnableExtendedPrecision) {
2332 // Specify format (uncomment one below to choose)
2333 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2334 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2335 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2336 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002337 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002338 }
2339 if (kEnableExtendedChannels) {
2340 // Specify channel mask (uncomment one below to choose)
2341 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2342 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2343 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2344 }
Eric Laurent83b88082014-06-20 18:31:16 -07002345 }
2346
Phil Burk062e67a2015-02-11 13:40:50 -08002347 AudioStreamOut *outputStream = NULL;
2348 status_t status = outHwDev->openOutputStream(
2349 &outputStream,
2350 *output,
2351 devices,
2352 flags,
2353 config,
2354 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002355
2356 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002357
Phil Burk062e67a2015-02-11 13:40:50 -08002358 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002359 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2360 sp<MmapPlaybackThread> thread =
2361 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2362 devices, AUDIO_DEVICE_NONE, mSystemReady);
2363 mMmapThreads.add(*output, thread);
2364 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2365 *output, thread.get());
2366 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002367 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002368 sp<PlaybackThread> thread;
2369 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2370 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2371 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2372 *output, thread.get());
2373 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2374 || !isValidPcmSinkFormat(config->format)
2375 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2376 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2377 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2378 *output, thread.get());
2379 } else {
2380 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2381 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2382 *output, thread.get());
2383 }
2384 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002385 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002386 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002387 }
Eric Laurent83b88082014-06-20 18:31:16 -07002388 }
2389
2390 return 0;
2391}
2392
Eric Laurentcf2c0212014-07-25 16:20:43 -07002393status_t AudioFlinger::openOutput(audio_module_handle_t module,
2394 audio_io_handle_t *output,
2395 audio_config_t *config,
2396 audio_devices_t *devices,
2397 const String8& address,
2398 uint32_t *latencyMs,
2399 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002401 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2402 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002403 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002404 (devices != NULL) ? *devices : 0,
2405 config->sample_rate,
2406 config->format,
2407 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002408 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002410 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002411 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002413
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 Mutex::Autolock _l(mLock);
2415
Eric Laurent6acd1d42017-01-04 14:23:29 -08002416 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002417 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002418 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2419 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2420 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421
Eric Laurent6acd1d42017-01-04 14:23:29 -08002422 // notify client processes of the new output creation
2423 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002424
Eric Laurent6acd1d42017-01-04 14:23:29 -08002425 // the first primary output opened designates the primary hw device
2426 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002427 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002428 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002429
Eric Laurent6acd1d42017-01-04 14:23:29 -08002430 AutoMutex lock(mHardwareLock);
2431 mHardwareStatus = AUDIO_HW_SET_MODE;
2432 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2433 mHardwareStatus = AUDIO_HW_IDLE;
2434 }
2435 } else {
2436 MmapThread *mmapThread = (MmapThread *)thread.get();
2437 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002438 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002439 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 }
2441
Eric Laurentcf2c0212014-07-25 16:20:43 -07002442 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443}
2444
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002445audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2446 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447{
2448 Mutex::Autolock _l(mLock);
2449 MixerThread *thread1 = checkMixerThread_l(output1);
2450 MixerThread *thread2 = checkMixerThread_l(output2);
2451
2452 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002453 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2454 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002455 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 }
2457
Glenn Kasteneeecb982016-02-26 10:44:04 -08002458 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002459 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 thread->addOutputTrack(thread2);
2461 mPlaybackThreads.add(id, thread);
2462 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002463 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464 return id;
2465}
2466
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002467status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468{
Glenn Kastend96c5722012-04-25 13:44:49 -07002469 return closeOutput_nonvirtual(output);
2470}
2471
2472status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2473{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474 // keep strong reference on the playback thread so that
2475 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002476 sp<PlaybackThread> playbackThread;
2477 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 {
2479 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002480 playbackThread = checkPlaybackThread_l(output);
2481 if (playbackThread != NULL) {
2482 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483
Andy Hungdc099c22018-09-18 13:46:39 -07002484 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002485
Eric Laurent6acd1d42017-01-04 14:23:29 -08002486 if (playbackThread->type() == ThreadBase::MIXER) {
2487 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2488 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2489 DuplicatingThread *dupThread =
2490 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2491 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002493 }
2494 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495
2496
Eric Laurent6acd1d42017-01-04 14:23:29 -08002497 mPlaybackThreads.removeItem(output);
2498 // save all effects to the default thread
2499 if (mPlaybackThreads.size()) {
2500 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2501 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002502 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002503 Mutex::Autolock _dl(dstThread->mLock);
2504 Mutex::Autolock _sl(playbackThread->mLock);
2505 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2506 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002507 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002508 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 }
2511 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002512 } else {
2513 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2514 if (mmapThread == 0) {
2515 return BAD_VALUE;
2516 }
Andy Hungdc099c22018-09-18 13:46:39 -07002517 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002518 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002519 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002521 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2522 ioDesc->mIoHandle = output;
2523 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002524 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002526 // The thread entity (active unit of execution) is no longer running here,
2527 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 if (playbackThread != 0) {
2530 playbackThread->exit();
2531 if (!playbackThread->isDuplicating()) {
2532 closeOutputFinish(playbackThread);
2533 }
2534 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002535 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002536 mmapThread->exit();
2537 AudioStreamOut *out = mmapThread->clearOutput();
2538 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2539 // from now on thread->mOutput is NULL
2540 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 }
2542 return NO_ERROR;
2543}
2544
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002545void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002546{
2547 AudioStreamOut *out = thread->clearOutput();
2548 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2549 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002550 delete out;
2551}
2552
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002553void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002554{
2555 mPlaybackThreads.removeItem(thread->mId);
2556 thread->exit();
2557 closeOutputFinish(thread);
2558}
2559
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002560status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561{
2562 Mutex::Autolock _l(mLock);
2563 PlaybackThread *thread = checkPlaybackThread_l(output);
2564
2565 if (thread == NULL) {
2566 return BAD_VALUE;
2567 }
2568
Steve Block3856b092011-10-20 11:56:00 +01002569 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570 thread->suspend();
2571
2572 return NO_ERROR;
2573}
2574
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002575status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576{
2577 Mutex::Autolock _l(mLock);
2578 PlaybackThread *thread = checkPlaybackThread_l(output);
2579
2580 if (thread == NULL) {
2581 return BAD_VALUE;
2582 }
2583
Steve Block3856b092011-10-20 11:56:00 +01002584 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585
2586 thread->restore();
2587
2588 return NO_ERROR;
2589}
2590
Eric Laurentcf2c0212014-07-25 16:20:43 -07002591status_t AudioFlinger::openInput(audio_module_handle_t module,
2592 audio_io_handle_t *input,
2593 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002594 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002595 const String8& address,
2596 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002597 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598{
Eric Laurent83b88082014-06-20 18:31:16 -07002599 Mutex::Autolock _l(mLock);
2600
Glenn Kastene7d66712015-03-05 13:46:52 -08002601 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002602 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002603 }
2604
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002605 sp<ThreadBase> thread = openInput_l(
2606 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002607
2608 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002609 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002610 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002611 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002613 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002614}
Dima Zavin799a70e2011-04-18 16:57:27 -07002615
Eric Laurent6acd1d42017-01-04 14:23:29 -08002616sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002617 audio_io_handle_t *input,
2618 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002619 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002620 const String8& address,
2621 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002622 audio_input_flags_t flags,
2623 audio_devices_t outputDevice,
2624 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002625{
Glenn Kastene7d66712015-03-05 13:46:52 -08002626 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002627 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002628 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002629 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002630 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002631
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002632 // Some flags are specific to framework and must not leak to the HAL.
2633 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2634
Glenn Kasteneeecb982016-02-26 10:44:04 -08002635 // Audio Policy can request a specific handle for hardware hotword.
2636 // The goal here is not to re-open an already opened input.
2637 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002638 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002639 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2640 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2641 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2642 return 0;
2643 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2644 // This should not happen in a transient state with current design.
2645 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2646 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002647 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002648
Eric Laurentcf2c0212014-07-25 16:20:43 -07002649 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002650 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002651 sp<StreamInHalInterface> inStream;
2652 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002653 *input, devices, &halconfig, flags, address.string(), source,
2654 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002655 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2656 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002657 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002658 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002659 halconfig.sample_rate,
2660 halconfig.format,
2661 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002662 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002663 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002665 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002666 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002667 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002668 audio_is_linear_pcm(config->format) &&
2669 audio_is_linear_pcm(halconfig.format) &&
2670 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002671 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2672 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002673 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002674 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002675 inStream.clear();
2676 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002677 *input, devices, &halconfig, flags, address.string(), source,
2678 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002679 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 }
2681
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002682 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002683 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002684 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2685 sp<MmapCaptureThread> thread =
2686 new MmapCaptureThread(this, *input,
2687 inHwDev, inputStream,
2688 primaryOutputDevice_l(), devices, mSystemReady);
2689 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002690 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2691 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002692 return thread;
2693 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002694 // Start record thread
2695 // RecordThread requires both input and output device indication to forward to audio
2696 // pre processing modules
2697 sp<RecordThread> thread = new RecordThread(this,
2698 inputStream,
2699 *input,
2700 primaryOutputDevice_l(),
2701 devices,
2702 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002703 );
2704 mRecordThreads.add(*input, thread);
2705 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2706 return thread;
2707 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 }
2709
Eric Laurentcf2c0212014-07-25 16:20:43 -07002710 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711 return 0;
2712}
2713
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002714status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715{
Glenn Kastend96c5722012-04-25 13:44:49 -07002716 return closeInput_nonvirtual(input);
2717}
2718
2719status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2720{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 // keep strong reference on the record thread so that
2722 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002723 sp<RecordThread> recordThread;
2724 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725 {
2726 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002727 recordThread = checkRecordThread_l(input);
2728 if (recordThread != 0) {
2729 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730
Andy Hungdc099c22018-09-18 13:46:39 -07002731 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002732
Eric Laurent6acd1d42017-01-04 14:23:29 -08002733 // If we still have effect chains, it means that a client still holds a handle
2734 // on at least one effect. We must either move the chain to an existing thread with the
2735 // same session ID or put it aside in case a new record thread is opened for a
2736 // new capture on the same session
2737 sp<EffectChain> chain;
2738 {
2739 Mutex::Autolock _sl(recordThread->mLock);
2740 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2741 // Note: maximum one chain per record thread
2742 if (effectChains.size() != 0) {
2743 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002744 }
2745 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002746 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002747 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002748 // This should only happen in case of overlap between one thread tear down and the
2749 // creation of its replacement
2750 size_t i;
2751 for (i = 0; i < mRecordThreads.size(); i++) {
2752 sp<RecordThread> t = mRecordThreads.valueAt(i);
2753 if (t == recordThread) {
2754 continue;
2755 }
2756 if (t->hasAudioSession(chain->sessionId()) != 0) {
2757 Mutex::Autolock _l(t->mLock);
2758 ALOGV("closeInput() found thread %d for effect session %d",
2759 t->id(), chain->sessionId());
2760 t->addEffectChain_l(chain);
2761 break;
2762 }
2763 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002764 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002765 if (i == mRecordThreads.size()) {
2766 putOrphanEffectChain_l(chain);
2767 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002768 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002769 mRecordThreads.removeItem(input);
2770 } else {
2771 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2772 if (mmapThread == 0) {
2773 return BAD_VALUE;
2774 }
Andy Hungdc099c22018-09-18 13:46:39 -07002775 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002776 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002777 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002778 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2779 ioDesc->mIoHandle = input;
2780 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781 }
Eric Laurent83b88082014-06-20 18:31:16 -07002782 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2783 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002784 if (recordThread != 0) {
2785 closeInputFinish(recordThread);
2786 } else if (mmapThread != 0) {
2787 mmapThread->exit();
2788 AudioStreamIn *in = mmapThread->clearInput();
2789 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2790 // from now on thread->mInput is NULL
2791 delete in;
2792 }
Eric Laurent83b88082014-06-20 18:31:16 -07002793 return NO_ERROR;
2794}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002796void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002797{
2798 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002799 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002800 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002801 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002802 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002803}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002805void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002806{
2807 mRecordThreads.removeItem(thread->mId);
2808 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809}
2810
Glenn Kastend2304db2014-02-03 07:40:31 -08002811status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812{
2813 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002814 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815
2816 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2817 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002818 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002819 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002820 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2821 mMmapThreads[i]->invalidateTracks(stream);
2822 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 return NO_ERROR;
2824}
2825
2826
Glenn Kasteneeecb982016-02-26 10:44:04 -08002827audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828{
Glenn Kasten9d003132016-04-06 14:38:09 -07002829 // This is a binder API, so a malicious client could pass in a bad parameter.
2830 // Check for that before calling the internal API nextUniqueId().
2831 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2832 ALOGE("newAudioUniqueId invalid use %d", use);
2833 return AUDIO_UNIQUE_ID_ALLOCATE;
2834 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002835 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836}
2837
Glenn Kastend848eb42016-03-08 13:42:11 -08002838void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002839{
2840 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002841 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002842 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002843 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2844 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002845 caller = pid;
2846 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002847
Eric Laurent021cf962014-05-13 10:18:14 -07002848 {
2849 Mutex::Autolock _cl(mClientLock);
2850 // Ignore requests received from processes not known as notification client. The request
2851 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2852 // called from a different pid leaving a stale session reference. Also we don't know how
2853 // to clear this reference if the client process dies.
2854 if (mNotificationClients.indexOfKey(caller) < 0) {
2855 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2856 return;
2857 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002858 }
2859
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002860 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002861 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002862 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002863 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2864 ref->mCnt++;
2865 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002866 return;
2867 }
2868 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002869 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2870 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002871}
2872
Glenn Kastend848eb42016-03-08 13:42:11 -08002873void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002874{
Eric Laurent6c796322019-04-09 14:13:17 -07002875 std::vector< sp<EffectModule> > removedEffects;
2876 {
2877 Mutex::Autolock _l(mLock);
2878 pid_t caller = IPCThreadState::self()->getCallingPid();
2879 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2880 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2881 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2882 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002883 }
Eric Laurent6c796322019-04-09 14:13:17 -07002884 size_t num = mAudioSessionRefs.size();
2885 for (size_t i = 0; i < num; i++) {
2886 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2887 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2888 ref->mCnt--;
2889 ALOGV(" decremented refcount to %d", ref->mCnt);
2890 if (ref->mCnt == 0) {
2891 mAudioSessionRefs.removeAt(i);
2892 delete ref;
2893 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2894 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2895 }
2896 goto Exit;
2897 }
2898 }
2899 // If the caller is audioserver it is likely that the session being released was acquired
2900 // on behalf of a process not in notification clients and we ignore the warning.
2901 ALOGW_IF(!isAudioServerUid(callerUid),
2902 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002903 }
Eric Laurent6c796322019-04-09 14:13:17 -07002904
2905Exit:
2906 for (auto& effect : removedEffects) {
2907 effect->updatePolicyState();
2908 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002909}
2910
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002911bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2912{
2913 size_t num = mAudioSessionRefs.size();
2914 for (size_t i = 0; i < num; i++) {
2915 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2916 if (ref->mSessionid == audioSession) {
2917 return true;
2918 }
2919 }
2920 return false;
2921}
2922
Eric Laurent6c796322019-04-09 14:13:17 -07002923std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002924
Steve Block3856b092011-10-20 11:56:00 +01002925 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002926
2927 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002928 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002929
2930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2931 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002932 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002933 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2934 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002935 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2936 chains.push(ec);
2937 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002938 }
2939 }
Eric Laurent6c796322019-04-09 14:13:17 -07002940
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002941 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2942 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002943 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002944 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2945 sp<EffectChain> ec = t->mEffectChains[j];
2946 chains.push(ec);
2947 }
2948 }
2949
Eric Laurent6c796322019-04-09 14:13:17 -07002950 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2951 sp<MmapThread> t = mMmapThreads.valueAt(i);
2952 Mutex::Autolock _l(t->mLock);
2953 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2954 sp<EffectChain> ec = t->mEffectChains[j];
2955 chains.push(ec);
2956 }
2957 }
2958
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002959 for (size_t i = 0; i < chains.size(); i++) {
2960 sp<EffectChain> ec = chains[i];
2961 int sessionid = ec->sessionId();
2962 sp<ThreadBase> t = ec->mThread.promote();
2963 if (t == 0) {
2964 continue;
2965 }
2966 size_t numsessionrefs = mAudioSessionRefs.size();
2967 bool found = false;
2968 for (size_t k = 0; k < numsessionrefs; k++) {
2969 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002970 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002971 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002972 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002973 found = true;
2974 break;
2975 }
2976 }
2977 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002978 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002979 // remove all effects from the chain
2980 while (ec->mEffects.size()) {
2981 sp<EffectModule> effect = ec->mEffects[0];
2982 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002983 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002984 if (effect->purgeHandles()) {
2985 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002986 }
Eric Laurent6c796322019-04-09 14:13:17 -07002987 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002988 }
2989 }
2990 }
Eric Laurent6c796322019-04-09 14:13:17 -07002991 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002992}
2993
Andy Hungdc099c22018-09-18 13:46:39 -07002994// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2995void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2996{
2997 audio_utils::FdToString fdToString;
2998 const int fd = fdToString.fd();
2999 if (fd >= 0) {
3000 thread->dump(fd, {} /* args */);
3001 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3002 }
3003}
3004
Glenn Kasteneeecb982016-02-26 10:44:04 -08003005// checkThread_l() must be called with AudioFlinger::mLock held
3006AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3007{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003008 ThreadBase *thread = checkMmapThread_l(ioHandle);
3009 if (thread == 0) {
3010 switch (audio_unique_id_get_use(ioHandle)) {
3011 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3012 thread = checkPlaybackThread_l(ioHandle);
3013 break;
3014 case AUDIO_UNIQUE_ID_USE_INPUT:
3015 thread = checkRecordThread_l(ioHandle);
3016 break;
3017 default:
3018 break;
3019 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003020 }
3021 return thread;
3022}
3023
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003025AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026{
Glenn Kastena1117922012-01-26 10:53:32 -08003027 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028}
3029
3030// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003031AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032{
3033 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003034 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035}
3036
3037// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003038AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039{
Glenn Kastena1117922012-01-26 10:53:32 -08003040 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041}
3042
Eric Laurent6acd1d42017-01-04 14:23:29 -08003043// checkMmapThread_l() must be called with AudioFlinger::mLock held
3044AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3045{
3046 return mMmapThreads.valueFor(io).get();
3047}
3048
3049
3050// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3051AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3052{
Eric Laurent7459b902017-04-19 18:10:41 -07003053 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003054 if (volumeInterface == nullptr) {
3055 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3056 if (mmapThread != nullptr) {
3057 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003058 MmapPlaybackThread *mmapPlaybackThread =
3059 static_cast<MmapPlaybackThread *>(mmapThread);
3060 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003061 }
3062 }
3063 }
3064 return volumeInterface;
3065}
3066
3067Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3068{
3069 Vector <VolumeInterface *> volumeInterfaces;
3070 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003071 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003072 }
3073 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3074 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003075 MmapPlaybackThread *mmapPlaybackThread =
3076 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3077 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003078 }
3079 }
3080 return volumeInterfaces;
3081}
3082
Glenn Kasteneeecb982016-02-26 10:44:04 -08003083audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084{
Glenn Kasten9d003132016-04-06 14:38:09 -07003085 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003086 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003087 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3088 for (int retry = 0; retry < maxRetries; retry++) {
3089 // The cast allows wraparound from max positive to min negative instead of abort
3090 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3091 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3092 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3093 // allow wrap by skipping 0 and -1 for session ids
3094 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3095 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3096 return (audio_unique_id_t) (base | use);
3097 }
3098 }
3099 // We have no way of recovering from wraparound
3100 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3101 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102}
3103
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003104AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003105{
3106 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3107 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003108 if(thread->isDuplicating()) {
3109 continue;
3110 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003111 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003112 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003113 return thread;
3114 }
3115 }
3116 return NULL;
3117}
3118
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003119audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003120{
3121 PlaybackThread *thread = primaryPlaybackThread_l();
3122
3123 if (thread == NULL) {
3124 return 0;
3125 }
3126
Eric Laurentf1c04f92012-08-28 14:26:53 -07003127 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003128}
3129
Glenn Kastena7335632016-06-09 17:09:53 -07003130AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3131{
3132 size_t minFrameCount = 0;
3133 PlaybackThread *minThread = NULL;
3134 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3135 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3136 if (!thread->isDuplicating()) {
3137 size_t frameCount = thread->frameCountHAL();
3138 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3139 (frameCount == minFrameCount && thread->hasFastMixer() &&
3140 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3141 minFrameCount = frameCount;
3142 minThread = thread;
3143 }
3144 }
3145 }
3146 return minThread;
3147}
3148
Eric Laurenta011e352012-03-29 15:51:43 -07003149sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003150 audio_session_t triggerSession,
3151 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003152 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003153 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003154{
3155 Mutex::Autolock _l(mLock);
3156
3157 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3158 status_t playStatus = NAME_NOT_FOUND;
3159 status_t recStatus = NAME_NOT_FOUND;
3160 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3161 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3162 if (playStatus == NO_ERROR) {
3163 return event;
3164 }
3165 }
3166 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3167 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3168 if (recStatus == NO_ERROR) {
3169 return event;
3170 }
3171 }
3172 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3173 mPendingSyncEvents.add(event);
3174 } else {
3175 ALOGV("createSyncEvent() invalid event %d", event->type());
3176 event.clear();
3177 }
3178 return event;
3179}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003180
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181// ----------------------------------------------------------------------------
3182// Effect management
3183// ----------------------------------------------------------------------------
3184
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003185sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3186 return mEffectsFactoryHal;
3187}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188
Glenn Kastenf587ba52012-01-26 16:25:10 -08003189status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190{
3191 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003192 if (mEffectsFactoryHal.get()) {
3193 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3194 } else {
3195 return -ENODEV;
3196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197}
3198
Glenn Kastenf587ba52012-01-26 16:25:10 -08003199status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200{
3201 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003202 if (mEffectsFactoryHal.get()) {
3203 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3204 } else {
3205 return -ENODEV;
3206 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207}
3208
Glenn Kasten5e92a782012-01-30 07:40:52 -08003209status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003210 const effect_uuid_t *pTypeUuid,
3211 uint32_t preferredTypeFlag,
3212 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003214 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3215 return BAD_VALUE;
3216 }
3217
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003219
3220 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003221 return -ENODEV;
3222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003224 status_t status = NO_ERROR;
3225 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3226 // If uuid is specified, request effect descriptor from that.
3227 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3228 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3229 // If uuid is not specified, look for an available implementation
3230 // of the required type instead.
3231
3232 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3233 effect_descriptor_t desc;
3234 desc.flags = 0; // prevent compiler warning
3235
3236 uint32_t numEffects = 0;
3237 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3238 if (status < 0) {
3239 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3240 return status;
3241 }
3242
3243 bool found = false;
3244 for (uint32_t i = 0; i < numEffects; i++) {
3245 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3246 if (status < 0) {
3247 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3248 continue;
3249 }
3250 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3251 // If matching type found save effect descriptor.
3252 found = true;
3253 *descriptor = desc;
3254
3255 // If there's no preferred flag or this descriptor matches the preferred
3256 // flag, success! If this descriptor doesn't match the preferred
3257 // flag, continue enumeration in case a better matching version of this
3258 // effect type is available. Note that this means if no effect with a
3259 // correct flag is found, the descriptor returned will correspond to the
3260 // last effect that at least had a matching type uuid (if any).
3261 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3262 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3263 break;
3264 }
3265 }
3266 }
3267
3268 if (!found) {
3269 status = NAME_NOT_FOUND;
3270 ALOGW("getEffectDescriptor(): Effect not found by type.");
3271 }
3272 } else {
3273 status = BAD_VALUE;
3274 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3275 }
3276 return status;
3277}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003279sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 effect_descriptor_t *pDesc,
3281 const sp<IEffectClient>& effectClient,
3282 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003283 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003284 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003285 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003286 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 status_t *status,
3288 int *id,
3289 int *enabled)
3290{
3291 status_t lStatus = NO_ERROR;
3292 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294
Eric Laurentb6436272016-12-07 19:24:50 -08003295 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003296 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003297 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3298 ALOGW_IF(pid != -1 && pid != callingPid,
3299 "%s uid %d pid %d tried to pass itself off as pid %d",
3300 __func__, callingUid, callingPid, pid);
3301 pid = callingPid;
3302 }
3303
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003304 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3305 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306
3307 if (pDesc == NULL) {
3308 lStatus = BAD_VALUE;
3309 goto Exit;
3310 }
3311
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003312 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003313 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003314 lStatus = NO_INIT;
3315 goto Exit;
3316 }
3317
Andy Hung6096dcd2019-03-13 13:20:30 -07003318 // check audio settings permission for global effects
3319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3320 if (!settingsAllowed()) {
3321 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3322 lStatus = PERMISSION_DENIED;
3323 goto Exit;
3324 }
3325 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3326 if (!isAudioServerUid(callingUid)) {
3327 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3328 lStatus = PERMISSION_DENIED;
3329 goto Exit;
3330 }
3331
3332 if (io == AUDIO_IO_HANDLE_NONE) {
3333 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3334 lStatus = BAD_VALUE;
3335 goto Exit;
3336 }
3337 } else {
3338 // general sessionId.
3339
3340 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3341 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3342 lStatus = BAD_VALUE;
3343 goto Exit;
3344 }
3345
3346 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3347 // to prevent creating an effect when one doesn't actually have track with that session?
3348 }
3349
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003351 // Get the full effect descriptor from the uuid/type.
3352 // If the session is the output mix, prefer an auxiliary effect,
3353 // otherwise no preference.
3354 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3355 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3356 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3357 if (lStatus < 0) {
3358 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3359 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360 }
3361
3362 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003363 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003364 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3365 lStatus = INVALID_OPERATION;
3366 goto Exit;
3367 }
3368
Eric Laurent59255e42011-07-27 19:49:51 -07003369 // check recording permission for visualizer
3370 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003371 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003372 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003373 lStatus = PERMISSION_DENIED;
3374 goto Exit;
3375 }
3376
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003378 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003379 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003380 // if the output returned by getOutputForEffect() is removed before we lock the
3381 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3382 // and we will exit safely
3383 io = AudioSystem::getOutputForEffect(&desc);
3384 ALOGV("createEffect got output %d", io);
3385 }
3386
3387 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388
3389 // If output is not specified try to find a matching audio session ID in one of the
3390 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003391 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3392 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003393 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3394 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003395 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003396 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003397 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3398 if (io == AUDIO_IO_HANDLE_NONE) {
3399 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003401 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003402 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003403 }
Andy Hung444bb552019-03-14 17:06:39 -07003404
3405 // If you wish to create a Record preprocessing AudioEffect in Java,
3406 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3407 // Otherwise it will fail when created on a Playback thread by legacy
3408 // handling below. Ditto with Mmap, the associated Mmap track must be created
3409 // before creating the AudioEffect or the io handle must be specified.
3410 //
3411 // Detect if the effect is created after an AudioRecord is destroyed.
3412 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3413 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3414 " for session %d no longer exists",
3415 __func__, desc.name, sessionId);
3416 lStatus = PERMISSION_DENIED;
3417 goto Exit;
3418 }
3419
3420 // Legacy handling of creating an effect on an expired or made-up
3421 // session id. We think that it is a Playback effect.
3422 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003423 // If no output thread contains the requested session ID, default to
3424 // first output. The effect chain will be moved to the correct output
3425 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003426 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003427 io = mPlaybackThreads.keyAt(0);
3428 }
Steve Block3856b092011-10-20 11:56:00 +01003429 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003430 } else if (checkPlaybackThread_l(io) != nullptr) {
3431 // allow only one effect chain per sessionId on mPlaybackThreads.
3432 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3433 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3434 if (io == checkIo) continue;
3435 const uint32_t sessionType =
3436 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3437 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3438 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3439 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3440 android_errorWriteLog(0x534e4554, "123237974");
3441 lStatus = BAD_VALUE;
3442 goto Exit;
3443 }
3444 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003445 }
3446 ThreadBase *thread = checkRecordThread_l(io);
3447 if (thread == NULL) {
3448 thread = checkPlaybackThread_l(io);
3449 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003450 thread = checkMmapThread_l(io);
3451 if (thread == NULL) {
3452 ALOGE("createEffect() unknown output thread");
3453 lStatus = BAD_VALUE;
3454 goto Exit;
3455 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003456 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003457 } else {
3458 // Check if one effect chain was awaiting for an effect to be created on this
3459 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003460 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003461 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003462 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003463 thread->addEffectChain_l(chain);
3464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003465 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003466
Eric Laurent021cf962014-05-13 10:18:14 -07003467 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003469 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003470 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003471 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003472 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003473 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003474 // remove local strong reference to Client with mClientLock held
3475 Mutex::Autolock _cl(mClientLock);
3476 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003477 } else {
3478 // handle must be valid here, but check again to be safe.
3479 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481 }
3482
Eric Laurent6c796322019-04-09 14:13:17 -07003483 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3484 // Check CPU and memory usage
3485 sp<EffectModule> effect = handle->effect().promote();
3486 if (effect != nullptr) {
3487 status_t rStatus = effect->updatePolicyState();
3488 if (rStatus != NO_ERROR) {
3489 lStatus = rStatus;
3490 }
3491 }
3492 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003493 handle.clear();
3494 }
3495
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003497 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 return handle;
3499}
3500
Glenn Kastend848eb42016-03-08 13:42:11 -08003501status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003502 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003503{
Steve Block3856b092011-10-20 11:56:00 +01003504 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003505 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003506 Mutex::Autolock _l(mLock);
3507 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003508 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003509 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510 }
Eric Laurentde070132010-07-13 04:45:46 -07003511 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3512 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003513 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003514 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 }
Eric Laurentde070132010-07-13 04:45:46 -07003516 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3517 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003518 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003519 return BAD_VALUE;
3520 }
3521
3522 Mutex::Autolock _dl(dstThread->mLock);
3523 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003524 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525}
3526
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003527
3528void AudioFlinger::setEffectSuspended(int effectId,
3529 audio_session_t sessionId,
3530 bool suspended)
3531{
3532 Mutex::Autolock _l(mLock);
3533
3534 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3535 if (thread == nullptr) {
3536 return;
3537 }
3538 Mutex::Autolock _sl(thread->mLock);
3539 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3540 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3541}
3542
3543
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003544// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003545status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003546 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003547 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003548{
Steve Block3856b092011-10-20 11:56:00 +01003549 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003550 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003551
Eric Laurent59255e42011-07-27 19:49:51 -07003552 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003553 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003554 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003555 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003556 return INVALID_OPERATION;
3557 }
3558
Eric Laurent4c415062016-06-17 16:14:16 -07003559 // Check whether the destination thread and all effects in the chain are compatible
3560 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003561 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003562 " destination thread %p is not compatible with effects in the chain",
3563 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003564 return INVALID_OPERATION;
3565 }
3566
Eric Laurent39e94f82010-07-28 01:32:47 -07003567 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003568 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003569 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003570 // removed.
3571 srcThread->removeEffectChain_l(chain);
3572
3573 // transfer all effects one by one so that new effect chain is created on new thread with
3574 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003575 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003576 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003577 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003578 Vector< sp<EffectModule> > removed;
3579 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003580 while (effect != 0) {
3581 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003582 removed.add(effect);
3583 status = dstThread->addEffect_l(effect);
3584 if (status != NO_ERROR) {
3585 break;
3586 }
Eric Laurentec35a142011-10-05 17:42:25 -07003587 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3588 if (effect->state() == EffectModule::ACTIVE ||
3589 effect->state() == EffectModule::STOPPING) {
3590 effect->start();
3591 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003592 // if the move request is not received from audio policy manager, the effect must be
3593 // re-registered with the new strategy and output
3594 if (dstChain == 0) {
3595 dstChain = effect->chain().promote();
3596 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003597 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003598 status = NO_INIT;
3599 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003600 }
3601 strategy = dstChain->strategy();
3602 }
Eric Laurentde070132010-07-13 04:45:46 -07003603 effect = chain->getEffectFromId_l(0);
3604 }
3605
Eric Laurent5baf2af2013-09-12 17:37:00 -07003606 if (status != NO_ERROR) {
3607 for (size_t i = 0; i < removed.size(); i++) {
3608 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003609 }
3610 }
3611
3612 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613}
3614
Eric Laurent6c796322019-04-09 14:13:17 -07003615status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3616 const sp<PlaybackThread>& dstThread,
3617 sp<PlaybackThread> *srcThread)
3618{
3619 status_t status = NO_ERROR;
3620 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003621 sp<PlaybackThread> thread =
3622 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003623
3624 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3625 Mutex::Autolock _dl(dstThread->mLock);
3626 Mutex::Autolock _sl(thread->mLock);
3627 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3628 sp<EffectChain> dstChain;
3629 if (srcChain == 0) {
3630 return INVALID_OPERATION;
3631 }
3632
3633 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3634 if (effect == 0) {
3635 return INVALID_OPERATION;
3636 }
3637 thread->removeEffect_l(effect);
3638 status = dstThread->addEffect_l(effect);
3639 if (status != NO_ERROR) {
3640 thread->addEffect_l(effect);
3641 status = INVALID_OPERATION;
3642 goto Exit;
3643 }
3644
3645 dstChain = effect->chain().promote();
3646 if (dstChain == 0) {
3647 thread->addEffect_l(effect);
3648 status = INVALID_OPERATION;
3649 }
3650
3651Exit:
3652 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3653 if (effect->state() == EffectModule::ACTIVE ||
3654 effect->state() == EffectModule::STOPPING) {
3655 effect->start();
3656 }
3657 }
3658
3659 if (status == NO_ERROR && srcThread != nullptr) {
3660 *srcThread = thread;
3661 }
3662 return status;
3663}
3664
Eric Laurent5baf2af2013-09-12 17:37:00 -07003665bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003666{
3667 if (mGlobalEffectEnableTime != 0 &&
3668 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3669 return true;
3670 }
3671
3672 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3673 sp<EffectChain> ec =
3674 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003675 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003676 return true;
3677 }
3678 }
3679 return false;
3680}
3681
Eric Laurent5baf2af2013-09-12 17:37:00 -07003682void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003683{
3684 Mutex::Autolock _l(mLock);
3685
3686 mGlobalEffectEnableTime = systemTime();
3687
3688 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3689 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3690 if (t->mType == ThreadBase::OFFLOAD) {
3691 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3692 }
3693 }
3694
3695}
3696
Eric Laurentaaa44472014-09-12 17:41:50 -07003697status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3698{
Eric Laurentd8365c52017-07-16 15:27:05 -07003699 // clear possible suspended state before parking the chain so that it starts in default state
3700 // when attached to a new record thread
3701 chain->setEffectSuspended_l(FX_IID_AEC, false);
3702 chain->setEffectSuspended_l(FX_IID_NS, false);
3703
Glenn Kastend848eb42016-03-08 13:42:11 -08003704 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003705 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003706 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003707 if (index >= 0) {
3708 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3709 return ALREADY_EXISTS;
3710 }
3711 mOrphanEffectChains.add(session, chain);
3712 return NO_ERROR;
3713}
3714
3715sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3716{
3717 sp<EffectChain> chain;
3718 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003719 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003720 if (index >= 0) {
3721 chain = mOrphanEffectChains.valueAt(index);
3722 mOrphanEffectChains.removeItemsAt(index);
3723 }
3724 return chain;
3725}
3726
3727bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3728{
3729 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003730 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003731 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003732 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003733 if (index >= 0) {
3734 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003735 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003736 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003737 mOrphanEffectChains.removeItemsAt(index);
3738 }
3739 return true;
3740 }
3741 return false;
3742}
3743
3744
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745// ----------------------------------------------------------------------------
3746
3747status_t AudioFlinger::onTransact(
3748 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3749{
3750 return BnAudioFlinger::onTransact(code, data, reply, flags);
3751}
3752
Glenn Kasten63238ef2015-03-02 15:50:29 -08003753} // namespace android