blob: 19499e21c793ce862ba58d7075b0796fa3affa7d [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
jiabin8cb192f2019-09-23 10:34:20 -070022// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23#define AUDIO_ARRAYS_STATIC_CHECK 1
24
Glenn Kasten153b9fe2013-07-15 11:23:36 -070025#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080026#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <math.h>
28#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/time.h>
31#include <sys/resource.h>
32
jiabin57303cc2018-12-18 15:45:57 -080033#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080034#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/IServiceManager.h>
36#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070037#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070039#include <media/audiohal/DeviceHalInterface.h>
40#include <media/audiohal/DevicesFactoryHalInterface.h>
41#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070042#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070043#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070044#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/String16.h>
46#include <utils/threads.h>
47
Steven Morelandf0c02ce2018-02-23 14:53:55 -080048#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <cutils/properties.h>
50
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070052#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070055#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Andy Hung6770c6f2015-04-07 13:43:36 -070057#include <media/AudioResamplerPublic.h>
58
Mikhail Naganov9fe94012016-10-14 14:57:40 -070059#include <system/audio_effects/effect_visualizer.h>
60#include <system/audio_effects/effect_ns.h>
61#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten9e58b552013-01-18 15:09:48 -080067#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070068#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069#include <media/nbaio/Pipe.h>
70#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080071#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070072#include <mediautils/ServiceUtilities.h>
Eric Laurentb680e952019-09-27 15:40:33 -070073#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070074#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080075
rago3bd1c872016-09-26 12:58:14 -070076//#define BUFLOG_NDEBUG 0
77#include <BufLog.h>
78
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080079#include "TypedLogger.h"
80
Mathias Agopian65ab4712010-07-14 17:59:35 -070081// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070082
John Grossman1c345192012-03-27 14:00:17 -070083// Note: the following macro is used for extremely verbose logging message. In
84// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
85// 0; but one side effect of this is to turn all LOGV's as well. Some messages
86// are so verbose that we want to suppress them even when we have ALOG_ASSERT
87// turned on. Do not uncomment the #def below unless you really know what you
88// are doing and want to see all of the extremely verbose messages.
89//#define VERY_VERY_VERBOSE_LOGGING
90#ifdef VERY_VERY_VERBOSE_LOGGING
91#define ALOGVV ALOGV
92#else
93#define ALOGVV(a...) do { } while(0)
94#endif
Eric Laurentde070132010-07-13 04:45:46 -070095
Mathias Agopian65ab4712010-07-14 17:59:35 -070096namespace android {
97
Glenn Kastenec1d6b52011-12-12 09:04:45 -080098static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
99static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700100static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700101static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
Glenn Kasten58912562012-04-03 10:45:00 -0700103
John Grossman4ff14ba2012-02-08 16:37:41 -0800104nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800105
Eric Laurent81784c32012-11-19 14:55:58 -0800106uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700107
Eric Laurent813e2a72013-08-31 12:59:48 -0700108// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
109// we define a minimum time during which a global effect is considered enabled.
110static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
111
Eric Laurentfc235202016-12-20 18:48:17 -0800112Mutex gLock;
113wp<AudioFlinger> gAudioFlinger;
114
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700115// Keep a strong reference to media.log service around forever.
116// The service is within our parent process so it can never die in a way that we could observe.
117// These two variables are const after initialization.
118static sp<IBinder> sMediaLogServiceAsBinder;
119static sp<IMediaLogService> sMediaLogService;
120
121static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
122
123static void sMediaLogInit()
124{
125 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
126 if (sMediaLogServiceAsBinder != 0) {
127 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
128 }
129}
130
jiabin57303cc2018-12-18 15:45:57 -0800131// Keep a strong reference to external vibrator service
132static sp<os::IExternalVibratorService> sExternalVibratorService;
133
134static sp<os::IExternalVibratorService> getExternalVibratorService() {
135 if (sExternalVibratorService == 0) {
136 sp <IBinder> binder = defaultServiceManager()->getService(
137 String16("external_vibrator_service"));
138 if (binder != 0) {
139 sExternalVibratorService =
140 interface_cast<os::IExternalVibratorService>(binder);
141 }
142 }
143 return sExternalVibratorService;
144}
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700148std::string formatToString(audio_format_t format) {
149 std::string result;
150 FormatConverter::toString(format, result);
151 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800152}
153
Mathias Agopian65ab4712010-07-14 17:59:35 -0700154// ----------------------------------------------------------------------------
155
156AudioFlinger::AudioFlinger()
157 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800158 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800159 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800160 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700161 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800162 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800163 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700164 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800165 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700166 mBtNrecIsOff(false),
167 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700168 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800169 mTotalMemory(0),
170 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700171 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700172 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700173 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700174{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700175 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
176 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
177 // zero ID has a special meaning, so unavailable
178 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
179 }
180
Glenn Kastenae0cff12016-02-24 13:57:49 -0800181 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800182 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800183 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
184 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700185 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800186 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700187
Wei Jia3f273d12015-11-24 09:06:49 -0800188 // reset battery stats.
189 // if the audio service has crashed, battery stats could be left
190 // in bad state, reset the state upon service start.
191 BatteryNotifier::getInstance().noteResetAudio();
192
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700193 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700194 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
195
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800196 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurentb680e952019-09-27 15:40:33 -0700197 std::vector<pid_t> halPids;
198 mDevicesFactoryHal->getHalPids(&halPids);
199 TimeCheck::setAudioHalPids(halPids);
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700200}
201
202void AudioFlinger::onFirstRef()
203{
Eric Laurent93575202011-01-18 18:39:02 -0800204 Mutex::Autolock _l(mLock);
205
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800207 char val_str[PROPERTY_VALUE_MAX] = { 0 };
208 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
209 uint32_t int_val;
210 if (1 == sscanf(val_str, "%u", &int_val)) {
211 mStandbyTimeInNsecs = milliseconds(int_val);
212 ALOGI("Using %u mSec as standby time.", int_val);
213 } else {
214 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
215 ALOGI("Using default %u mSec as standby time.",
216 (uint32_t)(mStandbyTimeInNsecs / 1000000));
217 }
218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219
Eric Laurenta4c5a552012-03-29 10:12:40 -0700220 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800221
222 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223}
224
Eric Laurentb680e952019-09-27 15:40:33 -0700225status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
226 TimeCheck::setAudioHalPids(pids);
227 return NO_ERROR;
228}
229
Mathias Agopian65ab4712010-07-14 17:59:35 -0700230AudioFlinger::~AudioFlinger()
231{
232 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700233 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700234 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 }
236 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700237 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700238 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239 }
Andy Hungb4946b62019-03-14 11:19:28 -0700240 while (!mMmapThreads.isEmpty()) {
241 const audio_io_handle_t io = mMmapThreads.keyAt(0);
242 if (mMmapThreads.valueAt(0)->isOutput()) {
243 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
244 } else {
245 closeInput_nonvirtual(io); // removes entry from mMmapThreads
246 }
247 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700248
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800249 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
250 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700251 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700252 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700253
254 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700255 if (sMediaLogService != 0) {
256 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
257 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
258 mUnregisteredWriters.pop();
259 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700260 }
261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262}
263
Eric Laurentfc235202016-12-20 18:48:17 -0800264//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800265__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800266status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
267 const audio_attributes_t *attr,
268 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700269 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800270 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800271 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800272 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700273 sp<MmapStreamInterface>& interface,
274 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800275{
276 sp<AudioFlinger> af;
277 {
278 Mutex::Autolock _l(gLock);
279 af = gAudioFlinger.promote();
280 }
281 status_t ret = NO_INIT;
282 if (af != 0) {
283 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800284 direction, attr, config, client, deviceId,
285 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800286 }
287 return ret;
288}
289
Eric Laurent6acd1d42017-01-04 14:23:29 -0800290status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
291 const audio_attributes_t *attr,
292 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700293 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800294 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800295 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800296 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700297 sp<MmapStreamInterface>& interface,
298 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800299{
300 status_t ret = initCheck();
301 if (ret != NO_ERROR) {
302 return ret;
303 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800304 audio_session_t actualSessionId = *sessionId;
305 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
306 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
307 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800308 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700309 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800310 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700311 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800312 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
313 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
314 fullConfig.sample_rate = config->sample_rate;
315 fullConfig.channel_mask = config->channel_mask;
316 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800317 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700318
319 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800320 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200321 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800322 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800323 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
324 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800325 deviceId, &portId, &secondaryOutputs);
326 ALOGW_IF(!secondaryOutputs.empty(),
327 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800328 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700329 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700330 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800331 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800332 client.clientPid,
333 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800334 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800335 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700336 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800337 }
338 if (ret != NO_ERROR) {
339 return ret;
340 }
341
342 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
343 // audio policy manager and we can retrieve it
344 sp<MmapThread> thread = mMmapThreads.valueFor(io);
345 if (thread != 0) {
346 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700347 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700348 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800349 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800350 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700351 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700352 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700353 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800354 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700355 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800356 ret = NO_INIT;
357 }
358
359 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
360
Eric Laurentfc235202016-12-20 18:48:17 -0800361 return ret;
362}
363
jiabin57303cc2018-12-18 15:45:57 -0800364/* static */
365int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
366 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
367 if (evs != 0) {
368 int32_t ret;
369 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
370 if (status.isOk()) {
371 return ret;
372 }
373 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800374 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800375}
376
377/* static */
378void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
379 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
380 if (evs != 0) {
381 evs->onExternalVibrationStop(*externalVibration);
382 }
383}
384
Eric Laurenta4c5a552012-03-29 10:12:40 -0700385static const char * const audio_interfaces[] = {
386 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
387 AUDIO_HARDWARE_MODULE_ID_A2DP,
388 AUDIO_HARDWARE_MODULE_ID_USB,
389};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700390
Phil Burk062e67a2015-02-11 13:40:50 -0800391AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700392 audio_module_handle_t module,
jiabinc0106832019-10-24 14:58:31 -0700393 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700394{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700395 // if module is 0, the request comes from an old policy manager and we should load
396 // well known modules
397 if (module == 0) {
398 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700399 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700400 loadHwModule_l(audio_interfaces[i]);
401 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700402 // then try to find a module supporting the requested device.
403 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
404 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700405 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
406 uint32_t supportedDevices;
407 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabinc0106832019-10-24 14:58:31 -0700408 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700409 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700410 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700411 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700412 } else {
413 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700414 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
415 if (audioHwDevice != NULL) {
416 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700417 }
418 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700419
Dima Zavin799a70e2011-04-18 16:57:27 -0700420 return NULL;
421}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422
Glenn Kasten0f11b512014-01-31 16:18:54 -0800423void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
428
429 result.append("Clients:\n");
430 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800431 sp<Client> client = mClients.valueAt(i).promote();
432 if (client != 0) {
433 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
434 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 }
436 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700437
Eric Laurentd1b28d42013-09-18 18:47:13 -0700438 result.append("Notification Clients:\n");
439 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
440 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
441 result.append(buffer);
442 }
443
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700444 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800445 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700446 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
447 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800448 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700449 result.append(buffer);
450 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452}
453
454
Glenn Kasten0f11b512014-01-31 16:18:54 -0800455void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700456{
457 const size_t SIZE = 256;
458 char buffer[SIZE];
459 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800460 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461
John Grossman4ff14ba2012-02-08 16:37:41 -0800462 snprintf(buffer, SIZE, "Hardware status: %d\n"
463 "Standby Time mSec: %u\n",
464 hardwareStatus,
465 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 result.append(buffer);
467 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468}
469
Glenn Kasten0f11b512014-01-31 16:18:54 -0800470void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471{
472 const size_t SIZE = 256;
473 char buffer[SIZE];
474 String8 result;
475 snprintf(buffer, SIZE, "Permission Denial: "
476 "can't dump AudioFlinger from pid=%d, uid=%d\n",
477 IPCThreadState::self()->getCallingPid(),
478 IPCThreadState::self()->getCallingUid());
479 result.append(buffer);
480 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481}
482
Eric Laurent81784c32012-11-19 14:55:58 -0800483bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700485 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
486 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487}
488
489status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
490{
Glenn Kasten44deb052012-02-05 18:09:08 -0800491 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492 dumpPermissionDenial(fd, args);
493 } else {
494 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800495 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 if (!hardwareLocked) {
497 String8 result(kHardwareLockedString);
498 write(fd, result.string(), result.size());
499 } else {
500 mHardwareLock.unlock();
501 }
502
Eric Tan7b651152018-07-13 10:17:19 -0700503 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504
505 // failed to lock - AudioFlinger is probably deadlocked
506 if (!locked) {
507 String8 result(kDeadlockedString);
508 write(fd, result.string(), result.size());
509 }
510
Eric Laurent021cf962014-05-13 10:18:14 -0700511 bool clientLocked = dumpTryLock(mClientLock);
512 if (!clientLocked) {
513 String8 result(kClientLockedString);
514 write(fd, result.string(), result.size());
515 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700516
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700517 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700518 mEffectsFactoryHal->dumpEffects(fd);
519 } else {
520 String8 result(kNoEffectsFactory);
521 write(fd, result.string(), result.size());
522 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700523
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700525 if (clientLocked) {
526 mClientLock.unlock();
527 }
528
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 dumpInternals(fd, args);
530
531 // dump playback threads
532 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
533 mPlaybackThreads.valueAt(i)->dump(fd, args);
534 }
535
536 // dump record threads
537 for (size_t i = 0; i < mRecordThreads.size(); i++) {
538 mRecordThreads.valueAt(i)->dump(fd, args);
539 }
540
Eric Laurent6acd1d42017-01-04 14:23:29 -0800541 // dump mmap threads
542 for (size_t i = 0; i < mMmapThreads.size(); i++) {
543 mMmapThreads.valueAt(i)->dump(fd, args);
544 }
545
Eric Laurentaaa44472014-09-12 17:41:50 -0700546 // dump orphan effect chains
547 if (mOrphanEffectChains.size() != 0) {
548 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
549 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
550 mOrphanEffectChains.valueAt(i)->dump(fd, args);
551 }
552 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700553 // dump all hardware devs
554 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700555 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
556 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700558
Mikhail Naganov201369b2018-05-16 16:52:32 -0700559 mPatchPanel.dump(fd);
560
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700561 // dump external setParameters
562 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
563 dprintf(fd, "\n%s setParameters:\n", name);
564 logger.dump(fd, " " /* prefix */);
565 };
566 dumpLogger(mRejectedSetParameterLog, "Rejected");
567 dumpLogger(mAppSetParameterLog, "App");
568 dumpLogger(mSystemSetParameterLog, "System");
569
Andy Hunga8115dc2018-08-24 15:51:59 -0700570 // dump historical threads in the last 10 seconds
571 const std::string threadLog = mThreadLog.dumpToString(
572 "Historical Thread Log ", 0 /* lines */,
573 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
574 write(fd, threadLog.c_str(), threadLog.size());
575
rago3bd1c872016-09-26 12:58:14 -0700576 BUFLOG_RESET;
577
Glenn Kastend65d73c2012-06-22 17:21:07 -0700578 if (locked) {
579 mLock.unlock();
580 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800581
Andy Hung8946a282018-04-19 20:04:56 -0700582#ifdef TEE_SINK
583 // NBAIO_Tee dump is safe to call outside of AF lock.
584 NBAIO_Tee::dumpAll(fd, "_DUMP");
585#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800586 // append a copy of media.log here by forwarding fd to it, but don't attempt
587 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700588 if (sMediaLogServiceAsBinder != 0) {
589 dprintf(fd, "\nmedia.log:\n");
590 Vector<String16> args;
591 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800592 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700593
594 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700595 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700596 bool unreachableMemory = false;
597 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700598 if (arg == String16("-m")) {
599 dumpMem = true;
600 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700601 unreachableMemory = true;
602 }
603 }
604
Andy Hung07b745e2016-05-23 16:21:07 -0700605 if (dumpMem) {
606 dprintf(fd, "\nDumping memory:\n");
607 std::string s = dumpMemoryAddresses(100 /* limit */);
608 write(fd, s.c_str(), s.size());
609 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700610 if (unreachableMemory) {
611 dprintf(fd, "\nDumping unreachable memory:\n");
612 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700613 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700614 write(fd, s.c_str(), s.size());
615 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616 }
617 return NO_ERROR;
618}
619
Eric Laurent021cf962014-05-13 10:18:14 -0700620sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800621{
Eric Laurent021cf962014-05-13 10:18:14 -0700622 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800623 // If pid is already in the mClients wp<> map, then use that entry
624 // (for which promote() is always != 0), otherwise create a new entry and Client.
625 sp<Client> client = mClients.valueFor(pid).promote();
626 if (client == 0) {
627 client = new Client(this, pid);
628 mClients.add(pid, client);
629 }
630
631 return client;
632}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633
Glenn Kasten9e58b552013-01-18 15:09:48 -0800634sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
635{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700636 // If there is no memory allocated for logs, return a dummy writer that does nothing.
637 // Similarly if we can't contact the media.log service, also return a dummy writer.
638 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800639 return new NBLog::Writer();
640 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700641 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
642 // If allocation fails, consult the vector of previously unregistered writers
643 // and garbage-collect one or more them until an allocation succeeds
644 if (shared == 0) {
645 Mutex::Autolock _l(mUnregisteredWritersLock);
646 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
647 {
648 // Pick the oldest stale writer to garbage-collect
649 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
650 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700651 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700652 // Now the media.log remote reference to IMemory is gone. When our last local
653 // reference to IMemory also drops to zero at end of this block,
654 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
655 }
656 // Re-attempt the allocation
657 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
658 if (shared != 0) {
659 goto success;
660 }
661 }
662 // Even after garbage-collecting all old writers, there is still not enough memory,
663 // so return a dummy writer
664 return new NBLog::Writer();
665 }
666success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800667 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
668 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
669 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700670 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800671 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800672}
673
674void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
675{
Glenn Kasten685ef092013-02-04 08:15:34 -0800676 if (writer == 0) {
677 return;
678 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800679 sp<IMemory> iMemory(writer->getIMemory());
680 if (iMemory == 0) {
681 return;
682 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700683 // Rather than removing the writer immediately, append it to a queue of old writers to
684 // be garbage-collected later. This allows us to continue to view old logs for a while.
685 Mutex::Autolock _l(mUnregisteredWritersLock);
686 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800687}
688
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689// IAudioFlinger interface
690
Eric Laurent21da6472017-11-09 16:29:26 -0800691sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
692 CreateTrackOutput& output,
693 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694{
695 sp<PlaybackThread::Track> track;
696 sp<TrackHandle> trackHandle;
697 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800699 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800700 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800701 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702
Eric Laurent21da6472017-11-09 16:29:26 -0800703 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700704 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800705 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700706 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
707 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700708 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700709
Andy Hung4ef19fa2018-05-15 19:35:29 -0700710 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800711 ALOGW_IF(clientUid != callingUid,
712 "%s uid %d tried to pass itself off as %d",
713 __FUNCTION__, callingUid, clientUid);
714 clientUid = callingUid;
715 updatePid = true;
716 }
717 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700718 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800719 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800720 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700721 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800722 __func__, callingUid, callingPid, clientPid);
723 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700724 }
725
Eric Laurent21da6472017-11-09 16:29:26 -0800726 audio_session_t sessionId = input.sessionId;
727 if (sessionId == AUDIO_SESSION_ALLOCATE) {
728 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800729 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
730 lStatus = BAD_VALUE;
731 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800732 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800733
Eric Laurent21da6472017-11-09 16:29:26 -0800734 output.sessionId = sessionId;
735 output.outputId = AUDIO_IO_HANDLE_NONE;
736 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700737 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200738 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800739 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800740
741 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
742 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
743 goto Exit;
744 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800745 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
746 // but if someone uses binder directly they could bypass that and cause us to crash
747 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000748 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 lStatus = BAD_VALUE;
750 goto Exit;
751 }
752
Glenn Kasten53b5d092014-02-05 10:00:23 -0800753 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800754 if (!audio_is_output_channel(input.config.channel_mask)) {
755 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800756 lStatus = BAD_VALUE;
757 goto Exit;
758 }
759
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700760 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800761 if (!audio_is_valid_format(input.config.format)) {
762 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700763 lStatus = BAD_VALUE;
764 goto Exit;
765 }
766
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767 {
768 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800769 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800771 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772 lStatus = BAD_VALUE;
773 goto Exit;
774 }
775
Eric Laurent21da6472017-11-09 16:29:26 -0800776 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777
Glenn Kastene848bd92014-03-13 15:00:32 -0700778 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800779 // check if an effect chain with the same session ID is present on another
780 // output thread and move it here.
781 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
782 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
783 if (mPlaybackThreads.keyAt(i) != output.outputId) {
784 uint32_t sessions = t->hasAudioSession(sessionId);
785 if (sessions & ThreadBase::EFFECT_SESSION) {
786 effectThread = t.get();
787 break;
Eric Laurentde070132010-07-13 04:45:46 -0700788 }
789 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 }
Eric Laurent21da6472017-11-09 16:29:26 -0800791 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792
Eric Laurent21da6472017-11-09 16:29:26 -0800793 output.sampleRate = input.config.sample_rate;
794 output.frameCount = input.frameCount;
795 output.notificationFrameCount = input.notificationFrameCount;
796 output.flags = input.flags;
797
Eric Laurent42984412019-05-09 17:57:03 -0700798 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700799 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800800 &output.frameCount, &output.notificationFrameCount,
801 input.notificationsPerBuffer, input.speed,
802 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700803 callingPid, input.clientInfo.clientTid, clientUid,
804 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800805 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700806 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700807
Eric Laurent21da6472017-11-09 16:29:26 -0800808 output.afFrameCount = thread->frameCount();
809 output.afSampleRate = thread->sampleRate();
810 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800811 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800812
Kevin Rocard153f92d2018-12-18 18:33:28 -0800813 if (lStatus == NO_ERROR) {
814 // Connect secondary outputs. Failure on a secondary output must not imped the primary
815 // Any secondary output setup failure will lead to a desync between the AP and AF until
816 // the track is destroyed.
817 TeePatches teePatches;
818 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
819 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
820 if (secondaryThread == NULL) {
821 ALOGE("no playback thread found for secondary output %d", output.outputId);
822 continue;
823 }
824
Kevin Rocard20a44f82019-09-18 11:24:52 +0100825 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
826 / thread->sampleRate();
827 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
828 / secondaryThread->sampleRate();
829 // If the secondary output has just been opened, the first secondaryThread write
830 // will not block as it will fill the empty startup buffer of the HAL,
831 // so a second sink buffer needs to be ready for the immediate next blocking write.
832 // Additionally, have a margin of one main thread buffer as the scheduling jitter
833 // can reorder the writes (eg if thread A&B have the same write intervale,
834 // the scheduler could schedule AB...BA)
835 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
836 // Total secondary output buffer must be at least as the read frames plus
837 // the margin of a few buffers on both sides in case the
838 // threads scheduling has some jitter.
839 // That value should not impact latency as the secondary track is started before
840 // its buffer is full, see frameCountToBeReady.
841 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
842 // The frameCount should also not be smaller than the secondary thread min frame
843 // count
844 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
845 [&] { Mutex::Autolock _l(secondaryThread->mLock);
846 return secondaryThread->latency_l(); }(),
847 secondaryThread->mNormalFrameCount,
848 secondaryThread->mSampleRate,
849 output.sampleRate,
850 input.speed);
851 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800852
853 using namespace std::chrono_literals;
854 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
855 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
856 output.sampleRate,
857 inChannelMask,
858 input.config.format,
859 frameCount,
860 NULL /* buffer */,
861 (size_t)0 /* bufferSize */,
862 AUDIO_INPUT_FLAG_DIRECT,
863 0ns /* timeout */);
864 status_t status = patchRecord->initCheck();
865 if (status != NO_ERROR) {
866 ALOGE("Secondary output patchRecord init failed: %d", status);
867 continue;
868 }
Andy Hungae22b482019-05-09 15:38:55 -0700869
870 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
871 // for fast usage: thread has fast mixer, sample rate matches, etc.;
872 // for now, we exclude fast tracks by removing the Fast flag.
873 const audio_output_flags_t outputFlags =
874 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800875 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
876 streamType,
877 output.sampleRate,
878 input.config.channel_mask,
879 input.config.format,
880 frameCount,
881 patchRecord->buffer(),
882 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700883 outputFlags,
Kevin Rocard20a44f82019-09-18 11:24:52 +0100884 0ns /* timeout */,
885 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800886 status = patchTrack->initCheck();
887 if (status != NO_ERROR) {
888 ALOGE("Secondary output patchTrack init failed: %d", status);
889 continue;
890 }
891 teePatches.push_back({patchRecord, patchTrack});
892 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800893 // In case the downstream patchTrack on the secondaryThread temporarily outlives
894 // our created track, ensure the corresponding patchRecord is still alive.
895 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
896 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800897 }
898 track->setTeePatches(std::move(teePatches));
899 }
900
Eric Laurent39e94f82010-07-28 01:32:47 -0700901 // move effect chain to this output thread if an effect on same session was waiting
902 // for a track to be created
903 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700904 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700905 Mutex::Autolock _dl(thread->mLock);
906 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700907 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
908 effectThreadId = thread->id();
909 effectIds = thread->getEffectIds_l(sessionId);
910 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700911 }
Eric Laurenta011e352012-03-29 15:51:43 -0700912
913 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700914 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800915 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700916 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700917 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700918 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700919 } else {
920 mPendingSyncEvents[i]->cancel();
921 }
Eric Laurenta011e352012-03-29 15:51:43 -0700922 mPendingSyncEvents.removeAt(i);
923 i--;
924 }
925 }
926 }
Glenn Kastene198c362013-08-13 09:13:36 -0700927
Eric Laurent21da6472017-11-09 16:29:26 -0800928 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 }
Glenn Kastene198c362013-08-13 09:13:36 -0700930
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700931 if (lStatus != NO_ERROR) {
932 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700933 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700934 // Don't hold mClientLock when releasing the reference on the track as the
935 // destructor will acquire it.
936 {
937 Mutex::Autolock _cl(mClientLock);
938 client.clear();
939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700941 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 }
943
Eric Laurent6c796322019-04-09 14:13:17 -0700944 // effectThreadId is not NONE if an effect chain corresponding to the track session
945 // was found on another thread and must be moved on this thread
946 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
947 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
948 }
949
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700950 // return handle to client
951 trackHandle = new TrackHandle(track);
952
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800954 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700955 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800956 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700957 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958 return trackHandle;
959}
960
Glenn Kasten2c073da2016-02-26 09:14:08 -0800961uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962{
963 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800964 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800966 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 return 0;
968 }
969 return thread->sampleRate();
970}
971
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800972audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973{
974 Mutex::Autolock _l(mLock);
975 PlaybackThread *thread = checkPlaybackThread_l(output);
976 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000977 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800978 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 }
980 return thread->format();
981}
982
Glenn Kasten2c073da2016-02-26 09:14:08 -0800983size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984{
985 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800986 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800988 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 return 0;
990 }
Glenn Kasten58912562012-04-03 10:45:00 -0700991 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
992 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 return thread->frameCount();
994}
995
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700996size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
997{
998 Mutex::Autolock _l(mLock);
999 ThreadBase *thread = checkThread_l(ioHandle);
1000 if (thread == NULL) {
1001 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1002 return 0;
1003 }
1004 return thread->frameCountHAL();
1005}
1006
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001007uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008{
1009 Mutex::Autolock _l(mLock);
1010 PlaybackThread *thread = checkPlaybackThread_l(output);
1011 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001012 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 return 0;
1014 }
1015 return thread->latency();
1016}
1017
1018status_t AudioFlinger::setMasterVolume(float value)
1019{
Eric Laurenta1884f92011-08-23 08:25:03 -07001020 status_t ret = initCheck();
1021 if (ret != NO_ERROR) {
1022 return ret;
1023 }
1024
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 // check calling permissions
1026 if (!settingsAllowed()) {
1027 return PERMISSION_DENIED;
1028 }
1029
Eric Laurenta4c5a552012-03-29 10:12:40 -07001030 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001031 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001032
John Grossmanee578c02012-07-23 17:05:46 -07001033 // Set master volume in the HALs which support it.
1034 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1035 AutoMutex lock(mHardwareLock);
1036 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001037
John Grossmanee578c02012-07-23 17:05:46 -07001038 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1039 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001040 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -08001041 }
John Grossmanee578c02012-07-23 17:05:46 -07001042 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044
John Grossmanee578c02012-07-23 17:05:46 -07001045 // Now set the master volume in each playback thread. Playback threads
1046 // assigned to HALs which do not have master volume support will apply
1047 // master volume during the mix operation. Threads with HALs which do
1048 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001049 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1050 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1051 continue;
1052 }
John Grossmanee578c02012-07-23 17:05:46 -07001053 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001054 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055
1056 return NO_ERROR;
1057}
1058
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001059status_t AudioFlinger::setMasterBalance(float balance)
1060{
1061 status_t ret = initCheck();
1062 if (ret != NO_ERROR) {
1063 return ret;
1064 }
1065
1066 // check calling permissions
1067 if (!settingsAllowed()) {
1068 return PERMISSION_DENIED;
1069 }
1070
1071 // check range
1072 if (isnan(balance) || fabs(balance) > 1.f) {
1073 return BAD_VALUE;
1074 }
1075
1076 Mutex::Autolock _l(mLock);
1077
1078 // short cut.
1079 if (mMasterBalance == balance) return NO_ERROR;
1080
1081 mMasterBalance = balance;
1082
1083 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1084 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1085 continue;
1086 }
1087 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1088 }
1089
1090 return NO_ERROR;
1091}
1092
Glenn Kastenf78aee72012-01-04 11:00:47 -08001093status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094{
Eric Laurenta1884f92011-08-23 08:25:03 -07001095 status_t ret = initCheck();
1096 if (ret != NO_ERROR) {
1097 return ret;
1098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099
1100 // check calling permissions
1101 if (!settingsAllowed()) {
1102 return PERMISSION_DENIED;
1103 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001104 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001105 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 return BAD_VALUE;
1107 }
1108
1109 { // scope for the lock
1110 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001111 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001113 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 mHardwareStatus = AUDIO_HW_IDLE;
1115 }
1116
1117 if (NO_ERROR == ret) {
1118 Mutex::Autolock _l(mLock);
1119 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001120 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001121 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 }
1123
1124 return ret;
1125}
1126
1127status_t AudioFlinger::setMicMute(bool state)
1128{
Eric Laurenta1884f92011-08-23 08:25:03 -07001129 status_t ret = initCheck();
1130 if (ret != NO_ERROR) {
1131 return ret;
1132 }
1133
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134 // check calling permissions
1135 if (!settingsAllowed()) {
1136 return PERMISSION_DENIED;
1137 }
1138
1139 AutoMutex lock(mHardwareLock);
1140 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001141 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001142 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1143 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001144 if (result != NO_ERROR) {
1145 ret = result;
1146 }
1147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 mHardwareStatus = AUDIO_HW_IDLE;
1149 return ret;
1150}
1151
1152bool AudioFlinger::getMicMute() const
1153{
Eric Laurenta1884f92011-08-23 08:25:03 -07001154 status_t ret = initCheck();
1155 if (ret != NO_ERROR) {
1156 return false;
1157 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001158 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001159 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001160 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001162 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001163 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1164 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001165 if (result == NO_ERROR) {
1166 mute = mute && state;
1167 }
1168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001170
1171 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172}
1173
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001174void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1175{
1176 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1177
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001178 AutoMutex lock(mLock);
1179 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001180 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1181 }
1182 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1183 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001184 }
1185}
1186
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187status_t AudioFlinger::setMasterMute(bool muted)
1188{
John Grossmand8f178d2012-07-20 14:51:35 -07001189 status_t ret = initCheck();
1190 if (ret != NO_ERROR) {
1191 return ret;
1192 }
1193
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 // check calling permissions
1195 if (!settingsAllowed()) {
1196 return PERMISSION_DENIED;
1197 }
1198
John Grossmanee578c02012-07-23 17:05:46 -07001199 Mutex::Autolock _l(mLock);
1200 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001201
John Grossmanee578c02012-07-23 17:05:46 -07001202 // Set master mute in the HALs which support it.
1203 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1204 AutoMutex lock(mHardwareLock);
1205 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001206
John Grossmanee578c02012-07-23 17:05:46 -07001207 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1208 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001209 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001210 }
John Grossmanee578c02012-07-23 17:05:46 -07001211 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001212 }
1213
John Grossmanee578c02012-07-23 17:05:46 -07001214 // Now set the master mute in each playback thread. Playback threads
1215 // assigned to HALs which do not have master mute support will apply master
1216 // mute during the mix operation. Threads with HALs which do support master
1217 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001218 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1219 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1220 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001221 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222
1223 return NO_ERROR;
1224}
1225
1226float AudioFlinger::masterVolume() const
1227{
Glenn Kasten98067102011-12-13 11:47:54 -08001228 Mutex::Autolock _l(mLock);
1229 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230}
1231
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001232status_t AudioFlinger::getMasterBalance(float *balance) const
1233{
1234 Mutex::Autolock _l(mLock);
1235 *balance = getMasterBalance_l();
1236 return NO_ERROR; // if called through binder, may return a transactional error
1237}
1238
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239bool AudioFlinger::masterMute() const
1240{
Glenn Kasten98067102011-12-13 11:47:54 -08001241 Mutex::Autolock _l(mLock);
1242 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243}
1244
John Grossman4ff14ba2012-02-08 16:37:41 -08001245float AudioFlinger::masterVolume_l() const
1246{
John Grossman4ff14ba2012-02-08 16:37:41 -08001247 return mMasterVolume;
1248}
1249
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001250float AudioFlinger::getMasterBalance_l() const
1251{
1252 return mMasterBalance;
1253}
1254
John Grossmand8f178d2012-07-20 14:51:35 -07001255bool AudioFlinger::masterMute_l() const
1256{
John Grossmanee578c02012-07-23 17:05:46 -07001257 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001258}
1259
Eric Laurent223fd5c2014-11-11 13:43:36 -08001260status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1261{
1262 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001263 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001264 return BAD_VALUE;
1265 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001266 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1267 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1268 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001269 return PERMISSION_DENIED;
1270 }
1271
1272 return NO_ERROR;
1273}
1274
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001275status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1276 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277{
1278 // check calling permissions
1279 if (!settingsAllowed()) {
1280 return PERMISSION_DENIED;
1281 }
1282
Eric Laurent223fd5c2014-11-11 13:43:36 -08001283 status_t status = checkStreamType(stream);
1284 if (status != NO_ERROR) {
1285 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 }
Eric Laurent98e38192018-02-15 18:31:53 -08001287 if (output == AUDIO_IO_HANDLE_NONE) {
1288 return BAD_VALUE;
1289 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001290 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1291 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292
1293 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001294 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1295 if (volumeInterface == NULL) {
1296 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 }
Eric Laurent98e38192018-02-15 18:31:53 -08001298 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299
1300 return NO_ERROR;
1301}
1302
Glenn Kastenfff6d712012-01-12 16:38:12 -08001303status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304{
1305 // check calling permissions
1306 if (!settingsAllowed()) {
1307 return PERMISSION_DENIED;
1308 }
1309
Eric Laurent223fd5c2014-11-11 13:43:36 -08001310 status_t status = checkStreamType(stream);
1311 if (status != NO_ERROR) {
1312 return status;
1313 }
1314 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1315
1316 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001317 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318 return BAD_VALUE;
1319 }
1320
Eric Laurent93575202011-01-18 18:39:02 -08001321 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001323 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1324 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1325 volumeInterfaces[i]->setStreamMute(stream, muted);
1326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001327
1328 return NO_ERROR;
1329}
1330
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001331float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001332{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001333 status_t status = checkStreamType(stream);
1334 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001335 return 0.0f;
1336 }
Eric Laurent98e38192018-02-15 18:31:53 -08001337 if (output == AUDIO_IO_HANDLE_NONE) {
1338 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339 }
1340
Eric Laurent98e38192018-02-15 18:31:53 -08001341 AutoMutex lock(mLock);
1342 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1343 if (volumeInterface == NULL) {
1344 return 0.0f;
1345 }
1346
1347 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348}
1349
Glenn Kastenfff6d712012-01-12 16:38:12 -08001350bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001352 status_t status = checkStreamType(stream);
1353 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354 return true;
1355 }
1356
Glenn Kasten6637baa2012-01-09 09:40:36 -08001357 AutoMutex lock(mLock);
1358 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359}
1360
Eric Laurent054d9d32015-04-24 08:48:48 -07001361
1362void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1363{
1364 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1365 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1366 }
1367}
1368
jiabin10d86fd2019-10-31 17:20:42 -07001369void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1370{
1371 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1372 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1373 }
1374}
1375
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001376// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1377void AudioFlinger::forwardParametersToDownstreamPatches_l(
1378 audio_io_handle_t upStream, const String8& keyValuePairs,
1379 std::function<bool(const sp<PlaybackThread>&)> useThread)
1380{
1381 std::vector<PatchPanel::SoftwarePatch> swPatches;
1382 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1383 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1384 __func__, swPatches.size(), upStream);
1385 for (const auto& swPatch : swPatches) {
1386 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1387 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1388 downStream->setParameters(keyValuePairs);
1389 }
1390 }
1391}
1392
Eric Laurentf1047e82018-04-16 19:18:20 -07001393// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1394// Some keys are used for audio routing and audio path configuration and should be reserved for use
1395// by audio policy and audio flinger for functional, privacy and security reasons.
1396void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1397{
1398 static const String8 kReservedParameters[] = {
1399 String8(AudioParameter::keyRouting),
1400 String8(AudioParameter::keySamplingRate),
1401 String8(AudioParameter::keyFormat),
1402 String8(AudioParameter::keyChannels),
1403 String8(AudioParameter::keyFrameCount),
1404 String8(AudioParameter::keyInputSource),
1405 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovbb3b1602019-07-08 15:28:43 -07001406 String8(AudioParameter::keyDeviceConnect),
1407 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001408 String8(AudioParameter::keyStreamSupportedFormats),
1409 String8(AudioParameter::keyStreamSupportedChannels),
1410 String8(AudioParameter::keyStreamSupportedSamplingRates),
1411 };
1412
Andy Hung4ef19fa2018-05-15 19:35:29 -07001413 if (isAudioServerUid(callingUid)) {
1414 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001415 }
1416
1417 AudioParameter param = AudioParameter(keyValuePairs);
1418 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001419 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001420 for (auto& key : kReservedParameters) {
1421 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001422 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001423 param.remove(key);
1424 }
1425 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001426 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1427 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001428 keyValuePairs = param.toString();
1429}
1430
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001431void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1432 size_t rejectedKVPSize, const String8& rejectedKVPs,
1433 uid_t callingUid) {
1434 auto prefix = String8::format("UID %5d", callingUid);
1435 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1436 if (rejectedKVPSize != 0) {
1437 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1438 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1439 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1440 } else {
1441 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1442 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1443 }
1444}
1445
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001446status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447{
Eric Laurentf1047e82018-04-16 19:18:20 -07001448 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1449 ioHandle, keyValuePairs.string(),
1450 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001451
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452 // check calling permissions
1453 if (!settingsAllowed()) {
1454 return PERMISSION_DENIED;
1455 }
1456
Eric Laurentf1047e82018-04-16 19:18:20 -07001457 String8 filteredKeyValuePairs = keyValuePairs;
1458 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1459
1460 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1461
Glenn Kasten142f5192014-03-25 17:44:59 -07001462 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1463 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001464 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001465 // result will remain NO_INIT if no audio device is present
1466 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001467 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001468 AutoMutex lock(mHardwareLock);
1469 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1470 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001471 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001472 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001473 // return success if at least one audio device accepts the parameters as not all
1474 // HALs are requested to support all parameters. If no audio device supports the
1475 // requested parameters, the last error is reported.
1476 if (final_result != NO_ERROR) {
1477 final_result = result;
1478 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001479 }
1480 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001481 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001482 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001483 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001484 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001485 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1486 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001487 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001488 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001489 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001490 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001491 }
1492 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001493 String8 screenState;
1494 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001495 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001496 if (isOff != (AudioFlinger::mScreenState & 1)) {
1497 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001498 }
1499 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001500 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 }
1502
1503 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1504 // and the thread is exited once the lock is released
1505 sp<ThreadBase> thread;
1506 {
1507 Mutex::Autolock _l(mLock);
1508 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001509 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001511 if (thread == 0) {
1512 thread = checkMmapThread_l(ioHandle);
1513 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001514 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001515 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001516 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001517 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001518 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1519 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001520 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 }
1523 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001524 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001525 status_t result = thread->setParameters(filteredKeyValuePairs);
1526 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1527 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528 }
1529 return BAD_VALUE;
1530}
1531
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001532String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001534 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1535 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536
Eric Laurenta4c5a552012-03-29 10:12:40 -07001537 Mutex::Autolock _l(mLock);
1538
Glenn Kasten142f5192014-03-25 17:44:59 -07001539 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001540 String8 out_s8;
1541
Dima Zavin799a70e2011-04-18 16:57:27 -07001542 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001543 String8 s;
1544 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001545 {
1546 AutoMutex lock(mHardwareLock);
1547 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001548 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1549 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001550 mHardwareStatus = AUDIO_HW_IDLE;
1551 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001552 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001553 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001554 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 }
1556
Eric Laurent6acd1d42017-01-04 14:23:29 -08001557 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1558 if (thread == NULL) {
1559 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1560 if (thread == NULL) {
1561 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1562 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001563 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001564 }
1565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001567 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568}
1569
Glenn Kastendd8104c2012-07-02 12:42:44 -07001570size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1571 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572{
Eric Laurenta1884f92011-08-23 08:25:03 -07001573 status_t ret = initCheck();
1574 if (ret != NO_ERROR) {
1575 return 0;
1576 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001577 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001578 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001579 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001580 return 0;
1581 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001582
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001583 AutoMutex lock(mHardwareLock);
1584 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001585 audio_config_t config, proposed;
1586 memset(&proposed, 0, sizeof(proposed));
1587 proposed.sample_rate = sampleRate;
1588 proposed.channel_mask = channelMask;
1589 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001590
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001591 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Tao Wu1eb82df2019-11-05 10:20:18 -08001592 size_t frames = 0;
Andy Hung6770c6f2015-04-07 13:43:36 -07001593 for (;;) {
1594 // Note: config is currently a const parameter for get_input_buffer_size()
1595 // but we use a copy from proposed in case config changes from the call.
1596 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001597 status_t result = dev->getInputBufferSize(&config, &frames);
1598 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001599 break; // hal success, config is the result
1600 }
1601 // change one parameter of the configuration each iteration to a more "common" value
1602 // to see if the device will support it.
1603 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1604 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1605 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1606 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1607 } else {
1608 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1609 "format %#x, channelMask 0x%X",
1610 sampleRate, format, channelMask);
1611 break; // retries failed, break out of loop with frames == 0.
1612 }
1613 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001614 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001615 if (frames > 0 && config.sample_rate != sampleRate) {
1616 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1617 }
1618 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619}
1620
Glenn Kasten5f972c02014-01-13 09:59:31 -08001621uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 Mutex::Autolock _l(mLock);
1624
1625 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1626 if (recordThread != NULL) {
1627 return recordThread->getInputFramesLost();
1628 }
1629 return 0;
1630}
1631
1632status_t AudioFlinger::setVoiceVolume(float value)
1633{
Eric Laurenta1884f92011-08-23 08:25:03 -07001634 status_t ret = initCheck();
1635 if (ret != NO_ERROR) {
1636 return ret;
1637 }
1638
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 // check calling permissions
1640 if (!settingsAllowed()) {
1641 return PERMISSION_DENIED;
1642 }
1643
1644 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001645 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001646 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001647 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 mHardwareStatus = AUDIO_HW_IDLE;
1649
1650 return ret;
1651}
1652
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001653status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001654 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 Mutex::Autolock _l(mLock);
1657
1658 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1659 if (playbackThread != NULL) {
1660 return playbackThread->getRenderPosition(halFrames, dspFrames);
1661 }
1662
1663 return BAD_VALUE;
1664}
1665
1666void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1667{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001669 if (client == 0) {
1670 return;
1671 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001672 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001673 {
1674 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001675 if (mNotificationClients.indexOfKey(pid) < 0) {
1676 sp<NotificationClient> notificationClient = new NotificationClient(this,
1677 client,
1678 pid);
1679 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680
Eric Laurent021cf962014-05-13 10:18:14 -07001681 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682
Marco Nelissen06b46062014-11-14 07:58:25 -08001683 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001684 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001685 }
1686 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687
Eric Laurent021cf962014-05-13 10:18:14 -07001688 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001689 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001690 // the config change is always sent from playback or record threads to avoid deadlock
1691 // with AudioSystem::gLock
1692 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001693 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001694 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001696 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001697 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 }
1699}
1700
1701void AudioFlinger::removeNotificationClient(pid_t pid)
1702{
Eric Laurent6c796322019-04-09 14:13:17 -07001703 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001704 {
Eric Laurent6c796322019-04-09 14:13:17 -07001705 Mutex::Autolock _l(mLock);
1706 {
1707 Mutex::Autolock _cl(mClientLock);
1708 mNotificationClients.removeItem(pid);
1709 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001710
Eric Laurent6c796322019-04-09 14:13:17 -07001711 ALOGV("%d died, releasing its sessions", pid);
1712 size_t num = mAudioSessionRefs.size();
1713 bool removed = false;
1714 for (size_t i = 0; i < num; ) {
1715 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1716 ALOGV(" pid %d @ %zu", ref->mPid, i);
1717 if (ref->mPid == pid) {
1718 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1719 mAudioSessionRefs.removeAt(i);
1720 delete ref;
1721 removed = true;
1722 num--;
1723 } else {
1724 i++;
1725 }
1726 }
1727 if (removed) {
1728 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001729 }
1730 }
Eric Laurent6c796322019-04-09 14:13:17 -07001731 for (auto& effect : removedEffects) {
1732 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001733 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734}
1735
Eric Laurent73e26b62015-04-27 16:55:58 -07001736void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001737 const sp<AudioIoDescriptor>& ioDesc,
1738 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739{
Eric Laurent021cf962014-05-13 10:18:14 -07001740 Mutex::Autolock _l(mClientLock);
1741 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001743 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1744 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1745 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746 }
1747}
1748
Eric Laurent021cf962014-05-13 10:18:14 -07001749// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750void AudioFlinger::removeClient_l(pid_t pid)
1751{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001752 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001753 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 mClients.removeItem(pid);
1755}
1756
Eric Laurent717e1282012-06-29 16:36:52 -07001757// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001758sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1759 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001760{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001761 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001762
1763 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001764 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001765 ALOG_ASSERT(thread == 0);
1766 thread = mPlaybackThreads.valueAt(i);
1767 }
1768 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001769 if (thread != nullptr) {
1770 return thread;
1771 }
1772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1773 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1774 ALOG_ASSERT(thread == 0);
1775 thread = mRecordThreads.valueAt(i);
1776 }
1777 }
1778 if (thread != nullptr) {
1779 return thread;
1780 }
1781 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1782 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1783 ALOG_ASSERT(thread == 0);
1784 thread = mMmapThreads.valueAt(i);
1785 }
1786 }
Eric Laurent717e1282012-06-29 16:36:52 -07001787 return thread;
1788}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791
1792// ----------------------------------------------------------------------------
1793
1794AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1795 : RefBase(),
1796 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001797 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798{
Andy Hung6f248bb2018-01-23 14:04:37 -08001799 mMemoryDealer = new MemoryDealer(
1800 audioFlinger->getClientSharedHeapSize(),
1801 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802}
1803
Eric Laurent021cf962014-05-13 10:18:14 -07001804// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805AudioFlinger::Client::~Client()
1806{
1807 mAudioFlinger->removeClient_l(mPid);
1808}
1809
Glenn Kasten435dbe62012-01-30 10:15:48 -08001810sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811{
1812 return mMemoryDealer;
1813}
1814
1815// ----------------------------------------------------------------------------
1816
1817AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1818 const sp<IAudioFlingerClient>& client,
1819 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001820 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821{
1822}
1823
1824AudioFlinger::NotificationClient::~NotificationClient()
1825{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826}
1827
Glenn Kasten0f11b512014-01-31 16:18:54 -08001828void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829{
1830 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001831 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832}
1833
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001834// ----------------------------------------------------------------------------
1835AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1836 : mPendingRequests(false) {}
1837
1838
1839void AudioFlinger::MediaLogNotifier::requestMerge() {
1840 AutoMutex _l(mMutex);
1841 mPendingRequests = true;
1842 mCond.signal();
1843}
1844
1845bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001846 // Should already have been checked, but just in case
1847 if (sMediaLogService == 0) {
1848 return false;
1849 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001850 // Wait until there are pending requests
1851 {
1852 AutoMutex _l(mMutex);
1853 mPendingRequests = false; // to ignore past requests
1854 while (!mPendingRequests) {
1855 mCond.wait(mMutex);
1856 // TODO may also need an exitPending check
1857 }
1858 mPendingRequests = false;
1859 }
1860 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001861 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001862 usleep(kPostTriggerSleepPeriod);
1863 return true;
1864}
1865
1866void AudioFlinger::requestLogMerge() {
1867 mMediaLogNotifier->requestMerge();
1868}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869
1870// ----------------------------------------------------------------------------
1871
Eric Laurentf14db3c2017-12-08 14:20:36 -08001872sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1873 CreateRecordOutput& output,
1874 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875{
1876 sp<RecordThread::RecordTrack> recordTrack;
1877 sp<RecordHandle> recordHandle;
1878 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001880 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001881 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882
Eric Laurentf14db3c2017-12-08 14:20:36 -08001883 output.cblk.clear();
1884 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001885 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001886
Eric Laurentf14db3c2017-12-08 14:20:36 -08001887 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001888 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001889 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001890 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001891 ALOGW_IF(clientUid != callingUid,
1892 "%s uid %d tried to pass itself off as %d",
1893 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001894 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001895 updatePid = true;
1896 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001897 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001898 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001899 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001900 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001901 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001902 __func__, callingUid, callingPid, clientPid);
1903 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001904 }
1905
Andy Hung6770c6f2015-04-07 13:43:36 -07001906 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001907 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1908 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001909 lStatus = BAD_VALUE;
1910 goto Exit;
1911 }
1912
Glenn Kasten53b5d092014-02-05 10:00:23 -08001913 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001914 if (!audio_is_input_channel(input.config.channel_mask)) {
1915 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001916 lStatus = BAD_VALUE;
1917 goto Exit;
1918 }
1919
Eric Laurentf14db3c2017-12-08 14:20:36 -08001920 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1921 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1922 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1923 lStatus = BAD_VALUE;
1924 goto Exit;
1925 }
1926
1927 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001928 output.selectedDeviceId = input.selectedDeviceId;
1929 output.flags = input.flags;
1930
1931 client = registerPid(clientPid);
1932
1933 // Not a conventional loop, but a retry loop for at most two iterations total.
1934 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1935 // Exits loop via break on no error of got exit on error
1936 // The sp<> references will be dropped when re-entering scope.
1937 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1938 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001939 // release previously opened input if retrying.
1940 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1941 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001942 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001943 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001944 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001945 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001946 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001947 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001948 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001949 sessionId,
1950 // FIXME compare to AudioTrack
1951 clientPid,
1952 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001953 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001954 &input.config,
1955 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07001956 if (lStatus != NO_ERROR) {
1957 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
1958 goto Exit;
1959 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001960
Glenn Kasten05997e22014-03-13 15:08:33 -07001961 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001963 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 if (thread == NULL) {
jiabinc1de2df2019-05-07 14:26:40 -07001965 ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 lStatus = BAD_VALUE;
1967 goto Exit;
1968 }
1969
Eric Laurentf14db3c2017-12-08 14:20:36 -08001970 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971
Eric Laurentf14db3c2017-12-08 14:20:36 -08001972 output.sampleRate = input.config.sample_rate;
1973 output.frameCount = input.frameCount;
1974 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001975
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001976 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001977 input.config.format, input.config.channel_mask,
1978 &output.frameCount, sessionId,
1979 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001980 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001981 input.clientInfo.clientTid,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07001982 &lStatus, portId,
1983 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001984 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001985
Eric Laurentf14db3c2017-12-08 14:20:36 -08001986 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1987 // audio policy manager without FAST constraint
1988 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001989 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001990 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001991
1992 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001993 goto Exit;
1994 }
1995
1996 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1997 // session and move it to this thread.
1998 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1999 if (chain != 0) {
2000 Mutex::Autolock _l(thread->mLock);
2001 thread->addEffectChain_l(chain);
2002 }
2003 break;
2004 }
2005 // End of retry loop.
2006 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 }
Glenn Kastene198c362013-08-13 09:13:36 -07002008
Eric Laurentf14db3c2017-12-08 14:20:36 -08002009 output.cblk = recordTrack->getCblk();
2010 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002011 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002012
2013 // return handle to client
2014 recordHandle = new RecordHandle(recordTrack);
2015
2016Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002017 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002018 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002019 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002020 // Don't hold mClientLock when releasing the reference on the track as the
2021 // destructor will acquire it.
2022 {
2023 Mutex::Autolock _cl(mClientLock);
2024 client.clear();
2025 }
Eric Laurent896c9672017-12-08 14:08:45 -08002026 recordTrack.clear();
2027 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002028 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002029 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 }
2031
Glenn Kasten9156ef32013-08-06 15:39:08 -07002032 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 return recordHandle;
2034}
2035
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002036
2037
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038// ----------------------------------------------------------------------------
2039
Eric Laurenta4c5a552012-03-29 10:12:40 -07002040audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2041{
Eric Laurent44622db2014-08-01 19:00:33 -07002042 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002043 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002044 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002045 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002046 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002047 }
2048 Mutex::Autolock _l(mLock);
2049 return loadHwModule_l(name);
2050}
2051
2052// loadHwModule_l() must be called with AudioFlinger::mLock held
2053audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2054{
2055 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2056 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2057 ALOGW("loadHwModule() module %s already loaded", name);
2058 return mAudioHwDevs.keyAt(i);
2059 }
2060 }
2061
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002062 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002063
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002064 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002065 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002066 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002067 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002068 }
2069
2070 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002071 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002072 mHardwareStatus = AUDIO_HW_IDLE;
2073 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002074 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002075 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002076 }
2077
John Grossmanee578c02012-07-23 17:05:46 -07002078 // Check and cache this HAL's level of support for master mute and master
2079 // volume. If this is the first HAL opened, and it supports the get
2080 // methods, use the initial values provided by the HAL as the current
2081 // master mute and volume settings.
2082
2083 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2084 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002085 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002086
2087 if (0 == mAudioHwDevs.size()) {
2088 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002089 float mv;
2090 if (OK == dev->getMasterVolume(&mv)) {
2091 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002092 }
2093
2094 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002095 bool mm;
2096 if (OK == dev->getMasterMute(&mm)) {
2097 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002098 }
2099 }
2100
Eric Laurenta4c5a552012-03-29 10:12:40 -07002101 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002102 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002103 flags = static_cast<AudioHwDevice::Flags>(flags |
2104 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2105 }
2106
2107 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002108 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002109 flags = static_cast<AudioHwDevice::Flags>(flags |
2110 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2111 }
2112
Eric Laurenta4c5a552012-03-29 10:12:40 -07002113 mHardwareStatus = AUDIO_HW_IDLE;
2114 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002115 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002116 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2117 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2118 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002119
Glenn Kastena13cde92016-03-28 15:26:02 -07002120 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002121 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002122
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002123 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002124
2125 return handle;
2126
2127}
2128
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002129// ----------------------------------------------------------------------------
2130
Glenn Kasten3b16c762012-11-14 08:44:39 -08002131uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002132{
2133 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002134 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002135 return thread != NULL ? thread->sampleRate() : 0;
2136}
2137
Glenn Kastene33054e2012-11-14 12:54:39 -08002138size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002139{
2140 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002141 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002142 return thread != NULL ? thread->frameCountHAL() : 0;
2143}
2144
2145// ----------------------------------------------------------------------------
2146
Andy Hung6f248bb2018-01-23 14:04:37 -08002147status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002148{
2149 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002150 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002151 return PERMISSION_DENIED;
2152 }
2153 Mutex::Autolock _l(mLock);
2154 if (mIsDeviceTypeKnown) {
2155 return INVALID_OPERATION;
2156 }
2157 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002158 mTotalMemory = totalMemory;
2159 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2160 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2161 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2162 // though actual setting is determined through device configuration.
2163 constexpr int64_t GB = 1024 * 1024 * 1024;
2164 mClientSharedHeapSize =
2165 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2166 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2167 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2168 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2169 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002170 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002171
2172 // TODO: Cache the client shared heap size in a persistent property.
2173 // It's possible that a native process or Java service or app accesses audioserver
2174 // after it is registered by system server, but before AudioService updates
2175 // the memory info. This would occur immediately after boot or an audioserver
2176 // crash and restore. Before update from AudioService, the client would get the
2177 // minimum heap size.
2178
2179 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2180 (isLowRamDevice ? "true" : "false"),
2181 (long long)mTotalMemory,
2182 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002183 return NO_ERROR;
2184}
2185
Andy Hung6f248bb2018-01-23 14:04:37 -08002186size_t AudioFlinger::getClientSharedHeapSize() const
2187{
2188 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2189 if (heapSizeInBytes != 0) { // read-only property overrides all.
2190 return heapSizeInBytes;
2191 }
2192 return mClientSharedHeapSize;
2193}
2194
Mikhail Naganovdea53042018-04-26 13:10:21 -07002195status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2196{
2197 ALOGV(__func__);
2198
2199 audio_module_handle_t module;
2200 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2201 module = config->ext.device.hw_module;
2202 } else {
2203 module = config->ext.mix.hw_module;
2204 }
2205
2206 Mutex::Autolock _l(mLock);
2207 ssize_t index = mAudioHwDevs.indexOfKey(module);
2208 if (index < 0) {
2209 ALOGW("%s() bad hw module %d", __func__, module);
2210 return BAD_VALUE;
2211 }
2212
2213 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2214 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2215}
2216
Eric Laurent93c3d412014-08-01 14:48:35 -07002217audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2218{
2219 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002220
2221 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2222 if (index >= 0) {
2223 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2224 mHwAvSyncIds.valueAt(index), sessionId);
2225 return mHwAvSyncIds.valueAt(index);
2226 }
2227
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002228 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002229 if (dev == NULL) {
2230 return AUDIO_HW_SYNC_INVALID;
2231 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002232 String8 reply;
2233 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002234 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002235 param = AudioParameter(reply);
2236 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002237
2238 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002239 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002240 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2241 return AUDIO_HW_SYNC_INVALID;
2242 }
2243
2244 // allow only one session for a given HW A/V sync ID.
2245 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2246 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2247 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2248 value, mHwAvSyncIds.keyAt(i));
2249 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002250 break;
2251 }
2252 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002253
2254 mHwAvSyncIds.add(sessionId, value);
2255
2256 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2257 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2258 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002259 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002260 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002261 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002262 String8 keyValuePairs = param.toString();
2263 thread->setParameters(keyValuePairs);
2264 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2265 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002266 break;
2267 }
2268 }
2269
2270 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2271 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002272}
2273
Eric Laurent72e3f392015-05-20 14:43:50 -07002274status_t AudioFlinger::systemReady()
2275{
2276 Mutex::Autolock _l(mLock);
2277 ALOGI("%s", __FUNCTION__);
2278 if (mSystemReady) {
2279 ALOGW("%s called twice", __FUNCTION__);
2280 return NO_ERROR;
2281 }
2282 mSystemReady = true;
2283 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2284 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2285 thread->systemReady();
2286 }
2287 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2288 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2289 thread->systemReady();
2290 }
2291 return NO_ERROR;
2292}
2293
jiabin46a76fa2018-01-05 10:18:21 -08002294status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2295{
jiabin9ff780e2018-03-19 18:19:52 -07002296 AutoMutex lock(mHardwareLock);
2297 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2298 status_t status = dev->getMicrophones(microphones);
2299 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002300}
2301
Eric Laurentfa90e842014-10-17 18:12:31 -07002302// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2303void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2304{
2305 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2306 if (index >= 0) {
2307 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2308 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2309 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002310 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002311 String8 keyValuePairs = param.toString();
2312 thread->setParameters(keyValuePairs);
2313 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2314 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002315 }
2316}
2317
2318
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002319// ----------------------------------------------------------------------------
2320
Eric Laurent83b88082014-06-20 18:31:16 -07002321
Eric Laurent6acd1d42017-01-04 14:23:29 -08002322sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabinc0106832019-10-24 14:58:31 -07002323 audio_io_handle_t *output,
2324 audio_config_t *config,
2325 audio_devices_t deviceType,
2326 const String8& address,
2327 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002328{
jiabinc0106832019-10-24 14:58:31 -07002329 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002330 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002331 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002332 }
2333
Eric Laurentcf2c0212014-07-25 16:20:43 -07002334 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002335 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2336 } else {
2337 // Audio Policy does not currently request a specific output handle.
2338 // If this is ever needed, see openInput_l() for example code.
2339 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2340 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002341 }
Eric Laurent83b88082014-06-20 18:31:16 -07002342
2343 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2344
Eric Laurent83b88082014-06-20 18:31:16 -07002345 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002346 // This if statement allows overriding the audio policy settings
2347 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2348 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2349 // Check only for Normal Mixing mode
2350 if (kEnableExtendedPrecision) {
2351 // Specify format (uncomment one below to choose)
2352 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2353 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2354 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2355 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002356 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002357 }
2358 if (kEnableExtendedChannels) {
2359 // Specify channel mask (uncomment one below to choose)
2360 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2361 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2362 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2363 }
Eric Laurent83b88082014-06-20 18:31:16 -07002364 }
2365
Phil Burk062e67a2015-02-11 13:40:50 -08002366 AudioStreamOut *outputStream = NULL;
2367 status_t status = outHwDev->openOutputStream(
2368 &outputStream,
2369 *output,
jiabinc0106832019-10-24 14:58:31 -07002370 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002371 flags,
2372 config,
2373 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002374
2375 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002376
Phil Burk062e67a2015-02-11 13:40:50 -08002377 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002378 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2379 sp<MmapPlaybackThread> thread =
jiabin10d86fd2019-10-31 17:20:42 -07002380 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002381 mMmapThreads.add(*output, thread);
2382 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2383 *output, thread.get());
2384 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002385 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002386 sp<PlaybackThread> thread;
2387 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabin10d86fd2019-10-31 17:20:42 -07002388 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002389 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2390 *output, thread.get());
2391 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2392 || !isValidPcmSinkFormat(config->format)
2393 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabin10d86fd2019-10-31 17:20:42 -07002394 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002395 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2396 *output, thread.get());
2397 } else {
jiabin10d86fd2019-10-31 17:20:42 -07002398 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002399 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2400 *output, thread.get());
2401 }
2402 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002403 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002404 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002405 }
Eric Laurent83b88082014-06-20 18:31:16 -07002406 }
2407
2408 return 0;
2409}
2410
Eric Laurentcf2c0212014-07-25 16:20:43 -07002411status_t AudioFlinger::openOutput(audio_module_handle_t module,
2412 audio_io_handle_t *output,
2413 audio_config_t *config,
jiabinc0106832019-10-24 14:58:31 -07002414 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002415 uint32_t *latencyMs,
2416 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417{
jiabinc0106832019-10-24 14:58:31 -07002418 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002419 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002420 this, module,
jiabinc0106832019-10-24 14:58:31 -07002421 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002422 config->sample_rate,
2423 config->format,
2424 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002425 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426
jiabinc0106832019-10-24 14:58:31 -07002427 audio_devices_t deviceType = device->type();
2428 const String8 address = String8(device->address().c_str());
2429
2430 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002431 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002433
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 Mutex::Autolock _l(mLock);
2435
jiabinc0106832019-10-24 14:58:31 -07002436 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002437 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002438 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2439 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2440 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441
Eric Laurent6acd1d42017-01-04 14:23:29 -08002442 // notify client processes of the new output creation
2443 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002444
Eric Laurent6acd1d42017-01-04 14:23:29 -08002445 // the first primary output opened designates the primary hw device
2446 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002447 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002448 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002449
Eric Laurent6acd1d42017-01-04 14:23:29 -08002450 AutoMutex lock(mHardwareLock);
2451 mHardwareStatus = AUDIO_HW_SET_MODE;
2452 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2453 mHardwareStatus = AUDIO_HW_IDLE;
2454 }
2455 } else {
2456 MmapThread *mmapThread = (MmapThread *)thread.get();
2457 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002458 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002459 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 }
2461
Eric Laurentcf2c0212014-07-25 16:20:43 -07002462 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463}
2464
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002465audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2466 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467{
2468 Mutex::Autolock _l(mLock);
2469 MixerThread *thread1 = checkMixerThread_l(output1);
2470 MixerThread *thread2 = checkMixerThread_l(output2);
2471
2472 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002473 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2474 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002475 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476 }
2477
Glenn Kasteneeecb982016-02-26 10:44:04 -08002478 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002479 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 thread->addOutputTrack(thread2);
2481 mPlaybackThreads.add(id, thread);
2482 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002483 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 return id;
2485}
2486
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002487status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488{
Glenn Kastend96c5722012-04-25 13:44:49 -07002489 return closeOutput_nonvirtual(output);
2490}
2491
2492status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2493{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 // keep strong reference on the playback thread so that
2495 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002496 sp<PlaybackThread> playbackThread;
2497 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 {
2499 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002500 playbackThread = checkPlaybackThread_l(output);
2501 if (playbackThread != NULL) {
2502 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503
Andy Hungdc099c22018-09-18 13:46:39 -07002504 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002505
Eric Laurent6acd1d42017-01-04 14:23:29 -08002506 if (playbackThread->type() == ThreadBase::MIXER) {
2507 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2508 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2509 DuplicatingThread *dupThread =
2510 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2511 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2512 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 }
2514 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002515
2516
Eric Laurent6acd1d42017-01-04 14:23:29 -08002517 mPlaybackThreads.removeItem(output);
2518 // save all effects to the default thread
2519 if (mPlaybackThreads.size()) {
2520 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2521 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002522 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002523 Mutex::Autolock _dl(dstThread->mLock);
2524 Mutex::Autolock _sl(playbackThread->mLock);
2525 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2526 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002527 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002528 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 }
2531 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002532 } else {
2533 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2534 if (mmapThread == 0) {
2535 return BAD_VALUE;
2536 }
Andy Hungdc099c22018-09-18 13:46:39 -07002537 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002538 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002539 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002541 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2542 ioDesc->mIoHandle = output;
2543 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002544 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002546 // The thread entity (active unit of execution) is no longer running here,
2547 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548
Eric Laurent6acd1d42017-01-04 14:23:29 -08002549 if (playbackThread != 0) {
2550 playbackThread->exit();
2551 if (!playbackThread->isDuplicating()) {
2552 closeOutputFinish(playbackThread);
2553 }
2554 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002555 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002556 mmapThread->exit();
2557 AudioStreamOut *out = mmapThread->clearOutput();
2558 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2559 // from now on thread->mOutput is NULL
2560 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 }
2562 return NO_ERROR;
2563}
2564
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002565void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002566{
2567 AudioStreamOut *out = thread->clearOutput();
2568 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2569 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002570 delete out;
2571}
2572
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002573void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002574{
2575 mPlaybackThreads.removeItem(thread->mId);
2576 thread->exit();
2577 closeOutputFinish(thread);
2578}
2579
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002580status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581{
2582 Mutex::Autolock _l(mLock);
2583 PlaybackThread *thread = checkPlaybackThread_l(output);
2584
2585 if (thread == NULL) {
2586 return BAD_VALUE;
2587 }
2588
Steve Block3856b092011-10-20 11:56:00 +01002589 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 thread->suspend();
2591
2592 return NO_ERROR;
2593}
2594
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002595status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596{
2597 Mutex::Autolock _l(mLock);
2598 PlaybackThread *thread = checkPlaybackThread_l(output);
2599
2600 if (thread == NULL) {
2601 return BAD_VALUE;
2602 }
2603
Steve Block3856b092011-10-20 11:56:00 +01002604 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605
2606 thread->restore();
2607
2608 return NO_ERROR;
2609}
2610
Eric Laurentcf2c0212014-07-25 16:20:43 -07002611status_t AudioFlinger::openInput(audio_module_handle_t module,
2612 audio_io_handle_t *input,
2613 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002614 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002615 const String8& address,
2616 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002617 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618{
Eric Laurent83b88082014-06-20 18:31:16 -07002619 Mutex::Autolock _l(mLock);
2620
Glenn Kastene7d66712015-03-05 13:46:52 -08002621 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002622 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002623 }
2624
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002625 sp<ThreadBase> thread = openInput_l(
2626 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002627
2628 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002629 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002630 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002631 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002633 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002634}
Dima Zavin799a70e2011-04-18 16:57:27 -07002635
Eric Laurent6acd1d42017-01-04 14:23:29 -08002636sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002637 audio_io_handle_t *input,
2638 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002639 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002640 const String8& address,
2641 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002642 audio_input_flags_t flags,
2643 audio_devices_t outputDevice,
2644 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002645{
Glenn Kastene7d66712015-03-05 13:46:52 -08002646 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002647 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002648 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002649 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002650 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002651
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002652 // Some flags are specific to framework and must not leak to the HAL.
2653 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2654
Glenn Kasteneeecb982016-02-26 10:44:04 -08002655 // Audio Policy can request a specific handle for hardware hotword.
2656 // The goal here is not to re-open an already opened input.
2657 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002658 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002659 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2660 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2661 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2662 return 0;
2663 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2664 // This should not happen in a transient state with current design.
2665 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2666 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002667 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002668
Eric Laurentcf2c0212014-07-25 16:20:43 -07002669 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002670 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002671 sp<StreamInHalInterface> inStream;
2672 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002673 *input, devices, &halconfig, flags, address.string(), source,
2674 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002675 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2676 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002677 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002678 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002679 halconfig.sample_rate,
2680 halconfig.format,
2681 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002682 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002683 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002685 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002686 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002687 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002688 audio_is_linear_pcm(config->format) &&
2689 audio_is_linear_pcm(halconfig.format) &&
2690 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002691 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2692 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002693 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002694 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002695 inStream.clear();
2696 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002697 *input, devices, &halconfig, flags, address.string(), source,
2698 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002699 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 }
2701
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002702 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002703 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002704 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2705 sp<MmapCaptureThread> thread =
jiabin10d86fd2019-10-31 17:20:42 -07002706 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002707 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002708 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2709 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002710 return thread;
2711 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002712 // Start record thread
2713 // RecordThread requires both input and output device indication to forward to audio
2714 // pre processing modules
jiabin10d86fd2019-10-31 17:20:42 -07002715 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002716 mRecordThreads.add(*input, thread);
2717 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2718 return thread;
2719 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 }
2721
Eric Laurentcf2c0212014-07-25 16:20:43 -07002722 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 return 0;
2724}
2725
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002726status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727{
Glenn Kastend96c5722012-04-25 13:44:49 -07002728 return closeInput_nonvirtual(input);
2729}
2730
2731status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2732{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 // keep strong reference on the record thread so that
2734 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002735 sp<RecordThread> recordThread;
2736 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737 {
2738 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002739 recordThread = checkRecordThread_l(input);
2740 if (recordThread != 0) {
2741 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742
Andy Hungdc099c22018-09-18 13:46:39 -07002743 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002744
Eric Laurent6acd1d42017-01-04 14:23:29 -08002745 // If we still have effect chains, it means that a client still holds a handle
2746 // on at least one effect. We must either move the chain to an existing thread with the
2747 // same session ID or put it aside in case a new record thread is opened for a
2748 // new capture on the same session
2749 sp<EffectChain> chain;
2750 {
2751 Mutex::Autolock _sl(recordThread->mLock);
2752 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2753 // Note: maximum one chain per record thread
2754 if (effectChains.size() != 0) {
2755 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002756 }
2757 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002758 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002759 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002760 // This should only happen in case of overlap between one thread tear down and the
2761 // creation of its replacement
2762 size_t i;
2763 for (i = 0; i < mRecordThreads.size(); i++) {
2764 sp<RecordThread> t = mRecordThreads.valueAt(i);
2765 if (t == recordThread) {
2766 continue;
2767 }
2768 if (t->hasAudioSession(chain->sessionId()) != 0) {
2769 Mutex::Autolock _l(t->mLock);
2770 ALOGV("closeInput() found thread %d for effect session %d",
2771 t->id(), chain->sessionId());
2772 t->addEffectChain_l(chain);
2773 break;
2774 }
2775 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002776 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002777 if (i == mRecordThreads.size()) {
2778 putOrphanEffectChain_l(chain);
2779 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002780 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002781 mRecordThreads.removeItem(input);
2782 } else {
2783 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2784 if (mmapThread == 0) {
2785 return BAD_VALUE;
2786 }
Andy Hungdc099c22018-09-18 13:46:39 -07002787 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002788 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002789 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002790 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2791 ioDesc->mIoHandle = input;
2792 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 }
Eric Laurent83b88082014-06-20 18:31:16 -07002794 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2795 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002796 if (recordThread != 0) {
2797 closeInputFinish(recordThread);
2798 } else if (mmapThread != 0) {
2799 mmapThread->exit();
2800 AudioStreamIn *in = mmapThread->clearInput();
2801 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2802 // from now on thread->mInput is NULL
2803 delete in;
2804 }
Eric Laurent83b88082014-06-20 18:31:16 -07002805 return NO_ERROR;
2806}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002808void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002809{
2810 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002811 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002812 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002813 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002814 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002815}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002817void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002818{
2819 mRecordThreads.removeItem(thread->mId);
2820 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821}
2822
Glenn Kastend2304db2014-02-03 07:40:31 -08002823status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824{
2825 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002826 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827
2828 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2829 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002830 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002831 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002832 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2833 mMmapThreads[i]->invalidateTracks(stream);
2834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835 return NO_ERROR;
2836}
2837
2838
Glenn Kasteneeecb982016-02-26 10:44:04 -08002839audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840{
Glenn Kasten9d003132016-04-06 14:38:09 -07002841 // This is a binder API, so a malicious client could pass in a bad parameter.
2842 // Check for that before calling the internal API nextUniqueId().
2843 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2844 ALOGE("newAudioUniqueId invalid use %d", use);
2845 return AUDIO_UNIQUE_ID_ALLOCATE;
2846 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002847 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848}
2849
Glenn Kastend848eb42016-03-08 13:42:11 -08002850void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002851{
2852 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002853 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002854 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002855 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2856 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002857 caller = pid;
2858 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002859
Eric Laurent021cf962014-05-13 10:18:14 -07002860 {
2861 Mutex::Autolock _cl(mClientLock);
2862 // Ignore requests received from processes not known as notification client. The request
2863 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2864 // called from a different pid leaving a stale session reference. Also we don't know how
2865 // to clear this reference if the client process dies.
2866 if (mNotificationClients.indexOfKey(caller) < 0) {
2867 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2868 return;
2869 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002870 }
2871
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002872 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002873 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002874 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002875 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2876 ref->mCnt++;
2877 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002878 return;
2879 }
2880 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002881 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2882 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002883}
2884
Glenn Kastend848eb42016-03-08 13:42:11 -08002885void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002886{
Eric Laurent6c796322019-04-09 14:13:17 -07002887 std::vector< sp<EffectModule> > removedEffects;
2888 {
2889 Mutex::Autolock _l(mLock);
2890 pid_t caller = IPCThreadState::self()->getCallingPid();
2891 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2892 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2893 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2894 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002895 }
Eric Laurent6c796322019-04-09 14:13:17 -07002896 size_t num = mAudioSessionRefs.size();
2897 for (size_t i = 0; i < num; i++) {
2898 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2899 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2900 ref->mCnt--;
2901 ALOGV(" decremented refcount to %d", ref->mCnt);
2902 if (ref->mCnt == 0) {
2903 mAudioSessionRefs.removeAt(i);
2904 delete ref;
2905 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2906 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2907 }
2908 goto Exit;
2909 }
2910 }
2911 // If the caller is audioserver it is likely that the session being released was acquired
2912 // on behalf of a process not in notification clients and we ignore the warning.
2913 ALOGW_IF(!isAudioServerUid(callerUid),
2914 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002915 }
Eric Laurent6c796322019-04-09 14:13:17 -07002916
2917Exit:
2918 for (auto& effect : removedEffects) {
2919 effect->updatePolicyState();
2920 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002921}
2922
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002923bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2924{
2925 size_t num = mAudioSessionRefs.size();
2926 for (size_t i = 0; i < num; i++) {
2927 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2928 if (ref->mSessionid == audioSession) {
2929 return true;
2930 }
2931 }
2932 return false;
2933}
2934
Eric Laurent6c796322019-04-09 14:13:17 -07002935std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002936
Steve Block3856b092011-10-20 11:56:00 +01002937 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002938
2939 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002940 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002941
2942 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2943 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002944 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002945 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2946 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurenta20c4e92019-11-12 15:55:51 -08002947 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07002948 chains.push(ec);
2949 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002950 }
2951 }
Eric Laurent6c796322019-04-09 14:13:17 -07002952
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002953 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2954 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002955 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002956 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2957 sp<EffectChain> ec = t->mEffectChains[j];
2958 chains.push(ec);
2959 }
2960 }
2961
Eric Laurent6c796322019-04-09 14:13:17 -07002962 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2963 sp<MmapThread> t = mMmapThreads.valueAt(i);
2964 Mutex::Autolock _l(t->mLock);
2965 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2966 sp<EffectChain> ec = t->mEffectChains[j];
2967 chains.push(ec);
2968 }
2969 }
2970
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002971 for (size_t i = 0; i < chains.size(); i++) {
2972 sp<EffectChain> ec = chains[i];
2973 int sessionid = ec->sessionId();
2974 sp<ThreadBase> t = ec->mThread.promote();
2975 if (t == 0) {
2976 continue;
2977 }
2978 size_t numsessionrefs = mAudioSessionRefs.size();
2979 bool found = false;
2980 for (size_t k = 0; k < numsessionrefs; k++) {
2981 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002982 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002983 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002984 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002985 found = true;
2986 break;
2987 }
2988 }
2989 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002990 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002991 // remove all effects from the chain
2992 while (ec->mEffects.size()) {
2993 sp<EffectModule> effect = ec->mEffects[0];
2994 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002995 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002996 if (effect->purgeHandles()) {
2997 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002998 }
Eric Laurent6c796322019-04-09 14:13:17 -07002999 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003000 }
3001 }
3002 }
Eric Laurent6c796322019-04-09 14:13:17 -07003003 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003004}
3005
Andy Hungdc099c22018-09-18 13:46:39 -07003006// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3007void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3008{
3009 audio_utils::FdToString fdToString;
3010 const int fd = fdToString.fd();
3011 if (fd >= 0) {
3012 thread->dump(fd, {} /* args */);
3013 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3014 }
3015}
3016
Glenn Kasteneeecb982016-02-26 10:44:04 -08003017// checkThread_l() must be called with AudioFlinger::mLock held
3018AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3019{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003020 ThreadBase *thread = checkMmapThread_l(ioHandle);
3021 if (thread == 0) {
3022 switch (audio_unique_id_get_use(ioHandle)) {
3023 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3024 thread = checkPlaybackThread_l(ioHandle);
3025 break;
3026 case AUDIO_UNIQUE_ID_USE_INPUT:
3027 thread = checkRecordThread_l(ioHandle);
3028 break;
3029 default:
3030 break;
3031 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003032 }
3033 return thread;
3034}
3035
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003037AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038{
Glenn Kastena1117922012-01-26 10:53:32 -08003039 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040}
3041
3042// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003043AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044{
3045 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003046 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047}
3048
3049// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003050AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051{
Glenn Kastena1117922012-01-26 10:53:32 -08003052 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053}
3054
Eric Laurent6acd1d42017-01-04 14:23:29 -08003055// checkMmapThread_l() must be called with AudioFlinger::mLock held
3056AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3057{
3058 return mMmapThreads.valueFor(io).get();
3059}
3060
3061
3062// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3063AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3064{
Eric Laurent7459b902017-04-19 18:10:41 -07003065 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003066 if (volumeInterface == nullptr) {
3067 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3068 if (mmapThread != nullptr) {
3069 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003070 MmapPlaybackThread *mmapPlaybackThread =
3071 static_cast<MmapPlaybackThread *>(mmapThread);
3072 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003073 }
3074 }
3075 }
3076 return volumeInterface;
3077}
3078
3079Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3080{
3081 Vector <VolumeInterface *> volumeInterfaces;
3082 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003083 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003084 }
3085 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3086 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003087 MmapPlaybackThread *mmapPlaybackThread =
3088 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3089 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003090 }
3091 }
3092 return volumeInterfaces;
3093}
3094
Glenn Kasteneeecb982016-02-26 10:44:04 -08003095audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096{
Glenn Kasten9d003132016-04-06 14:38:09 -07003097 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003098 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003099 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3100 for (int retry = 0; retry < maxRetries; retry++) {
3101 // The cast allows wraparound from max positive to min negative instead of abort
3102 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3103 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3104 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3105 // allow wrap by skipping 0 and -1 for session ids
3106 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3107 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3108 return (audio_unique_id_t) (base | use);
3109 }
3110 }
3111 // We have no way of recovering from wraparound
3112 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3113 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114}
3115
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003116AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003117{
3118 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3119 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003120 if(thread->isDuplicating()) {
3121 continue;
3122 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003123 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003124 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003125 return thread;
3126 }
3127 }
3128 return NULL;
3129}
3130
jiabin10d86fd2019-10-31 17:20:42 -07003131DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003132{
3133 PlaybackThread *thread = primaryPlaybackThread_l();
3134
3135 if (thread == NULL) {
jiabin10d86fd2019-10-31 17:20:42 -07003136 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003137 }
3138
jiabin10d86fd2019-10-31 17:20:42 -07003139 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003140}
3141
Glenn Kastena7335632016-06-09 17:09:53 -07003142AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3143{
3144 size_t minFrameCount = 0;
3145 PlaybackThread *minThread = NULL;
3146 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3147 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3148 if (!thread->isDuplicating()) {
3149 size_t frameCount = thread->frameCountHAL();
3150 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3151 (frameCount == minFrameCount && thread->hasFastMixer() &&
3152 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3153 minFrameCount = frameCount;
3154 minThread = thread;
3155 }
3156 }
3157 }
3158 return minThread;
3159}
3160
Eric Laurenta011e352012-03-29 15:51:43 -07003161sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003162 audio_session_t triggerSession,
3163 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003164 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003165 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003166{
3167 Mutex::Autolock _l(mLock);
3168
3169 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3170 status_t playStatus = NAME_NOT_FOUND;
3171 status_t recStatus = NAME_NOT_FOUND;
3172 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3173 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3174 if (playStatus == NO_ERROR) {
3175 return event;
3176 }
3177 }
3178 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3179 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3180 if (recStatus == NO_ERROR) {
3181 return event;
3182 }
3183 }
3184 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3185 mPendingSyncEvents.add(event);
3186 } else {
3187 ALOGV("createSyncEvent() invalid event %d", event->type());
3188 event.clear();
3189 }
3190 return event;
3191}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003192
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193// ----------------------------------------------------------------------------
3194// Effect management
3195// ----------------------------------------------------------------------------
3196
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003197sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3198 return mEffectsFactoryHal;
3199}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200
Glenn Kastenf587ba52012-01-26 16:25:10 -08003201status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202{
3203 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003204 if (mEffectsFactoryHal.get()) {
3205 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3206 } else {
3207 return -ENODEV;
3208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209}
3210
Glenn Kastenf587ba52012-01-26 16:25:10 -08003211status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212{
3213 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003214 if (mEffectsFactoryHal.get()) {
3215 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3216 } else {
3217 return -ENODEV;
3218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219}
3220
Glenn Kasten5e92a782012-01-30 07:40:52 -08003221status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003222 const effect_uuid_t *pTypeUuid,
3223 uint32_t preferredTypeFlag,
3224 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003226 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3227 return BAD_VALUE;
3228 }
3229
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003231
3232 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003233 return -ENODEV;
3234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003236 status_t status = NO_ERROR;
3237 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3238 // If uuid is specified, request effect descriptor from that.
3239 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3240 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3241 // If uuid is not specified, look for an available implementation
3242 // of the required type instead.
3243
3244 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3245 effect_descriptor_t desc;
3246 desc.flags = 0; // prevent compiler warning
3247
3248 uint32_t numEffects = 0;
3249 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3250 if (status < 0) {
3251 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3252 return status;
3253 }
3254
3255 bool found = false;
3256 for (uint32_t i = 0; i < numEffects; i++) {
3257 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3258 if (status < 0) {
3259 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3260 continue;
3261 }
3262 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3263 // If matching type found save effect descriptor.
3264 found = true;
3265 *descriptor = desc;
3266
3267 // If there's no preferred flag or this descriptor matches the preferred
3268 // flag, success! If this descriptor doesn't match the preferred
3269 // flag, continue enumeration in case a better matching version of this
3270 // effect type is available. Note that this means if no effect with a
3271 // correct flag is found, the descriptor returned will correspond to the
3272 // last effect that at least had a matching type uuid (if any).
3273 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3274 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3275 break;
3276 }
3277 }
3278 }
3279
3280 if (!found) {
3281 status = NAME_NOT_FOUND;
3282 ALOGW("getEffectDescriptor(): Effect not found by type.");
3283 }
3284 } else {
3285 status = BAD_VALUE;
3286 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3287 }
3288 return status;
3289}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003291sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 effect_descriptor_t *pDesc,
3293 const sp<IEffectClient>& effectClient,
3294 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003295 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003296 audio_session_t sessionId,
Eric Laurentfefebb52019-11-13 12:45:28 -08003297 const AudioDeviceTypeAddr& device __unused,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003298 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003299 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 status_t *status,
3301 int *id,
3302 int *enabled)
3303{
3304 status_t lStatus = NO_ERROR;
3305 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307
Eric Laurentb6436272016-12-07 19:24:50 -08003308 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003309 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003310 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3311 ALOGW_IF(pid != -1 && pid != callingPid,
3312 "%s uid %d pid %d tried to pass itself off as pid %d",
3313 __func__, callingUid, callingPid, pid);
3314 pid = callingPid;
3315 }
3316
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003317 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3318 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319
3320 if (pDesc == NULL) {
3321 lStatus = BAD_VALUE;
3322 goto Exit;
3323 }
3324
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003325 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003326 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003327 lStatus = NO_INIT;
3328 goto Exit;
3329 }
3330
Andy Hung6096dcd2019-03-13 13:20:30 -07003331 // check audio settings permission for global effects
3332 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3333 if (!settingsAllowed()) {
3334 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3335 lStatus = PERMISSION_DENIED;
3336 goto Exit;
3337 }
3338 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3339 if (!isAudioServerUid(callingUid)) {
3340 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3341 lStatus = PERMISSION_DENIED;
3342 goto Exit;
3343 }
3344
3345 if (io == AUDIO_IO_HANDLE_NONE) {
3346 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3347 lStatus = BAD_VALUE;
3348 goto Exit;
3349 }
Eric Laurenta20c4e92019-11-12 15:55:51 -08003350 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3351 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3352 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3353 lStatus = PERMISSION_DENIED;
3354 goto Exit;
3355 }
Eric Laurentfefebb52019-11-13 12:45:28 -08003356 if (io != AUDIO_IO_HANDLE_NONE) {
3357 ALOGE("%s: io handle should not be specified for device effect", __func__);
3358 lStatus = BAD_VALUE;
3359 goto Exit;
3360 }
Eric Laurenta20c4e92019-11-12 15:55:51 -08003361 //TODO: add check on device ID when added to arguments
Andy Hung6096dcd2019-03-13 13:20:30 -07003362 } else {
3363 // general sessionId.
3364
3365 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3366 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3367 lStatus = BAD_VALUE;
3368 goto Exit;
3369 }
3370
3371 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3372 // to prevent creating an effect when one doesn't actually have track with that session?
3373 }
3374
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003376 // Get the full effect descriptor from the uuid/type.
3377 // If the session is the output mix, prefer an auxiliary effect,
3378 // otherwise no preference.
3379 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3380 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3381 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3382 if (lStatus < 0) {
3383 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3384 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385 }
3386
3387 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003388 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3390 lStatus = INVALID_OPERATION;
3391 goto Exit;
3392 }
3393
Eric Laurent59255e42011-07-27 19:49:51 -07003394 // check recording permission for visualizer
3395 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003396 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurenta20c4e92019-11-12 15:55:51 -08003397 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003398 lStatus = PERMISSION_DENIED;
3399 goto Exit;
3400 }
3401
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003403 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003404 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003405 // if the output returned by getOutputForEffect() is removed before we lock the
3406 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3407 // and we will exit safely
3408 io = AudioSystem::getOutputForEffect(&desc);
3409 ALOGV("createEffect got output %d", io);
3410 }
3411
3412 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413
3414 // If output is not specified try to find a matching audio session ID in one of the
3415 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003416 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3417 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003418 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3419 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003420 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003421 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003422 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3423 if (io == AUDIO_IO_HANDLE_NONE) {
3424 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003426 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003427 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003428 }
Andy Hung444bb552019-03-14 17:06:39 -07003429
3430 // If you wish to create a Record preprocessing AudioEffect in Java,
3431 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3432 // Otherwise it will fail when created on a Playback thread by legacy
3433 // handling below. Ditto with Mmap, the associated Mmap track must be created
3434 // before creating the AudioEffect or the io handle must be specified.
3435 //
3436 // Detect if the effect is created after an AudioRecord is destroyed.
3437 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3438 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3439 " for session %d no longer exists",
3440 __func__, desc.name, sessionId);
3441 lStatus = PERMISSION_DENIED;
3442 goto Exit;
3443 }
3444
3445 // Legacy handling of creating an effect on an expired or made-up
3446 // session id. We think that it is a Playback effect.
3447 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003448 // If no output thread contains the requested session ID, default to
3449 // first output. The effect chain will be moved to the correct output
3450 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003451 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003452 io = mPlaybackThreads.keyAt(0);
3453 }
Steve Block3856b092011-10-20 11:56:00 +01003454 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003455 } else if (checkPlaybackThread_l(io) != nullptr) {
3456 // allow only one effect chain per sessionId on mPlaybackThreads.
3457 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3458 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3459 if (io == checkIo) continue;
3460 const uint32_t sessionType =
3461 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3462 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3463 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3464 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3465 android_errorWriteLog(0x534e4554, "123237974");
3466 lStatus = BAD_VALUE;
3467 goto Exit;
3468 }
3469 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003470 }
3471 ThreadBase *thread = checkRecordThread_l(io);
3472 if (thread == NULL) {
3473 thread = checkPlaybackThread_l(io);
3474 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003475 thread = checkMmapThread_l(io);
3476 if (thread == NULL) {
3477 ALOGE("createEffect() unknown output thread");
3478 lStatus = BAD_VALUE;
3479 goto Exit;
3480 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003481 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003482 } else {
3483 // Check if one effect chain was awaiting for an effect to be created on this
3484 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003485 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003486 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003487 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003488 thread->addEffectChain_l(chain);
3489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003491
Eric Laurent021cf962014-05-13 10:18:14 -07003492 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003494 // create effect on selected output thread
Eric Laurenta20c4e92019-11-12 15:55:51 -08003495 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003496 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003497 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003498 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003499 // remove local strong reference to Client with mClientLock held
3500 Mutex::Autolock _cl(mClientLock);
3501 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003502 } else {
3503 // handle must be valid here, but check again to be safe.
3504 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003505 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 }
3507
Eric Laurent6c796322019-04-09 14:13:17 -07003508 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3509 // Check CPU and memory usage
3510 sp<EffectModule> effect = handle->effect().promote();
3511 if (effect != nullptr) {
3512 status_t rStatus = effect->updatePolicyState();
3513 if (rStatus != NO_ERROR) {
3514 lStatus = rStatus;
3515 }
3516 }
3517 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003518 handle.clear();
3519 }
3520
Mathias Agopian65ab4712010-07-14 17:59:35 -07003521Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003522 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523 return handle;
3524}
3525
Glenn Kastend848eb42016-03-08 13:42:11 -08003526status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003527 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003528{
Steve Block3856b092011-10-20 11:56:00 +01003529 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003530 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003531 Mutex::Autolock _l(mLock);
3532 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003533 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003534 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 }
Eric Laurentde070132010-07-13 04:45:46 -07003536 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3537 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003538 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003539 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 }
Eric Laurentde070132010-07-13 04:45:46 -07003541 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3542 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003543 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003544 return BAD_VALUE;
3545 }
3546
3547 Mutex::Autolock _dl(dstThread->mLock);
3548 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003549 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550}
3551
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003552
3553void AudioFlinger::setEffectSuspended(int effectId,
3554 audio_session_t sessionId,
3555 bool suspended)
3556{
3557 Mutex::Autolock _l(mLock);
3558
3559 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3560 if (thread == nullptr) {
3561 return;
3562 }
3563 Mutex::Autolock _sl(thread->mLock);
3564 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3565 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3566}
3567
3568
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003569// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003570status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003571 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003572 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003573{
Steve Block3856b092011-10-20 11:56:00 +01003574 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003575 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003576
Eric Laurent59255e42011-07-27 19:49:51 -07003577 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003578 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003579 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003580 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003581 return INVALID_OPERATION;
3582 }
3583
Eric Laurent4c415062016-06-17 16:14:16 -07003584 // Check whether the destination thread and all effects in the chain are compatible
3585 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003586 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003587 " destination thread %p is not compatible with effects in the chain",
3588 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003589 return INVALID_OPERATION;
3590 }
3591
Eric Laurent39e94f82010-07-28 01:32:47 -07003592 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003593 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003594 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003595 // removed.
3596 srcThread->removeEffectChain_l(chain);
3597
3598 // transfer all effects one by one so that new effect chain is created on new thread with
3599 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003600 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003601 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003602 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003603 Vector< sp<EffectModule> > removed;
3604 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003605 while (effect != 0) {
3606 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003607 removed.add(effect);
3608 status = dstThread->addEffect_l(effect);
3609 if (status != NO_ERROR) {
3610 break;
3611 }
Eric Laurentec35a142011-10-05 17:42:25 -07003612 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3613 if (effect->state() == EffectModule::ACTIVE ||
3614 effect->state() == EffectModule::STOPPING) {
3615 effect->start();
3616 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003617 // if the move request is not received from audio policy manager, the effect must be
3618 // re-registered with the new strategy and output
3619 if (dstChain == 0) {
3620 dstChain = effect->chain().promote();
3621 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003622 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003623 status = NO_INIT;
3624 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003625 }
3626 strategy = dstChain->strategy();
3627 }
Eric Laurentde070132010-07-13 04:45:46 -07003628 effect = chain->getEffectFromId_l(0);
3629 }
3630
Eric Laurent5baf2af2013-09-12 17:37:00 -07003631 if (status != NO_ERROR) {
3632 for (size_t i = 0; i < removed.size(); i++) {
3633 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003634 }
3635 }
3636
3637 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638}
3639
Eric Laurent6c796322019-04-09 14:13:17 -07003640status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3641 const sp<PlaybackThread>& dstThread,
3642 sp<PlaybackThread> *srcThread)
3643{
3644 status_t status = NO_ERROR;
3645 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003646 sp<PlaybackThread> thread =
3647 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003648
3649 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3650 Mutex::Autolock _dl(dstThread->mLock);
3651 Mutex::Autolock _sl(thread->mLock);
3652 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3653 sp<EffectChain> dstChain;
3654 if (srcChain == 0) {
3655 return INVALID_OPERATION;
3656 }
3657
3658 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3659 if (effect == 0) {
3660 return INVALID_OPERATION;
3661 }
3662 thread->removeEffect_l(effect);
3663 status = dstThread->addEffect_l(effect);
3664 if (status != NO_ERROR) {
3665 thread->addEffect_l(effect);
3666 status = INVALID_OPERATION;
3667 goto Exit;
3668 }
3669
3670 dstChain = effect->chain().promote();
3671 if (dstChain == 0) {
3672 thread->addEffect_l(effect);
3673 status = INVALID_OPERATION;
3674 }
3675
3676Exit:
3677 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3678 if (effect->state() == EffectModule::ACTIVE ||
3679 effect->state() == EffectModule::STOPPING) {
3680 effect->start();
3681 }
3682 }
3683
3684 if (status == NO_ERROR && srcThread != nullptr) {
3685 *srcThread = thread;
3686 }
3687 return status;
3688}
3689
Eric Laurent5baf2af2013-09-12 17:37:00 -07003690bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003691{
3692 if (mGlobalEffectEnableTime != 0 &&
3693 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3694 return true;
3695 }
3696
3697 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3698 sp<EffectChain> ec =
3699 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003700 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003701 return true;
3702 }
3703 }
3704 return false;
3705}
3706
Eric Laurent5baf2af2013-09-12 17:37:00 -07003707void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003708{
3709 Mutex::Autolock _l(mLock);
3710
3711 mGlobalEffectEnableTime = systemTime();
3712
3713 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3714 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3715 if (t->mType == ThreadBase::OFFLOAD) {
3716 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3717 }
3718 }
3719
3720}
3721
Eric Laurentaaa44472014-09-12 17:41:50 -07003722status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3723{
Eric Laurentd8365c52017-07-16 15:27:05 -07003724 // clear possible suspended state before parking the chain so that it starts in default state
3725 // when attached to a new record thread
3726 chain->setEffectSuspended_l(FX_IID_AEC, false);
3727 chain->setEffectSuspended_l(FX_IID_NS, false);
3728
Glenn Kastend848eb42016-03-08 13:42:11 -08003729 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003730 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003731 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003732 if (index >= 0) {
3733 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3734 return ALREADY_EXISTS;
3735 }
3736 mOrphanEffectChains.add(session, chain);
3737 return NO_ERROR;
3738}
3739
3740sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3741{
3742 sp<EffectChain> chain;
3743 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003744 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003745 if (index >= 0) {
3746 chain = mOrphanEffectChains.valueAt(index);
3747 mOrphanEffectChains.removeItemsAt(index);
3748 }
3749 return chain;
3750}
3751
3752bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3753{
3754 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003755 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003756 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003757 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003758 if (index >= 0) {
3759 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003760 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003761 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003762 mOrphanEffectChains.removeItemsAt(index);
3763 }
3764 return true;
3765 }
3766 return false;
3767}
3768
3769
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770// ----------------------------------------------------------------------------
3771
3772status_t AudioFlinger::onTransact(
3773 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3774{
3775 return BnAudioFlinger::onTransact(code, data, reply, flags);
3776}
3777
Glenn Kasten63238ef2015-03-02 15:50:29 -08003778} // namespace android