blob: e5a6e27fad21e325d35945b969ebb28ad78c9cd7 [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
jiabina392a552019-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>
Andy Hungb68f5eb2019-12-03 16:49:17 -080043#include <media/MediaMetricsItem.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070044#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070045#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <utils/String16.h>
47#include <utils/threads.h>
48
Steven Morelandf0c02ce2018-02-23 14:53:55 -080049#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <cutils/properties.h>
51
Dima Zavin64760242011-05-11 14:15:23 -070052#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070053#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070056#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Andy Hung6770c6f2015-04-07 13:43:36 -070058#include <media/AudioResamplerPublic.h>
59
Mikhail Naganov9fe94012016-10-14 14:57:40 -070060#include <system/audio_effects/effect_visualizer.h>
61#include <system/audio_effects/effect_ns.h>
62#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063
Glenn Kasten3b21c502011-12-15 09:52:39 -080064#include <audio_utils/primitives.h>
65
Eric Laurentfeb0db62011-07-22 09:04:31 -070066#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080067
Glenn Kasten9e58b552013-01-18 15:09:48 -080068#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070069#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070#include <media/nbaio/Pipe.h>
71#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080072#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070073#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070074#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070075#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080076
rago3bd1c872016-09-26 12:58:14 -070077//#define BUFLOG_NDEBUG 0
78#include <BufLog.h>
79
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080080#include "TypedLogger.h"
81
Mathias Agopian65ab4712010-07-14 17:59:35 -070082// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070083
John Grossman1c345192012-03-27 14:00:17 -070084// Note: the following macro is used for extremely verbose logging message. In
85// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
86// 0; but one side effect of this is to turn all LOGV's as well. Some messages
87// are so verbose that we want to suppress them even when we have ALOG_ASSERT
88// turned on. Do not uncomment the #def below unless you really know what you
89// are doing and want to see all of the extremely verbose messages.
90//#define VERY_VERY_VERBOSE_LOGGING
91#ifdef VERY_VERY_VERBOSE_LOGGING
92#define ALOGVV ALOGV
93#else
94#define ALOGVV(a...) do { } while(0)
95#endif
Eric Laurentde070132010-07-13 04:45:46 -070096
Mathias Agopian65ab4712010-07-14 17:59:35 -070097namespace android {
98
Glenn Kastenec1d6b52011-12-12 09:04:45 -080099static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
100static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700101static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700102static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
Glenn Kasten58912562012-04-03 10:45:00 -0700104
John Grossman4ff14ba2012-02-08 16:37:41 -0800105nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800106
Eric Laurent81784c32012-11-19 14:55:58 -0800107uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700108
Eric Laurent813e2a72013-08-31 12:59:48 -0700109// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
110// we define a minimum time during which a global effect is considered enabled.
111static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
112
Eric Laurentfc235202016-12-20 18:48:17 -0800113Mutex gLock;
114wp<AudioFlinger> gAudioFlinger;
115
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700116// Keep a strong reference to media.log service around forever.
117// The service is within our parent process so it can never die in a way that we could observe.
118// These two variables are const after initialization.
119static sp<IBinder> sMediaLogServiceAsBinder;
120static sp<IMediaLogService> sMediaLogService;
121
122static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
123
124static void sMediaLogInit()
125{
126 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
127 if (sMediaLogServiceAsBinder != 0) {
128 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
129 }
130}
131
jiabin57303cc2018-12-18 15:45:57 -0800132// Keep a strong reference to external vibrator service
133static sp<os::IExternalVibratorService> sExternalVibratorService;
134
135static sp<os::IExternalVibratorService> getExternalVibratorService() {
136 if (sExternalVibratorService == 0) {
137 sp <IBinder> binder = defaultServiceManager()->getService(
138 String16("external_vibrator_service"));
139 if (binder != 0) {
140 sExternalVibratorService =
141 interface_cast<os::IExternalVibratorService>(binder);
142 }
143 }
144 return sExternalVibratorService;
145}
146
Mathias Agopian65ab4712010-07-14 17:59:35 -0700147// ----------------------------------------------------------------------------
148
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700149std::string formatToString(audio_format_t format) {
150 std::string result;
151 FormatConverter::toString(format, result);
152 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800153}
154
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155// ----------------------------------------------------------------------------
156
157AudioFlinger::AudioFlinger()
158 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800159 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800160 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800161 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700162 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800163 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800164 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700165 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800166 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700167 mBtNrecIsOff(false),
168 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700169 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800170 mTotalMemory(0),
171 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700172 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700173 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800174 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700175 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700176{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700177 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
178 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
179 // zero ID has a special meaning, so unavailable
180 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
181 }
182
Glenn Kastenae0cff12016-02-24 13:57:49 -0800183 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800184 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800185 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
186 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700187 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800188 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700189
Wei Jia3f273d12015-11-24 09:06:49 -0800190 // reset battery stats.
191 // if the audio service has crashed, battery stats could be left
192 // in bad state, reset the state upon service start.
193 BatteryNotifier::getInstance().noteResetAudio();
194
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700195 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700196 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
197
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800198 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700199 std::vector<pid_t> halPids;
200 mDevicesFactoryHal->getHalPids(&halPids);
201 TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800202
203 // Notify that we have started (also called when audioserver service restarts)
204 mediametrics::LogItem(mMetricsId)
205 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
206 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700207}
208
209void AudioFlinger::onFirstRef()
210{
Eric Laurent93575202011-01-18 18:39:02 -0800211 Mutex::Autolock _l(mLock);
212
Dima Zavin799a70e2011-04-18 16:57:27 -0700213 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 char val_str[PROPERTY_VALUE_MAX] = { 0 };
215 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
216 uint32_t int_val;
217 if (1 == sscanf(val_str, "%u", &int_val)) {
218 mStandbyTimeInNsecs = milliseconds(int_val);
219 ALOGI("Using %u mSec as standby time.", int_val);
220 } else {
221 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
222 ALOGI("Using default %u mSec as standby time.",
223 (uint32_t)(mStandbyTimeInNsecs / 1000000));
224 }
225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226
Eric Laurenta4c5a552012-03-29 10:12:40 -0700227 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800228
229 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700230}
231
Eric Laurent42896a02019-09-27 15:40:33 -0700232status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
233 TimeCheck::setAudioHalPids(pids);
234 return NO_ERROR;
235}
236
Mathias Agopian65ab4712010-07-14 17:59:35 -0700237AudioFlinger::~AudioFlinger()
238{
239 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700240 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700241 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242 }
243 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700244 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700245 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246 }
Andy Hungb4946b62019-03-14 11:19:28 -0700247 while (!mMmapThreads.isEmpty()) {
248 const audio_io_handle_t io = mMmapThreads.keyAt(0);
249 if (mMmapThreads.valueAt(0)->isOutput()) {
250 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
251 } else {
252 closeInput_nonvirtual(io); // removes entry from mMmapThreads
253 }
254 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700255
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800256 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
257 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700258 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700260
261 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700262 if (sMediaLogService != 0) {
263 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
264 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
265 mUnregisteredWriters.pop();
266 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700267 }
268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700269}
270
Eric Laurentfc235202016-12-20 18:48:17 -0800271//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800272__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800273status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
274 const audio_attributes_t *attr,
275 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700276 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800277 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800278 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800279 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700280 sp<MmapStreamInterface>& interface,
281 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800282{
283 sp<AudioFlinger> af;
284 {
285 Mutex::Autolock _l(gLock);
286 af = gAudioFlinger.promote();
287 }
288 status_t ret = NO_INIT;
289 if (af != 0) {
290 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800291 direction, attr, config, client, deviceId,
292 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800293 }
294 return ret;
295}
296
Eric Laurent6acd1d42017-01-04 14:23:29 -0800297status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
298 const audio_attributes_t *attr,
299 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700300 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800301 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800302 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800303 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700304 sp<MmapStreamInterface>& interface,
305 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800306{
307 status_t ret = initCheck();
308 if (ret != NO_ERROR) {
309 return ret;
310 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800311 audio_session_t actualSessionId = *sessionId;
312 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
313 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
314 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800315 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700316 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800317 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700318 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800319 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
320 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
321 fullConfig.sample_rate = config->sample_rate;
322 fullConfig.channel_mask = config->channel_mask;
323 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800324 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700325
326 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800327 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200328 &streamType, client.clientPid, client.clientUid,
Ricardo Correaac26cf72020-01-06 14:43:38 -0800329 client.packageName, &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800330 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
331 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800332 deviceId, &portId, &secondaryOutputs);
333 ALOGW_IF(!secondaryOutputs.empty(),
334 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800335 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700336 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700337 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800338 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800339 client.clientPid,
340 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800341 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800342 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700343 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800344 }
345 if (ret != NO_ERROR) {
346 return ret;
347 }
348
349 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
350 // audio policy manager and we can retrieve it
351 sp<MmapThread> thread = mMmapThreads.valueFor(io);
352 if (thread != 0) {
353 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700354 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700355 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800356 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800357 config->sample_rate = thread->sampleRate();
358 config->channel_mask = thread->channelMask();
359 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800360 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700361 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700362 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700363 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800364 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700365 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800366 ret = NO_INIT;
367 }
368
369 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
370
Eric Laurentfc235202016-12-20 18:48:17 -0800371 return ret;
372}
373
jiabin57303cc2018-12-18 15:45:57 -0800374/* static */
375int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
376 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
377 if (evs != 0) {
378 int32_t ret;
379 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
380 if (status.isOk()) {
381 return ret;
382 }
383 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800384 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800385}
386
387/* static */
388void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
389 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
390 if (evs != 0) {
391 evs->onExternalVibrationStop(*externalVibration);
392 }
393}
394
Eric Laurentb82e6b72019-11-22 17:25:04 -0800395status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
396 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
397 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
398 if (audioHwDevice == nullptr) {
399 return NO_INIT;
400 }
401 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
402}
403
404status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
405 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
406 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
407 if (audioHwDevice == nullptr) {
408 return NO_INIT;
409 }
410 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
411}
412
Eric Laurenta4c5a552012-03-29 10:12:40 -0700413static const char * const audio_interfaces[] = {
414 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
415 AUDIO_HARDWARE_MODULE_ID_A2DP,
416 AUDIO_HARDWARE_MODULE_ID_USB,
417};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700418
Phil Burk062e67a2015-02-11 13:40:50 -0800419AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700420 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700421 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700422{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700423 // if module is 0, the request comes from an old policy manager and we should load
424 // well known modules
425 if (module == 0) {
426 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700427 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700428 loadHwModule_l(audio_interfaces[i]);
429 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700430 // then try to find a module supporting the requested device.
431 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
432 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700433 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
434 uint32_t supportedDevices;
435 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700436 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700437 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700438 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700439 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700440 } else {
441 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700442 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
443 if (audioHwDevice != NULL) {
444 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700445 }
446 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700447
Dima Zavin799a70e2011-04-18 16:57:27 -0700448 return NULL;
449}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450
Glenn Kasten0f11b512014-01-31 16:18:54 -0800451void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 String8 result;
454
455 result.append("Clients:\n");
456 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800457 sp<Client> client = mClients.valueAt(i).promote();
458 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800459 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 }
461 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700462
Eric Laurentd1b28d42013-09-18 18:47:13 -0700463 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800464 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700465 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800466 const pid_t pid = mNotificationClients[i]->getPid();
467 const uid_t uid = mNotificationClients[i]->getUid();
468 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
469 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700470 }
471
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700472 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800473 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700474 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
475 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800476 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
477 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
478 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700479 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481}
482
483
Glenn Kasten0f11b512014-01-31 16:18:54 -0800484void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485{
486 const size_t SIZE = 256;
487 char buffer[SIZE];
488 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800489 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490
John Grossman4ff14ba2012-02-08 16:37:41 -0800491 snprintf(buffer, SIZE, "Hardware status: %d\n"
492 "Standby Time mSec: %u\n",
493 hardwareStatus,
494 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 result.append(buffer);
496 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497}
498
Glenn Kasten0f11b512014-01-31 16:18:54 -0800499void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500{
501 const size_t SIZE = 256;
502 char buffer[SIZE];
503 String8 result;
504 snprintf(buffer, SIZE, "Permission Denial: "
505 "can't dump AudioFlinger from pid=%d, uid=%d\n",
506 IPCThreadState::self()->getCallingPid(),
507 IPCThreadState::self()->getCallingUid());
508 result.append(buffer);
509 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510}
511
Eric Laurent81784c32012-11-19 14:55:58 -0800512bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700514 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
515 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700516}
517
518status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
519{
Glenn Kasten44deb052012-02-05 18:09:08 -0800520 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700521 dumpPermissionDenial(fd, args);
522 } else {
523 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800524 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525 if (!hardwareLocked) {
526 String8 result(kHardwareLockedString);
527 write(fd, result.string(), result.size());
528 } else {
529 mHardwareLock.unlock();
530 }
531
Eric Tan7b651152018-07-13 10:17:19 -0700532 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533
534 // failed to lock - AudioFlinger is probably deadlocked
535 if (!locked) {
536 String8 result(kDeadlockedString);
537 write(fd, result.string(), result.size());
538 }
539
Eric Laurent021cf962014-05-13 10:18:14 -0700540 bool clientLocked = dumpTryLock(mClientLock);
541 if (!clientLocked) {
542 String8 result(kClientLockedString);
543 write(fd, result.string(), result.size());
544 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700545
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700546 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700547 mEffectsFactoryHal->dumpEffects(fd);
548 } else {
549 String8 result(kNoEffectsFactory);
550 write(fd, result.string(), result.size());
551 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700552
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700554 if (clientLocked) {
555 mClientLock.unlock();
556 }
557
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 dumpInternals(fd, args);
559
560 // dump playback threads
561 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
562 mPlaybackThreads.valueAt(i)->dump(fd, args);
563 }
564
565 // dump record threads
566 for (size_t i = 0; i < mRecordThreads.size(); i++) {
567 mRecordThreads.valueAt(i)->dump(fd, args);
568 }
569
Eric Laurent6acd1d42017-01-04 14:23:29 -0800570 // dump mmap threads
571 for (size_t i = 0; i < mMmapThreads.size(); i++) {
572 mMmapThreads.valueAt(i)->dump(fd, args);
573 }
574
Eric Laurentaaa44472014-09-12 17:41:50 -0700575 // dump orphan effect chains
576 if (mOrphanEffectChains.size() != 0) {
577 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
578 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
579 mOrphanEffectChains.valueAt(i)->dump(fd, args);
580 }
581 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700582 // dump all hardware devs
583 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700584 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
585 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700587
Mikhail Naganov201369b2018-05-16 16:52:32 -0700588 mPatchPanel.dump(fd);
589
Eric Laurentb82e6b72019-11-22 17:25:04 -0800590 mDeviceEffectManager.dump(fd);
591
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700592 // dump external setParameters
593 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
594 dprintf(fd, "\n%s setParameters:\n", name);
595 logger.dump(fd, " " /* prefix */);
596 };
597 dumpLogger(mRejectedSetParameterLog, "Rejected");
598 dumpLogger(mAppSetParameterLog, "App");
599 dumpLogger(mSystemSetParameterLog, "System");
600
Andy Hunga8115dc2018-08-24 15:51:59 -0700601 // dump historical threads in the last 10 seconds
602 const std::string threadLog = mThreadLog.dumpToString(
603 "Historical Thread Log ", 0 /* lines */,
604 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
605 write(fd, threadLog.c_str(), threadLog.size());
606
rago3bd1c872016-09-26 12:58:14 -0700607 BUFLOG_RESET;
608
Glenn Kastend65d73c2012-06-22 17:21:07 -0700609 if (locked) {
610 mLock.unlock();
611 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800612
Andy Hung8946a282018-04-19 20:04:56 -0700613#ifdef TEE_SINK
614 // NBAIO_Tee dump is safe to call outside of AF lock.
615 NBAIO_Tee::dumpAll(fd, "_DUMP");
616#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800617 // append a copy of media.log here by forwarding fd to it, but don't attempt
618 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700619 if (sMediaLogServiceAsBinder != 0) {
620 dprintf(fd, "\nmedia.log:\n");
621 Vector<String16> args;
622 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800623 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700624
625 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700626 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700627 bool unreachableMemory = false;
628 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700629 if (arg == String16("-m")) {
630 dumpMem = true;
631 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700632 unreachableMemory = true;
633 }
634 }
635
Andy Hung07b745e2016-05-23 16:21:07 -0700636 if (dumpMem) {
637 dprintf(fd, "\nDumping memory:\n");
638 std::string s = dumpMemoryAddresses(100 /* limit */);
639 write(fd, s.c_str(), s.size());
640 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700641 if (unreachableMemory) {
642 dprintf(fd, "\nDumping unreachable memory:\n");
643 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700644 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700645 write(fd, s.c_str(), s.size());
646 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647 }
648 return NO_ERROR;
649}
650
Eric Laurent021cf962014-05-13 10:18:14 -0700651sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800652{
Eric Laurent021cf962014-05-13 10:18:14 -0700653 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800654 // If pid is already in the mClients wp<> map, then use that entry
655 // (for which promote() is always != 0), otherwise create a new entry and Client.
656 sp<Client> client = mClients.valueFor(pid).promote();
657 if (client == 0) {
658 client = new Client(this, pid);
659 mClients.add(pid, client);
660 }
661
662 return client;
663}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664
Glenn Kasten9e58b552013-01-18 15:09:48 -0800665sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
666{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700667 // If there is no memory allocated for logs, return a dummy writer that does nothing.
668 // Similarly if we can't contact the media.log service, also return a dummy writer.
669 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800670 return new NBLog::Writer();
671 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700672 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
673 // If allocation fails, consult the vector of previously unregistered writers
674 // and garbage-collect one or more them until an allocation succeeds
675 if (shared == 0) {
676 Mutex::Autolock _l(mUnregisteredWritersLock);
677 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
678 {
679 // Pick the oldest stale writer to garbage-collect
680 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
681 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700682 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700683 // Now the media.log remote reference to IMemory is gone. When our last local
684 // reference to IMemory also drops to zero at end of this block,
685 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
686 }
687 // Re-attempt the allocation
688 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
689 if (shared != 0) {
690 goto success;
691 }
692 }
693 // Even after garbage-collecting all old writers, there is still not enough memory,
694 // so return a dummy writer
695 return new NBLog::Writer();
696 }
697success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700698 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800699 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
700 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700701 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800702 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800703}
704
705void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
706{
Glenn Kasten685ef092013-02-04 08:15:34 -0800707 if (writer == 0) {
708 return;
709 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800710 sp<IMemory> iMemory(writer->getIMemory());
711 if (iMemory == 0) {
712 return;
713 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700714 // Rather than removing the writer immediately, append it to a queue of old writers to
715 // be garbage-collected later. This allows us to continue to view old logs for a while.
716 Mutex::Autolock _l(mUnregisteredWritersLock);
717 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800718}
719
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720// IAudioFlinger interface
721
Eric Laurent21da6472017-11-09 16:29:26 -0800722sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
723 CreateTrackOutput& output,
724 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725{
726 sp<PlaybackThread::Track> track;
727 sp<TrackHandle> trackHandle;
728 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800730 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800731 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800732 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733
Eric Laurent21da6472017-11-09 16:29:26 -0800734 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700735 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800736 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700737 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
738 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700739 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700740
Andy Hung4ef19fa2018-05-15 19:35:29 -0700741 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800742 ALOGW_IF(clientUid != callingUid,
743 "%s uid %d tried to pass itself off as %d",
744 __FUNCTION__, callingUid, clientUid);
745 clientUid = callingUid;
746 updatePid = true;
747 }
748 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700749 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800750 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800751 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700752 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800753 __func__, callingUid, callingPid, clientPid);
754 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700755 }
756
Eric Laurent21da6472017-11-09 16:29:26 -0800757 audio_session_t sessionId = input.sessionId;
758 if (sessionId == AUDIO_SESSION_ALLOCATE) {
759 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800760 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
761 lStatus = BAD_VALUE;
762 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800763 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800764
Eric Laurent21da6472017-11-09 16:29:26 -0800765 output.sessionId = sessionId;
766 output.outputId = AUDIO_IO_HANDLE_NONE;
767 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700768 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Ricardo Correaac26cf72020-01-06 14:43:38 -0800769 clientPid, clientUid, input.opPackageName,
770 &input.config, input.flags, &output.selectedDeviceId,
771 &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800772
773 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
774 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
775 goto Exit;
776 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800777 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
778 // but if someone uses binder directly they could bypass that and cause us to crash
779 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000780 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 lStatus = BAD_VALUE;
782 goto Exit;
783 }
784
Glenn Kasten53b5d092014-02-05 10:00:23 -0800785 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800786 if (!audio_is_output_channel(input.config.channel_mask)) {
787 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800788 lStatus = BAD_VALUE;
789 goto Exit;
790 }
791
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700792 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800793 if (!audio_is_valid_format(input.config.format)) {
794 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700795 lStatus = BAD_VALUE;
796 goto Exit;
797 }
798
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799 {
800 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800801 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800803 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 lStatus = BAD_VALUE;
805 goto Exit;
806 }
807
Eric Laurent21da6472017-11-09 16:29:26 -0800808 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809
Glenn Kastene848bd92014-03-13 15:00:32 -0700810 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800811 // check if an effect chain with the same session ID is present on another
812 // output thread and move it here.
813 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
814 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
815 if (mPlaybackThreads.keyAt(i) != output.outputId) {
816 uint32_t sessions = t->hasAudioSession(sessionId);
817 if (sessions & ThreadBase::EFFECT_SESSION) {
818 effectThread = t.get();
819 break;
Eric Laurentde070132010-07-13 04:45:46 -0700820 }
821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822 }
Eric Laurent21da6472017-11-09 16:29:26 -0800823 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824
Eric Laurent21da6472017-11-09 16:29:26 -0800825 output.sampleRate = input.config.sample_rate;
826 output.frameCount = input.frameCount;
827 output.notificationFrameCount = input.notificationFrameCount;
828 output.flags = input.flags;
829
Eric Laurent42984412019-05-09 17:57:03 -0700830 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700831 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800832 &output.frameCount, &output.notificationFrameCount,
833 input.notificationsPerBuffer, input.speed,
834 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700835 callingPid, input.clientInfo.clientTid, clientUid,
836 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800837 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700838 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700839
Eric Laurent21da6472017-11-09 16:29:26 -0800840 output.afFrameCount = thread->frameCount();
841 output.afSampleRate = thread->sampleRate();
842 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800843 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800844
Kevin Rocard153f92d2018-12-18 18:33:28 -0800845 if (lStatus == NO_ERROR) {
846 // Connect secondary outputs. Failure on a secondary output must not imped the primary
847 // Any secondary output setup failure will lead to a desync between the AP and AF until
848 // the track is destroyed.
849 TeePatches teePatches;
850 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
851 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
852 if (secondaryThread == NULL) {
853 ALOGE("no playback thread found for secondary output %d", output.outputId);
854 continue;
855 }
856
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100857 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
858 / thread->sampleRate();
859 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
860 / secondaryThread->sampleRate();
861 // If the secondary output has just been opened, the first secondaryThread write
862 // will not block as it will fill the empty startup buffer of the HAL,
863 // so a second sink buffer needs to be ready for the immediate next blocking write.
864 // Additionally, have a margin of one main thread buffer as the scheduling jitter
865 // can reorder the writes (eg if thread A&B have the same write intervale,
866 // the scheduler could schedule AB...BA)
867 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
868 // Total secondary output buffer must be at least as the read frames plus
869 // the margin of a few buffers on both sides in case the
870 // threads scheduling has some jitter.
871 // That value should not impact latency as the secondary track is started before
872 // its buffer is full, see frameCountToBeReady.
873 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
874 // The frameCount should also not be smaller than the secondary thread min frame
875 // count
876 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
877 [&] { Mutex::Autolock _l(secondaryThread->mLock);
878 return secondaryThread->latency_l(); }(),
879 secondaryThread->mNormalFrameCount,
880 secondaryThread->mSampleRate,
881 output.sampleRate,
882 input.speed);
883 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800884
885 using namespace std::chrono_literals;
886 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
887 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
888 output.sampleRate,
889 inChannelMask,
890 input.config.format,
891 frameCount,
892 NULL /* buffer */,
893 (size_t)0 /* bufferSize */,
894 AUDIO_INPUT_FLAG_DIRECT,
895 0ns /* timeout */);
896 status_t status = patchRecord->initCheck();
897 if (status != NO_ERROR) {
898 ALOGE("Secondary output patchRecord init failed: %d", status);
899 continue;
900 }
Andy Hungae22b482019-05-09 15:38:55 -0700901
902 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
903 // for fast usage: thread has fast mixer, sample rate matches, etc.;
904 // for now, we exclude fast tracks by removing the Fast flag.
905 const audio_output_flags_t outputFlags =
906 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800907 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
908 streamType,
909 output.sampleRate,
910 input.config.channel_mask,
911 input.config.format,
912 frameCount,
913 patchRecord->buffer(),
914 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700915 outputFlags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100916 0ns /* timeout */,
917 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800918 status = patchTrack->initCheck();
919 if (status != NO_ERROR) {
920 ALOGE("Secondary output patchTrack init failed: %d", status);
921 continue;
922 }
923 teePatches.push_back({patchRecord, patchTrack});
924 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800925 // In case the downstream patchTrack on the secondaryThread temporarily outlives
926 // our created track, ensure the corresponding patchRecord is still alive.
927 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
928 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800929 }
930 track->setTeePatches(std::move(teePatches));
931 }
932
Eric Laurent39e94f82010-07-28 01:32:47 -0700933 // move effect chain to this output thread if an effect on same session was waiting
934 // for a track to be created
935 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700936 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700937 Mutex::Autolock _dl(thread->mLock);
938 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700939 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
940 effectThreadId = thread->id();
941 effectIds = thread->getEffectIds_l(sessionId);
942 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700943 }
Eric Laurenta011e352012-03-29 15:51:43 -0700944
945 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700946 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800947 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700948 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700949 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700950 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700951 } else {
952 mPendingSyncEvents[i]->cancel();
953 }
Eric Laurenta011e352012-03-29 15:51:43 -0700954 mPendingSyncEvents.removeAt(i);
955 i--;
956 }
957 }
958 }
Glenn Kastene198c362013-08-13 09:13:36 -0700959
Eric Laurent21da6472017-11-09 16:29:26 -0800960 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961 }
Glenn Kastene198c362013-08-13 09:13:36 -0700962
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700963 if (lStatus != NO_ERROR) {
964 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700965 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700966 // Don't hold mClientLock when releasing the reference on the track as the
967 // destructor will acquire it.
968 {
969 Mutex::Autolock _cl(mClientLock);
970 client.clear();
971 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700973 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974 }
975
Eric Laurent6c796322019-04-09 14:13:17 -0700976 // effectThreadId is not NONE if an effect chain corresponding to the track session
977 // was found on another thread and must be moved on this thread
978 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
979 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
980 }
981
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700982 // return handle to client
983 trackHandle = new TrackHandle(track);
984
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800986 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700987 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800988 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700989 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 return trackHandle;
991}
992
Glenn Kasten2c073da2016-02-26 09:14:08 -0800993uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994{
995 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800996 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800998 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999 return 0;
1000 }
1001 return thread->sampleRate();
1002}
1003
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001004audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005{
1006 Mutex::Autolock _l(mLock);
1007 PlaybackThread *thread = checkPlaybackThread_l(output);
1008 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001009 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001010 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 }
1012 return thread->format();
1013}
1014
Glenn Kasten2c073da2016-02-26 09:14:08 -08001015size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016{
1017 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001018 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001020 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 return 0;
1022 }
Glenn Kasten58912562012-04-03 10:45:00 -07001023 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1024 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 return thread->frameCount();
1026}
1027
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001028size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1029{
1030 Mutex::Autolock _l(mLock);
1031 ThreadBase *thread = checkThread_l(ioHandle);
1032 if (thread == NULL) {
1033 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1034 return 0;
1035 }
1036 return thread->frameCountHAL();
1037}
1038
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001039uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040{
1041 Mutex::Autolock _l(mLock);
1042 PlaybackThread *thread = checkPlaybackThread_l(output);
1043 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001044 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045 return 0;
1046 }
1047 return thread->latency();
1048}
1049
1050status_t AudioFlinger::setMasterVolume(float value)
1051{
Eric Laurenta1884f92011-08-23 08:25:03 -07001052 status_t ret = initCheck();
1053 if (ret != NO_ERROR) {
1054 return ret;
1055 }
1056
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 // check calling permissions
1058 if (!settingsAllowed()) {
1059 return PERMISSION_DENIED;
1060 }
1061
Eric Laurenta4c5a552012-03-29 10:12:40 -07001062 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001063 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001064
John Grossmanee578c02012-07-23 17:05:46 -07001065 // Set master volume in the HALs which support it.
1066 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1067 AutoMutex lock(mHardwareLock);
1068 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001069
John Grossmanee578c02012-07-23 17:05:46 -07001070 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1071 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001072 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -08001073 }
John Grossmanee578c02012-07-23 17:05:46 -07001074 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076
John Grossmanee578c02012-07-23 17:05:46 -07001077 // Now set the master volume in each playback thread. Playback threads
1078 // assigned to HALs which do not have master volume support will apply
1079 // master volume during the mix operation. Threads with HALs which do
1080 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001081 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1082 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1083 continue;
1084 }
John Grossmanee578c02012-07-23 17:05:46 -07001085 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087
1088 return NO_ERROR;
1089}
1090
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001091status_t AudioFlinger::setMasterBalance(float balance)
1092{
1093 status_t ret = initCheck();
1094 if (ret != NO_ERROR) {
1095 return ret;
1096 }
1097
1098 // check calling permissions
1099 if (!settingsAllowed()) {
1100 return PERMISSION_DENIED;
1101 }
1102
1103 // check range
1104 if (isnan(balance) || fabs(balance) > 1.f) {
1105 return BAD_VALUE;
1106 }
1107
1108 Mutex::Autolock _l(mLock);
1109
1110 // short cut.
1111 if (mMasterBalance == balance) return NO_ERROR;
1112
1113 mMasterBalance = balance;
1114
1115 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1116 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1117 continue;
1118 }
1119 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1120 }
1121
1122 return NO_ERROR;
1123}
1124
Glenn Kastenf78aee72012-01-04 11:00:47 -08001125status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126{
Eric Laurenta1884f92011-08-23 08:25:03 -07001127 status_t ret = initCheck();
1128 if (ret != NO_ERROR) {
1129 return ret;
1130 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131
1132 // check calling permissions
1133 if (!settingsAllowed()) {
1134 return PERMISSION_DENIED;
1135 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001136 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001137 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138 return BAD_VALUE;
1139 }
1140
1141 { // scope for the lock
1142 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001143 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001145 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 mHardwareStatus = AUDIO_HW_IDLE;
1147 }
1148
1149 if (NO_ERROR == ret) {
1150 Mutex::Autolock _l(mLock);
1151 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001152 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001153 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 }
1155
1156 return ret;
1157}
1158
1159status_t AudioFlinger::setMicMute(bool state)
1160{
Eric Laurenta1884f92011-08-23 08:25:03 -07001161 status_t ret = initCheck();
1162 if (ret != NO_ERROR) {
1163 return ret;
1164 }
1165
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 // check calling permissions
1167 if (!settingsAllowed()) {
1168 return PERMISSION_DENIED;
1169 }
1170
1171 AutoMutex lock(mHardwareLock);
1172 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001173 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001174 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1175 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001176 if (result != NO_ERROR) {
1177 ret = result;
1178 }
1179 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 mHardwareStatus = AUDIO_HW_IDLE;
1181 return ret;
1182}
1183
1184bool AudioFlinger::getMicMute() const
1185{
Eric Laurenta1884f92011-08-23 08:25:03 -07001186 status_t ret = initCheck();
1187 if (ret != NO_ERROR) {
1188 return false;
1189 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001190 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001191 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001192 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001194 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001195 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1196 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001197 if (result == NO_ERROR) {
1198 mute = mute && state;
1199 }
1200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001202
1203 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204}
1205
Eric Laurent5ada82e2019-08-29 17:53:54 -07001206void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001207{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001208 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001209
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001210 AutoMutex lock(mLock);
1211 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001212 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001213 }
1214 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001215 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001216 }
1217}
1218
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219status_t AudioFlinger::setMasterMute(bool muted)
1220{
John Grossmand8f178d2012-07-20 14:51:35 -07001221 status_t ret = initCheck();
1222 if (ret != NO_ERROR) {
1223 return ret;
1224 }
1225
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 // check calling permissions
1227 if (!settingsAllowed()) {
1228 return PERMISSION_DENIED;
1229 }
1230
John Grossmanee578c02012-07-23 17:05:46 -07001231 Mutex::Autolock _l(mLock);
1232 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001233
John Grossmanee578c02012-07-23 17:05:46 -07001234 // Set master mute in the HALs which support it.
1235 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1236 AutoMutex lock(mHardwareLock);
1237 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001238
John Grossmanee578c02012-07-23 17:05:46 -07001239 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1240 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001241 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001242 }
John Grossmanee578c02012-07-23 17:05:46 -07001243 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001244 }
1245
John Grossmanee578c02012-07-23 17:05:46 -07001246 // Now set the master mute in each playback thread. Playback threads
1247 // assigned to HALs which do not have master mute support will apply master
1248 // mute during the mix operation. Threads with HALs which do support master
1249 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001250 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1251 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1252 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254
1255 return NO_ERROR;
1256}
1257
1258float AudioFlinger::masterVolume() const
1259{
Glenn Kasten98067102011-12-13 11:47:54 -08001260 Mutex::Autolock _l(mLock);
1261 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262}
1263
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001264status_t AudioFlinger::getMasterBalance(float *balance) const
1265{
1266 Mutex::Autolock _l(mLock);
1267 *balance = getMasterBalance_l();
1268 return NO_ERROR; // if called through binder, may return a transactional error
1269}
1270
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271bool AudioFlinger::masterMute() const
1272{
Glenn Kasten98067102011-12-13 11:47:54 -08001273 Mutex::Autolock _l(mLock);
1274 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275}
1276
John Grossman4ff14ba2012-02-08 16:37:41 -08001277float AudioFlinger::masterVolume_l() const
1278{
John Grossman4ff14ba2012-02-08 16:37:41 -08001279 return mMasterVolume;
1280}
1281
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001282float AudioFlinger::getMasterBalance_l() const
1283{
1284 return mMasterBalance;
1285}
1286
John Grossmand8f178d2012-07-20 14:51:35 -07001287bool AudioFlinger::masterMute_l() const
1288{
John Grossmanee578c02012-07-23 17:05:46 -07001289 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001290}
1291
Eric Laurent223fd5c2014-11-11 13:43:36 -08001292status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1293{
1294 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001295 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001296 return BAD_VALUE;
1297 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001298 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1299 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1300 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001301 return PERMISSION_DENIED;
1302 }
1303
1304 return NO_ERROR;
1305}
1306
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001307status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1308 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309{
1310 // check calling permissions
1311 if (!settingsAllowed()) {
1312 return PERMISSION_DENIED;
1313 }
1314
Eric Laurent223fd5c2014-11-11 13:43:36 -08001315 status_t status = checkStreamType(stream);
1316 if (status != NO_ERROR) {
1317 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318 }
Eric Laurent98e38192018-02-15 18:31:53 -08001319 if (output == AUDIO_IO_HANDLE_NONE) {
1320 return BAD_VALUE;
1321 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001322 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1323 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001324
1325 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001326 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1327 if (volumeInterface == NULL) {
1328 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001329 }
Eric Laurent98e38192018-02-15 18:31:53 -08001330 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331
1332 return NO_ERROR;
1333}
1334
Glenn Kastenfff6d712012-01-12 16:38:12 -08001335status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336{
1337 // check calling permissions
1338 if (!settingsAllowed()) {
1339 return PERMISSION_DENIED;
1340 }
1341
Eric Laurent223fd5c2014-11-11 13:43:36 -08001342 status_t status = checkStreamType(stream);
1343 if (status != NO_ERROR) {
1344 return status;
1345 }
1346 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1347
1348 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001349 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350 return BAD_VALUE;
1351 }
1352
Eric Laurent93575202011-01-18 18:39:02 -08001353 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001355 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1356 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1357 volumeInterfaces[i]->setStreamMute(stream, muted);
1358 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359
1360 return NO_ERROR;
1361}
1362
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001363float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001365 status_t status = checkStreamType(stream);
1366 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001367 return 0.0f;
1368 }
Eric Laurent98e38192018-02-15 18:31:53 -08001369 if (output == AUDIO_IO_HANDLE_NONE) {
1370 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371 }
1372
Eric Laurent98e38192018-02-15 18:31:53 -08001373 AutoMutex lock(mLock);
1374 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1375 if (volumeInterface == NULL) {
1376 return 0.0f;
1377 }
1378
1379 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380}
1381
Glenn Kastenfff6d712012-01-12 16:38:12 -08001382bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001384 status_t status = checkStreamType(stream);
1385 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 return true;
1387 }
1388
Glenn Kasten6637baa2012-01-09 09:40:36 -08001389 AutoMutex lock(mLock);
1390 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391}
1392
Eric Laurent054d9d32015-04-24 08:48:48 -07001393
1394void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1395{
1396 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1397 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1398 }
1399}
1400
jiabinc52b1ff2019-10-31 17:20:42 -07001401void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1402{
1403 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1404 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1405 }
1406}
1407
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001408// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1409void AudioFlinger::forwardParametersToDownstreamPatches_l(
1410 audio_io_handle_t upStream, const String8& keyValuePairs,
1411 std::function<bool(const sp<PlaybackThread>&)> useThread)
1412{
1413 std::vector<PatchPanel::SoftwarePatch> swPatches;
1414 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1415 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1416 __func__, swPatches.size(), upStream);
1417 for (const auto& swPatch : swPatches) {
1418 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1419 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1420 downStream->setParameters(keyValuePairs);
1421 }
1422 }
1423}
1424
Eric Laurentf1047e82018-04-16 19:18:20 -07001425// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1426// Some keys are used for audio routing and audio path configuration and should be reserved for use
1427// by audio policy and audio flinger for functional, privacy and security reasons.
1428void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1429{
1430 static const String8 kReservedParameters[] = {
1431 String8(AudioParameter::keyRouting),
1432 String8(AudioParameter::keySamplingRate),
1433 String8(AudioParameter::keyFormat),
1434 String8(AudioParameter::keyChannels),
1435 String8(AudioParameter::keyFrameCount),
1436 String8(AudioParameter::keyInputSource),
1437 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001438 String8(AudioParameter::keyDeviceConnect),
1439 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001440 String8(AudioParameter::keyStreamSupportedFormats),
1441 String8(AudioParameter::keyStreamSupportedChannels),
1442 String8(AudioParameter::keyStreamSupportedSamplingRates),
1443 };
1444
Andy Hung4ef19fa2018-05-15 19:35:29 -07001445 if (isAudioServerUid(callingUid)) {
1446 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001447 }
1448
1449 AudioParameter param = AudioParameter(keyValuePairs);
1450 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001451 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001452 for (auto& key : kReservedParameters) {
1453 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001454 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001455 param.remove(key);
1456 }
1457 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001458 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1459 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001460 keyValuePairs = param.toString();
1461}
1462
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001463void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1464 size_t rejectedKVPSize, const String8& rejectedKVPs,
1465 uid_t callingUid) {
1466 auto prefix = String8::format("UID %5d", callingUid);
1467 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1468 if (rejectedKVPSize != 0) {
1469 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1470 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1471 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1472 } else {
1473 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1474 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1475 }
1476}
1477
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001478status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479{
Eric Laurentf1047e82018-04-16 19:18:20 -07001480 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1481 ioHandle, keyValuePairs.string(),
1482 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001483
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 // check calling permissions
1485 if (!settingsAllowed()) {
1486 return PERMISSION_DENIED;
1487 }
1488
Eric Laurentf1047e82018-04-16 19:18:20 -07001489 String8 filteredKeyValuePairs = keyValuePairs;
1490 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1491
1492 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1493
Glenn Kasten142f5192014-03-25 17:44:59 -07001494 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1495 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001496 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001497 // result will remain NO_INIT if no audio device is present
1498 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001499 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001500 AutoMutex lock(mHardwareLock);
1501 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1502 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001503 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001504 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001505 // return success if at least one audio device accepts the parameters as not all
1506 // HALs are requested to support all parameters. If no audio device supports the
1507 // requested parameters, the last error is reported.
1508 if (final_result != NO_ERROR) {
1509 final_result = result;
1510 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001511 }
1512 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001513 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001514 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001515 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001516 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001517 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1518 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001519 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001520 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001521 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001522 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001523 }
1524 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001525 String8 screenState;
1526 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001527 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001528 if (isOff != (AudioFlinger::mScreenState & 1)) {
1529 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001530 }
1531 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001532 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 }
1534
1535 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1536 // and the thread is exited once the lock is released
1537 sp<ThreadBase> thread;
1538 {
1539 Mutex::Autolock _l(mLock);
1540 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001541 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001543 if (thread == 0) {
1544 thread = checkMmapThread_l(ioHandle);
1545 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001546 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001547 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001548 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001549 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001550 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1551 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001552 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001553 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 }
1555 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001556 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001557 status_t result = thread->setParameters(filteredKeyValuePairs);
1558 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1559 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 }
1561 return BAD_VALUE;
1562}
1563
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001564String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001566 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1567 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568
Eric Laurenta4c5a552012-03-29 10:12:40 -07001569 Mutex::Autolock _l(mLock);
1570
Glenn Kasten142f5192014-03-25 17:44:59 -07001571 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001572 String8 out_s8;
1573
Dima Zavin799a70e2011-04-18 16:57:27 -07001574 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001575 String8 s;
1576 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001577 {
1578 AutoMutex lock(mHardwareLock);
1579 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001580 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1581 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001582 mHardwareStatus = AUDIO_HW_IDLE;
1583 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001584 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001585 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001586 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 }
1588
Eric Laurent6acd1d42017-01-04 14:23:29 -08001589 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1590 if (thread == NULL) {
1591 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1592 if (thread == NULL) {
1593 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1594 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001595 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001596 }
1597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001599 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600}
1601
Glenn Kastendd8104c2012-07-02 12:42:44 -07001602size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1603 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604{
Eric Laurenta1884f92011-08-23 08:25:03 -07001605 status_t ret = initCheck();
1606 if (ret != NO_ERROR) {
1607 return 0;
1608 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001609 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001610 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001611 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001612 return 0;
1613 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001614
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001615 AutoMutex lock(mHardwareLock);
1616 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001617
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001618 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001619 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1620 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1621 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1622 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1623 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1624
1625 std::vector<audio_format_t> formats = {format};
1626 if (format != AUDIO_FORMAT_PCM_16_BIT)
1627 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1628
1629 std::vector<uint32_t> sampleRates = {sampleRate};
1630 static const uint32_t SR_44100 = 44100;
1631 static const uint32_t SR_48000 = 48000;
1632
1633 if (sampleRate != SR_48000)
1634 sampleRates.push_back(SR_48000);
1635 if (sampleRate != SR_44100)
1636 sampleRates.push_back(SR_44100);
1637
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001638 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001639
Robin Lee9899ff72019-12-24 22:02:08 +01001640 // Change parameters of the configuration each iteration until we find a
1641 // configuration that the device will support.
1642 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001643 for (auto testChannelMask : channelMasks) {
1644 config.channel_mask = testChannelMask;
1645 for (auto testFormat : formats) {
1646 config.format = testFormat;
1647 for (auto testSampleRate : sampleRates) {
1648 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001649
Judy Hsiaoabab5222019-11-09 18:14:58 +08001650 size_t bytes = 0;
1651 status_t result = dev->getInputBufferSize(&config, &bytes);
1652 if (result != OK || bytes == 0) {
1653 continue;
1654 }
1655
1656 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1657 config.format != format) {
1658 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1659 uint32_t srcChannelCount =
1660 audio_channel_count_from_in_mask(config.channel_mask);
1661 size_t srcFrames =
1662 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1663 size_t dstFrames = destinationFramesPossible(
1664 srcFrames, config.sample_rate, sampleRate);
1665 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1666 }
1667 return bytes;
1668 }
1669 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001670 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001671
1672 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1673 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1674 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675}
1676
Glenn Kasten5f972c02014-01-13 09:59:31 -08001677uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679 Mutex::Autolock _l(mLock);
1680
1681 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1682 if (recordThread != NULL) {
1683 return recordThread->getInputFramesLost();
1684 }
1685 return 0;
1686}
1687
1688status_t AudioFlinger::setVoiceVolume(float value)
1689{
Eric Laurenta1884f92011-08-23 08:25:03 -07001690 status_t ret = initCheck();
1691 if (ret != NO_ERROR) {
1692 return ret;
1693 }
1694
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 // check calling permissions
1696 if (!settingsAllowed()) {
1697 return PERMISSION_DENIED;
1698 }
1699
1700 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001701 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001702 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001703 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 mHardwareStatus = AUDIO_HW_IDLE;
1705
1706 return ret;
1707}
1708
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001709status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001710 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 Mutex::Autolock _l(mLock);
1713
1714 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1715 if (playbackThread != NULL) {
1716 return playbackThread->getRenderPosition(halFrames, dspFrames);
1717 }
1718
1719 return BAD_VALUE;
1720}
1721
1722void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1723{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001725 if (client == 0) {
1726 return;
1727 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001728 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001729 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001730 {
1731 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001732 if (mNotificationClients.indexOfKey(pid) < 0) {
1733 sp<NotificationClient> notificationClient = new NotificationClient(this,
1734 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001735 pid,
1736 uid);
1737 ALOGV("registerClient() client %p, pid %d, uid %u",
1738 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739
Eric Laurent021cf962014-05-13 10:18:14 -07001740 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741
Marco Nelissen06b46062014-11-14 07:58:25 -08001742 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001743 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001744 }
1745 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746
Eric Laurent021cf962014-05-13 10:18:14 -07001747 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001748 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001749 // the config change is always sent from playback or record threads to avoid deadlock
1750 // with AudioSystem::gLock
1751 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001752 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001753 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001755 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001756 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 }
1758}
1759
1760void AudioFlinger::removeNotificationClient(pid_t pid)
1761{
Eric Laurent6c796322019-04-09 14:13:17 -07001762 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001763 {
Eric Laurent6c796322019-04-09 14:13:17 -07001764 Mutex::Autolock _l(mLock);
1765 {
1766 Mutex::Autolock _cl(mClientLock);
1767 mNotificationClients.removeItem(pid);
1768 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001769
Eric Laurent6c796322019-04-09 14:13:17 -07001770 ALOGV("%d died, releasing its sessions", pid);
1771 size_t num = mAudioSessionRefs.size();
1772 bool removed = false;
1773 for (size_t i = 0; i < num; ) {
1774 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1775 ALOGV(" pid %d @ %zu", ref->mPid, i);
1776 if (ref->mPid == pid) {
1777 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1778 mAudioSessionRefs.removeAt(i);
1779 delete ref;
1780 removed = true;
1781 num--;
1782 } else {
1783 i++;
1784 }
1785 }
1786 if (removed) {
1787 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001788 }
1789 }
Eric Laurent6c796322019-04-09 14:13:17 -07001790 for (auto& effect : removedEffects) {
1791 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793}
1794
Eric Laurent73e26b62015-04-27 16:55:58 -07001795void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001796 const sp<AudioIoDescriptor>& ioDesc,
1797 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798{
Eric Laurent021cf962014-05-13 10:18:14 -07001799 Mutex::Autolock _l(mClientLock);
1800 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001802 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1803 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 }
1806}
1807
Eric Laurent021cf962014-05-13 10:18:14 -07001808// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809void AudioFlinger::removeClient_l(pid_t pid)
1810{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001811 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001812 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 mClients.removeItem(pid);
1814}
1815
Eric Laurent717e1282012-06-29 16:36:52 -07001816// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001817sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1818 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001819{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001820 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001821
1822 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001823 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001824 ALOG_ASSERT(thread == 0);
1825 thread = mPlaybackThreads.valueAt(i);
1826 }
1827 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001828 if (thread != nullptr) {
1829 return thread;
1830 }
1831 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1832 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1833 ALOG_ASSERT(thread == 0);
1834 thread = mRecordThreads.valueAt(i);
1835 }
1836 }
1837 if (thread != nullptr) {
1838 return thread;
1839 }
1840 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1841 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1842 ALOG_ASSERT(thread == 0);
1843 thread = mMmapThreads.valueAt(i);
1844 }
1845 }
Eric Laurent717e1282012-06-29 16:36:52 -07001846 return thread;
1847}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850
1851// ----------------------------------------------------------------------------
1852
1853AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1854 : RefBase(),
1855 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001856 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857{
Andy Hung6f248bb2018-01-23 14:04:37 -08001858 mMemoryDealer = new MemoryDealer(
1859 audioFlinger->getClientSharedHeapSize(),
1860 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
Eric Laurent021cf962014-05-13 10:18:14 -07001863// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864AudioFlinger::Client::~Client()
1865{
1866 mAudioFlinger->removeClient_l(mPid);
1867}
1868
Glenn Kasten435dbe62012-01-30 10:15:48 -08001869sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870{
1871 return mMemoryDealer;
1872}
1873
1874// ----------------------------------------------------------------------------
1875
1876AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1877 const sp<IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001878 pid_t pid,
1879 uid_t uid)
1880 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881{
1882}
1883
1884AudioFlinger::NotificationClient::~NotificationClient()
1885{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886}
1887
Glenn Kasten0f11b512014-01-31 16:18:54 -08001888void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889{
1890 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001891 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892}
1893
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001894// ----------------------------------------------------------------------------
1895AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1896 : mPendingRequests(false) {}
1897
1898
1899void AudioFlinger::MediaLogNotifier::requestMerge() {
1900 AutoMutex _l(mMutex);
1901 mPendingRequests = true;
1902 mCond.signal();
1903}
1904
1905bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001906 // Should already have been checked, but just in case
1907 if (sMediaLogService == 0) {
1908 return false;
1909 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001910 // Wait until there are pending requests
1911 {
1912 AutoMutex _l(mMutex);
1913 mPendingRequests = false; // to ignore past requests
1914 while (!mPendingRequests) {
1915 mCond.wait(mMutex);
1916 // TODO may also need an exitPending check
1917 }
1918 mPendingRequests = false;
1919 }
1920 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001921 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001922 usleep(kPostTriggerSleepPeriod);
1923 return true;
1924}
1925
1926void AudioFlinger::requestLogMerge() {
1927 mMediaLogNotifier->requestMerge();
1928}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929
1930// ----------------------------------------------------------------------------
1931
Eric Laurentf14db3c2017-12-08 14:20:36 -08001932sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1933 CreateRecordOutput& output,
1934 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935{
1936 sp<RecordThread::RecordTrack> recordTrack;
1937 sp<RecordHandle> recordHandle;
1938 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001940 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001941 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942
Eric Laurentf14db3c2017-12-08 14:20:36 -08001943 output.cblk.clear();
1944 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001945 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001946
Eric Laurentf14db3c2017-12-08 14:20:36 -08001947 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001948 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001949 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001950 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001951 ALOGW_IF(clientUid != callingUid,
1952 "%s uid %d tried to pass itself off as %d",
1953 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001954 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001955 updatePid = true;
1956 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001957 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001958 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001959 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001960 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001961 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001962 __func__, callingUid, callingPid, clientPid);
1963 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001964 }
1965
Andy Hung6770c6f2015-04-07 13:43:36 -07001966 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001967 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1968 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001969 lStatus = BAD_VALUE;
1970 goto Exit;
1971 }
1972
Glenn Kasten53b5d092014-02-05 10:00:23 -08001973 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001974 if (!audio_is_input_channel(input.config.channel_mask)) {
1975 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001976 lStatus = BAD_VALUE;
1977 goto Exit;
1978 }
1979
Eric Laurentf14db3c2017-12-08 14:20:36 -08001980 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1981 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1982 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1983 lStatus = BAD_VALUE;
1984 goto Exit;
1985 }
1986
1987 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001988 output.selectedDeviceId = input.selectedDeviceId;
1989 output.flags = input.flags;
1990
1991 client = registerPid(clientPid);
1992
1993 // Not a conventional loop, but a retry loop for at most two iterations total.
1994 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1995 // Exits loop via break on no error of got exit on error
1996 // The sp<> references will be dropped when re-entering scope.
1997 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1998 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001999 // release previously opened input if retrying.
2000 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2001 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002002 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002003 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002004 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002005 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002006 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002007 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002008 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002009 sessionId,
2010 // FIXME compare to AudioTrack
2011 clientPid,
2012 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08002013 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002014 &input.config,
2015 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002016 if (lStatus != NO_ERROR) {
2017 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2018 goto Exit;
2019 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002020
Glenn Kasten05997e22014-03-13 15:08:33 -07002021 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002023 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 if (thread == NULL) {
jiabinc1de2df2019-05-07 14:26:40 -07002025 ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 lStatus = BAD_VALUE;
2027 goto Exit;
2028 }
2029
Eric Laurentf14db3c2017-12-08 14:20:36 -08002030 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031
Eric Laurentf14db3c2017-12-08 14:20:36 -08002032 output.sampleRate = input.config.sample_rate;
2033 output.frameCount = input.frameCount;
2034 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002035
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002036 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002037 input.config.format, input.config.channel_mask,
2038 &output.frameCount, sessionId,
2039 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002040 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002041 input.clientInfo.clientTid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002042 &lStatus, portId,
2043 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002044 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002045
Eric Laurentf14db3c2017-12-08 14:20:36 -08002046 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2047 // audio policy manager without FAST constraint
2048 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002049 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002050 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002051
2052 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002053 goto Exit;
2054 }
2055
2056 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2057 // session and move it to this thread.
2058 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2059 if (chain != 0) {
2060 Mutex::Autolock _l(thread->mLock);
2061 thread->addEffectChain_l(chain);
2062 }
2063 break;
2064 }
2065 // End of retry loop.
2066 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 }
Glenn Kastene198c362013-08-13 09:13:36 -07002068
Eric Laurentf14db3c2017-12-08 14:20:36 -08002069 output.cblk = recordTrack->getCblk();
2070 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002071 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002072
2073 // return handle to client
2074 recordHandle = new RecordHandle(recordTrack);
2075
2076Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002077 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002078 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002079 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002080 // Don't hold mClientLock when releasing the reference on the track as the
2081 // destructor will acquire it.
2082 {
2083 Mutex::Autolock _cl(mClientLock);
2084 client.clear();
2085 }
Eric Laurent896c9672017-12-08 14:08:45 -08002086 recordTrack.clear();
2087 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002088 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 }
2091
Glenn Kasten9156ef32013-08-06 15:39:08 -07002092 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 return recordHandle;
2094}
2095
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002096
2097
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098// ----------------------------------------------------------------------------
2099
Eric Laurenta4c5a552012-03-29 10:12:40 -07002100audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2101{
Eric Laurent44622db2014-08-01 19:00:33 -07002102 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002103 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002104 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002105 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002106 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002107 }
2108 Mutex::Autolock _l(mLock);
2109 return loadHwModule_l(name);
2110}
2111
2112// loadHwModule_l() must be called with AudioFlinger::mLock held
2113audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2114{
2115 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2116 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2117 ALOGW("loadHwModule() module %s already loaded", name);
2118 return mAudioHwDevs.keyAt(i);
2119 }
2120 }
2121
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002122 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002123
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002124 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002125 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002126 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002127 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002128 }
2129
2130 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002131 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002132 mHardwareStatus = AUDIO_HW_IDLE;
2133 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002134 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002135 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002136 }
2137
John Grossmanee578c02012-07-23 17:05:46 -07002138 // Check and cache this HAL's level of support for master mute and master
2139 // volume. If this is the first HAL opened, and it supports the get
2140 // methods, use the initial values provided by the HAL as the current
2141 // master mute and volume settings.
2142
2143 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2144 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002145 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002146
2147 if (0 == mAudioHwDevs.size()) {
2148 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002149 float mv;
2150 if (OK == dev->getMasterVolume(&mv)) {
2151 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002152 }
2153
2154 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002155 bool mm;
2156 if (OK == dev->getMasterMute(&mm)) {
2157 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002158 }
2159 }
2160
Eric Laurenta4c5a552012-03-29 10:12:40 -07002161 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002162 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002163 flags = static_cast<AudioHwDevice::Flags>(flags |
2164 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2165 }
2166
2167 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002168 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002169 flags = static_cast<AudioHwDevice::Flags>(flags |
2170 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2171 }
2172
Eric Laurenta4c5a552012-03-29 10:12:40 -07002173 mHardwareStatus = AUDIO_HW_IDLE;
2174 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002175 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002176 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2177 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2178 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002179
Glenn Kastena13cde92016-03-28 15:26:02 -07002180 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002181 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002182
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002183 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002184
2185 return handle;
2186
2187}
2188
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002189// ----------------------------------------------------------------------------
2190
Glenn Kasten3b16c762012-11-14 08:44:39 -08002191uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002192{
2193 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002194 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002195 return thread != NULL ? thread->sampleRate() : 0;
2196}
2197
Glenn Kastene33054e2012-11-14 12:54:39 -08002198size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002199{
2200 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002201 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002202 return thread != NULL ? thread->frameCountHAL() : 0;
2203}
2204
2205// ----------------------------------------------------------------------------
2206
Andy Hung6f248bb2018-01-23 14:04:37 -08002207status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002208{
2209 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002210 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002211 return PERMISSION_DENIED;
2212 }
2213 Mutex::Autolock _l(mLock);
2214 if (mIsDeviceTypeKnown) {
2215 return INVALID_OPERATION;
2216 }
2217 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002218 mTotalMemory = totalMemory;
2219 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2220 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2221 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2222 // though actual setting is determined through device configuration.
2223 constexpr int64_t GB = 1024 * 1024 * 1024;
2224 mClientSharedHeapSize =
2225 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2226 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2227 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2228 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2229 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002230 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002231
2232 // TODO: Cache the client shared heap size in a persistent property.
2233 // It's possible that a native process or Java service or app accesses audioserver
2234 // after it is registered by system server, but before AudioService updates
2235 // the memory info. This would occur immediately after boot or an audioserver
2236 // crash and restore. Before update from AudioService, the client would get the
2237 // minimum heap size.
2238
2239 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2240 (isLowRamDevice ? "true" : "false"),
2241 (long long)mTotalMemory,
2242 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002243 return NO_ERROR;
2244}
2245
Andy Hung6f248bb2018-01-23 14:04:37 -08002246size_t AudioFlinger::getClientSharedHeapSize() const
2247{
2248 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2249 if (heapSizeInBytes != 0) { // read-only property overrides all.
2250 return heapSizeInBytes;
2251 }
2252 return mClientSharedHeapSize;
2253}
2254
Mikhail Naganovdea53042018-04-26 13:10:21 -07002255status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2256{
2257 ALOGV(__func__);
2258
2259 audio_module_handle_t module;
2260 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2261 module = config->ext.device.hw_module;
2262 } else {
2263 module = config->ext.mix.hw_module;
2264 }
2265
2266 Mutex::Autolock _l(mLock);
2267 ssize_t index = mAudioHwDevs.indexOfKey(module);
2268 if (index < 0) {
2269 ALOGW("%s() bad hw module %d", __func__, module);
2270 return BAD_VALUE;
2271 }
2272
2273 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2274 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2275}
2276
Eric Laurent93c3d412014-08-01 14:48:35 -07002277audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2278{
2279 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002280
2281 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2282 if (index >= 0) {
2283 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2284 mHwAvSyncIds.valueAt(index), sessionId);
2285 return mHwAvSyncIds.valueAt(index);
2286 }
2287
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002288 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002289 if (dev == NULL) {
2290 return AUDIO_HW_SYNC_INVALID;
2291 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002292 String8 reply;
2293 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002294 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002295 param = AudioParameter(reply);
2296 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002297
2298 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002299 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002300 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2301 return AUDIO_HW_SYNC_INVALID;
2302 }
2303
2304 // allow only one session for a given HW A/V sync ID.
2305 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2306 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2307 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2308 value, mHwAvSyncIds.keyAt(i));
2309 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002310 break;
2311 }
2312 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002313
2314 mHwAvSyncIds.add(sessionId, value);
2315
2316 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2317 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2318 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002319 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002320 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002321 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002322 String8 keyValuePairs = param.toString();
2323 thread->setParameters(keyValuePairs);
2324 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2325 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002326 break;
2327 }
2328 }
2329
2330 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2331 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002332}
2333
Eric Laurent72e3f392015-05-20 14:43:50 -07002334status_t AudioFlinger::systemReady()
2335{
2336 Mutex::Autolock _l(mLock);
2337 ALOGI("%s", __FUNCTION__);
2338 if (mSystemReady) {
2339 ALOGW("%s called twice", __FUNCTION__);
2340 return NO_ERROR;
2341 }
2342 mSystemReady = true;
2343 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2344 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2345 thread->systemReady();
2346 }
2347 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2348 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2349 thread->systemReady();
2350 }
2351 return NO_ERROR;
2352}
2353
jiabin46a76fa2018-01-05 10:18:21 -08002354status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2355{
jiabin9ff780e2018-03-19 18:19:52 -07002356 AutoMutex lock(mHardwareLock);
2357 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2358 status_t status = dev->getMicrophones(microphones);
2359 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002360}
2361
Eric Laurentfa90e842014-10-17 18:12:31 -07002362// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2363void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2364{
2365 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2366 if (index >= 0) {
2367 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2368 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2369 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002370 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002371 String8 keyValuePairs = param.toString();
2372 thread->setParameters(keyValuePairs);
2373 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2374 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002375 }
2376}
2377
2378
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002379// ----------------------------------------------------------------------------
2380
Eric Laurent83b88082014-06-20 18:31:16 -07002381
Eric Laurent6acd1d42017-01-04 14:23:29 -08002382sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002383 audio_io_handle_t *output,
2384 audio_config_t *config,
2385 audio_devices_t deviceType,
2386 const String8& address,
2387 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002388{
jiabin43810402019-10-24 14:58:31 -07002389 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002390 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002391 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002392 }
2393
Eric Laurentcf2c0212014-07-25 16:20:43 -07002394 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002395 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2396 } else {
2397 // Audio Policy does not currently request a specific output handle.
2398 // If this is ever needed, see openInput_l() for example code.
2399 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2400 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002401 }
Eric Laurent83b88082014-06-20 18:31:16 -07002402
2403 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2404
Eric Laurent83b88082014-06-20 18:31:16 -07002405 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002406 // This if statement allows overriding the audio policy settings
2407 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2408 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2409 // Check only for Normal Mixing mode
2410 if (kEnableExtendedPrecision) {
2411 // Specify format (uncomment one below to choose)
2412 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2413 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2414 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2415 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002416 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002417 }
2418 if (kEnableExtendedChannels) {
2419 // Specify channel mask (uncomment one below to choose)
2420 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2421 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2422 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2423 }
Eric Laurent83b88082014-06-20 18:31:16 -07002424 }
2425
Phil Burk062e67a2015-02-11 13:40:50 -08002426 AudioStreamOut *outputStream = NULL;
2427 status_t status = outHwDev->openOutputStream(
2428 &outputStream,
2429 *output,
jiabin43810402019-10-24 14:58:31 -07002430 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002431 flags,
2432 config,
2433 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002434
2435 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002436
Phil Burk062e67a2015-02-11 13:40:50 -08002437 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002438 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2439 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002440 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002441 mMmapThreads.add(*output, thread);
2442 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2443 *output, thread.get());
2444 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002445 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002446 sp<PlaybackThread> thread;
2447 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002448 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002449 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2450 *output, thread.get());
2451 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2452 || !isValidPcmSinkFormat(config->format)
2453 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002454 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002455 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2456 *output, thread.get());
2457 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002458 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002459 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2460 *output, thread.get());
2461 }
2462 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002463 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002464 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002465 }
Eric Laurent83b88082014-06-20 18:31:16 -07002466 }
2467
2468 return 0;
2469}
2470
Eric Laurentcf2c0212014-07-25 16:20:43 -07002471status_t AudioFlinger::openOutput(audio_module_handle_t module,
2472 audio_io_handle_t *output,
2473 audio_config_t *config,
jiabin43810402019-10-24 14:58:31 -07002474 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002475 uint32_t *latencyMs,
2476 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477{
jiabin43810402019-10-24 14:58:31 -07002478 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002479 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002480 this, module,
jiabin43810402019-10-24 14:58:31 -07002481 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002482 config->sample_rate,
2483 config->format,
2484 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002485 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486
jiabin43810402019-10-24 14:58:31 -07002487 audio_devices_t deviceType = device->type();
2488 const String8 address = String8(device->address().c_str());
2489
2490 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002491 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002493
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 Mutex::Autolock _l(mLock);
2495
jiabin43810402019-10-24 14:58:31 -07002496 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002497 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002498 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2499 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2500 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501
Eric Laurent6acd1d42017-01-04 14:23:29 -08002502 // notify client processes of the new output creation
2503 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002504
Eric Laurent6acd1d42017-01-04 14:23:29 -08002505 // the first primary output opened designates the primary hw device
2506 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002507 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002508 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002509
Eric Laurent6acd1d42017-01-04 14:23:29 -08002510 AutoMutex lock(mHardwareLock);
2511 mHardwareStatus = AUDIO_HW_SET_MODE;
2512 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2513 mHardwareStatus = AUDIO_HW_IDLE;
2514 }
2515 } else {
2516 MmapThread *mmapThread = (MmapThread *)thread.get();
2517 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002518 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002519 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 }
2521
Eric Laurentcf2c0212014-07-25 16:20:43 -07002522 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523}
2524
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002525audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2526 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527{
2528 Mutex::Autolock _l(mLock);
2529 MixerThread *thread1 = checkMixerThread_l(output1);
2530 MixerThread *thread2 = checkMixerThread_l(output2);
2531
2532 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002533 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2534 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002535 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 }
2537
Glenn Kasteneeecb982016-02-26 10:44:04 -08002538 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002539 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 thread->addOutputTrack(thread2);
2541 mPlaybackThreads.add(id, thread);
2542 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002543 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 return id;
2545}
2546
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002547status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548{
Glenn Kastend96c5722012-04-25 13:44:49 -07002549 return closeOutput_nonvirtual(output);
2550}
2551
2552status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2553{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 // keep strong reference on the playback thread so that
2555 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002556 sp<PlaybackThread> playbackThread;
2557 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 {
2559 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002560 playbackThread = checkPlaybackThread_l(output);
2561 if (playbackThread != NULL) {
2562 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563
Andy Hungdc099c22018-09-18 13:46:39 -07002564 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002565
Eric Laurent6acd1d42017-01-04 14:23:29 -08002566 if (playbackThread->type() == ThreadBase::MIXER) {
2567 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2568 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2569 DuplicatingThread *dupThread =
2570 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2571 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2572 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002573 }
2574 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575
2576
Eric Laurent6acd1d42017-01-04 14:23:29 -08002577 mPlaybackThreads.removeItem(output);
2578 // save all effects to the default thread
2579 if (mPlaybackThreads.size()) {
2580 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2581 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002582 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583 Mutex::Autolock _dl(dstThread->mLock);
2584 Mutex::Autolock _sl(playbackThread->mLock);
2585 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2586 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002587 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002588 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002589 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 }
2591 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002592 } else {
2593 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2594 if (mmapThread == 0) {
2595 return BAD_VALUE;
2596 }
Andy Hungdc099c22018-09-18 13:46:39 -07002597 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002598 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002599 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002601 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2602 ioDesc->mIoHandle = output;
2603 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002604 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002606 // The thread entity (active unit of execution) is no longer running here,
2607 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608
Eric Laurent6acd1d42017-01-04 14:23:29 -08002609 if (playbackThread != 0) {
2610 playbackThread->exit();
2611 if (!playbackThread->isDuplicating()) {
2612 closeOutputFinish(playbackThread);
2613 }
2614 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002615 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002616 mmapThread->exit();
2617 AudioStreamOut *out = mmapThread->clearOutput();
2618 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2619 // from now on thread->mOutput is NULL
2620 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 }
2622 return NO_ERROR;
2623}
2624
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002625void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002626{
2627 AudioStreamOut *out = thread->clearOutput();
2628 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2629 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002630 delete out;
2631}
2632
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002633void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002634{
2635 mPlaybackThreads.removeItem(thread->mId);
2636 thread->exit();
2637 closeOutputFinish(thread);
2638}
2639
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002640status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641{
2642 Mutex::Autolock _l(mLock);
2643 PlaybackThread *thread = checkPlaybackThread_l(output);
2644
2645 if (thread == NULL) {
2646 return BAD_VALUE;
2647 }
2648
Steve Block3856b092011-10-20 11:56:00 +01002649 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 thread->suspend();
2651
2652 return NO_ERROR;
2653}
2654
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002655status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656{
2657 Mutex::Autolock _l(mLock);
2658 PlaybackThread *thread = checkPlaybackThread_l(output);
2659
2660 if (thread == NULL) {
2661 return BAD_VALUE;
2662 }
2663
Steve Block3856b092011-10-20 11:56:00 +01002664 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665
2666 thread->restore();
2667
2668 return NO_ERROR;
2669}
2670
Eric Laurentcf2c0212014-07-25 16:20:43 -07002671status_t AudioFlinger::openInput(audio_module_handle_t module,
2672 audio_io_handle_t *input,
2673 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002674 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002675 const String8& address,
2676 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002677 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678{
Eric Laurent83b88082014-06-20 18:31:16 -07002679 Mutex::Autolock _l(mLock);
2680
Glenn Kastene7d66712015-03-05 13:46:52 -08002681 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002682 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002683 }
2684
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002685 sp<ThreadBase> thread = openInput_l(
2686 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002687
2688 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002689 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002690 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002691 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002693 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002694}
Dima Zavin799a70e2011-04-18 16:57:27 -07002695
Eric Laurent6acd1d42017-01-04 14:23:29 -08002696sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002697 audio_io_handle_t *input,
2698 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002699 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002700 const String8& address,
2701 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002702 audio_input_flags_t flags,
2703 audio_devices_t outputDevice,
2704 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002705{
Glenn Kastene7d66712015-03-05 13:46:52 -08002706 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002707 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002708 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002709 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002710 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002711
Glenn Kasteneeecb982016-02-26 10:44:04 -08002712 // Audio Policy can request a specific handle for hardware hotword.
2713 // The goal here is not to re-open an already opened input.
2714 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002715 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002716 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2717 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2718 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2719 return 0;
2720 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2721 // This should not happen in a transient state with current design.
2722 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2723 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002724 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002725
Eric Laurentcf2c0212014-07-25 16:20:43 -07002726 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002727 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002728 sp<StreamInHalInterface> inStream;
2729 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002730 *input, devices, &halconfig, flags, address.string(), source,
2731 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002732 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2733 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002734 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002735 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002736 halconfig.sample_rate,
2737 halconfig.format,
2738 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002739 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002740 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002742 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002743 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002744 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002745 audio_is_linear_pcm(config->format) &&
2746 audio_is_linear_pcm(halconfig.format) &&
2747 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002748 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2749 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002750 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002751 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002752 inStream.clear();
2753 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002754 *input, devices, &halconfig, flags, address.string(), source,
2755 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002756 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 }
2758
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002759 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002760 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002761 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2762 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002763 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002764 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002765 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2766 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002767 return thread;
2768 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002769 // Start record thread
2770 // RecordThread requires both input and output device indication to forward to audio
2771 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002772 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002773 mRecordThreads.add(*input, thread);
2774 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2775 return thread;
2776 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 }
2778
Eric Laurentcf2c0212014-07-25 16:20:43 -07002779 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780 return 0;
2781}
2782
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002783status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784{
Glenn Kastend96c5722012-04-25 13:44:49 -07002785 return closeInput_nonvirtual(input);
2786}
2787
2788status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2789{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790 // keep strong reference on the record thread so that
2791 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002792 sp<RecordThread> recordThread;
2793 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 {
2795 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002796 recordThread = checkRecordThread_l(input);
2797 if (recordThread != 0) {
2798 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799
Andy Hungdc099c22018-09-18 13:46:39 -07002800 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002801
Eric Laurent6acd1d42017-01-04 14:23:29 -08002802 // If we still have effect chains, it means that a client still holds a handle
2803 // on at least one effect. We must either move the chain to an existing thread with the
2804 // same session ID or put it aside in case a new record thread is opened for a
2805 // new capture on the same session
2806 sp<EffectChain> chain;
2807 {
2808 Mutex::Autolock _sl(recordThread->mLock);
2809 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2810 // Note: maximum one chain per record thread
2811 if (effectChains.size() != 0) {
2812 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002813 }
2814 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002815 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002816 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002817 // This should only happen in case of overlap between one thread tear down and the
2818 // creation of its replacement
2819 size_t i;
2820 for (i = 0; i < mRecordThreads.size(); i++) {
2821 sp<RecordThread> t = mRecordThreads.valueAt(i);
2822 if (t == recordThread) {
2823 continue;
2824 }
2825 if (t->hasAudioSession(chain->sessionId()) != 0) {
2826 Mutex::Autolock _l(t->mLock);
2827 ALOGV("closeInput() found thread %d for effect session %d",
2828 t->id(), chain->sessionId());
2829 t->addEffectChain_l(chain);
2830 break;
2831 }
2832 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002833 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002834 if (i == mRecordThreads.size()) {
2835 putOrphanEffectChain_l(chain);
2836 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002837 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002838 mRecordThreads.removeItem(input);
2839 } else {
2840 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2841 if (mmapThread == 0) {
2842 return BAD_VALUE;
2843 }
Andy Hungdc099c22018-09-18 13:46:39 -07002844 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002845 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002846 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002847 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2848 ioDesc->mIoHandle = input;
2849 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 }
Eric Laurent83b88082014-06-20 18:31:16 -07002851 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2852 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002853 if (recordThread != 0) {
2854 closeInputFinish(recordThread);
2855 } else if (mmapThread != 0) {
2856 mmapThread->exit();
2857 AudioStreamIn *in = mmapThread->clearInput();
2858 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2859 // from now on thread->mInput is NULL
2860 delete in;
2861 }
Eric Laurent83b88082014-06-20 18:31:16 -07002862 return NO_ERROR;
2863}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002865void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002866{
2867 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002868 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002869 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002870 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002871 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002872}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002874void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002875{
2876 mRecordThreads.removeItem(thread->mId);
2877 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878}
2879
Glenn Kastend2304db2014-02-03 07:40:31 -08002880status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881{
2882 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002883 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884
2885 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2886 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002887 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002888 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002889 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2890 mMmapThreads[i]->invalidateTracks(stream);
2891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 return NO_ERROR;
2893}
2894
2895
Glenn Kasteneeecb982016-02-26 10:44:04 -08002896audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897{
Glenn Kasten9d003132016-04-06 14:38:09 -07002898 // This is a binder API, so a malicious client could pass in a bad parameter.
2899 // Check for that before calling the internal API nextUniqueId().
2900 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2901 ALOGE("newAudioUniqueId invalid use %d", use);
2902 return AUDIO_UNIQUE_ID_ALLOCATE;
2903 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002904 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905}
2906
Andy Hung8b0bfd92019-12-23 13:11:11 -08002907void AudioFlinger::acquireAudioSessionId(
2908 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002909{
2910 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002911 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002912 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002913 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08002914 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
2915 caller = pid; // check must match releaseAudioSessionId()
2916 }
2917 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
2918 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08002919 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002920
Eric Laurent021cf962014-05-13 10:18:14 -07002921 {
2922 Mutex::Autolock _cl(mClientLock);
2923 // Ignore requests received from processes not known as notification client. The request
2924 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2925 // called from a different pid leaving a stale session reference. Also we don't know how
2926 // to clear this reference if the client process dies.
2927 if (mNotificationClients.indexOfKey(caller) < 0) {
2928 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2929 return;
2930 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002931 }
2932
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002933 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002934 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002935 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002936 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2937 ref->mCnt++;
2938 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002939 return;
2940 }
2941 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08002942 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002943 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002944}
2945
Glenn Kastend848eb42016-03-08 13:42:11 -08002946void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002947{
Eric Laurent6c796322019-04-09 14:13:17 -07002948 std::vector< sp<EffectModule> > removedEffects;
2949 {
2950 Mutex::Autolock _l(mLock);
2951 pid_t caller = IPCThreadState::self()->getCallingPid();
2952 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2953 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08002954 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
2955 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002956 }
Eric Laurent6c796322019-04-09 14:13:17 -07002957 size_t num = mAudioSessionRefs.size();
2958 for (size_t i = 0; i < num; i++) {
2959 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2960 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2961 ref->mCnt--;
2962 ALOGV(" decremented refcount to %d", ref->mCnt);
2963 if (ref->mCnt == 0) {
2964 mAudioSessionRefs.removeAt(i);
2965 delete ref;
2966 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2967 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2968 }
2969 goto Exit;
2970 }
2971 }
2972 // If the caller is audioserver it is likely that the session being released was acquired
2973 // on behalf of a process not in notification clients and we ignore the warning.
2974 ALOGW_IF(!isAudioServerUid(callerUid),
2975 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002976 }
Eric Laurent6c796322019-04-09 14:13:17 -07002977
2978Exit:
2979 for (auto& effect : removedEffects) {
2980 effect->updatePolicyState();
2981 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002982}
2983
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002984bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2985{
2986 size_t num = mAudioSessionRefs.size();
2987 for (size_t i = 0; i < num; i++) {
2988 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2989 if (ref->mSessionid == audioSession) {
2990 return true;
2991 }
2992 }
2993 return false;
2994}
2995
Eric Laurent6c796322019-04-09 14:13:17 -07002996std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002997
Steve Block3856b092011-10-20 11:56:00 +01002998 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002999
3000 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003001 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003002
3003 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3004 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003005 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003006 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3007 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003008 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003009 chains.push(ec);
3010 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003011 }
3012 }
Eric Laurent6c796322019-04-09 14:13:17 -07003013
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003014 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3015 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003016 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003017 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3018 sp<EffectChain> ec = t->mEffectChains[j];
3019 chains.push(ec);
3020 }
3021 }
3022
Eric Laurent6c796322019-04-09 14:13:17 -07003023 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3024 sp<MmapThread> t = mMmapThreads.valueAt(i);
3025 Mutex::Autolock _l(t->mLock);
3026 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3027 sp<EffectChain> ec = t->mEffectChains[j];
3028 chains.push(ec);
3029 }
3030 }
3031
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003032 for (size_t i = 0; i < chains.size(); i++) {
3033 sp<EffectChain> ec = chains[i];
3034 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003035 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003036 if (t == 0) {
3037 continue;
3038 }
3039 size_t numsessionrefs = mAudioSessionRefs.size();
3040 bool found = false;
3041 for (size_t k = 0; k < numsessionrefs; k++) {
3042 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003043 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003044 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003045 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003046 found = true;
3047 break;
3048 }
3049 }
3050 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003051 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003052 // remove all effects from the chain
3053 while (ec->mEffects.size()) {
3054 sp<EffectModule> effect = ec->mEffects[0];
3055 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003056 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003057 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003058 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003059 }
Eric Laurent6c796322019-04-09 14:13:17 -07003060 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003061 }
3062 }
3063 }
Eric Laurent6c796322019-04-09 14:13:17 -07003064 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003065}
3066
Andy Hungdc099c22018-09-18 13:46:39 -07003067// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3068void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3069{
3070 audio_utils::FdToString fdToString;
3071 const int fd = fdToString.fd();
3072 if (fd >= 0) {
3073 thread->dump(fd, {} /* args */);
3074 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3075 }
3076}
3077
Glenn Kasteneeecb982016-02-26 10:44:04 -08003078// checkThread_l() must be called with AudioFlinger::mLock held
3079AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3080{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003081 ThreadBase *thread = checkMmapThread_l(ioHandle);
3082 if (thread == 0) {
3083 switch (audio_unique_id_get_use(ioHandle)) {
3084 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3085 thread = checkPlaybackThread_l(ioHandle);
3086 break;
3087 case AUDIO_UNIQUE_ID_USE_INPUT:
3088 thread = checkRecordThread_l(ioHandle);
3089 break;
3090 default:
3091 break;
3092 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003093 }
3094 return thread;
3095}
3096
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003098AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099{
Glenn Kastena1117922012-01-26 10:53:32 -08003100 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101}
3102
3103// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003104AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105{
3106 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003107 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108}
3109
3110// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003111AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112{
Glenn Kastena1117922012-01-26 10:53:32 -08003113 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114}
3115
Eric Laurent6acd1d42017-01-04 14:23:29 -08003116// checkMmapThread_l() must be called with AudioFlinger::mLock held
3117AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3118{
3119 return mMmapThreads.valueFor(io).get();
3120}
3121
3122
3123// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3124AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3125{
Eric Laurent7459b902017-04-19 18:10:41 -07003126 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003127 if (volumeInterface == nullptr) {
3128 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3129 if (mmapThread != nullptr) {
3130 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003131 MmapPlaybackThread *mmapPlaybackThread =
3132 static_cast<MmapPlaybackThread *>(mmapThread);
3133 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003134 }
3135 }
3136 }
3137 return volumeInterface;
3138}
3139
3140Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3141{
3142 Vector <VolumeInterface *> volumeInterfaces;
3143 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003144 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003145 }
3146 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3147 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003148 MmapPlaybackThread *mmapPlaybackThread =
3149 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3150 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003151 }
3152 }
3153 return volumeInterfaces;
3154}
3155
Glenn Kasteneeecb982016-02-26 10:44:04 -08003156audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157{
Glenn Kasten9d003132016-04-06 14:38:09 -07003158 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003159 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003160 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3161 for (int retry = 0; retry < maxRetries; retry++) {
3162 // The cast allows wraparound from max positive to min negative instead of abort
3163 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3164 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3165 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3166 // allow wrap by skipping 0 and -1 for session ids
3167 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3168 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3169 return (audio_unique_id_t) (base | use);
3170 }
3171 }
3172 // We have no way of recovering from wraparound
3173 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3174 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175}
3176
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003177AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003178{
3179 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3180 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003181 if(thread->isDuplicating()) {
3182 continue;
3183 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003184 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003185 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003186 return thread;
3187 }
3188 }
3189 return NULL;
3190}
3191
jiabinc52b1ff2019-10-31 17:20:42 -07003192DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003193{
3194 PlaybackThread *thread = primaryPlaybackThread_l();
3195
3196 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003197 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003198 }
3199
jiabinc52b1ff2019-10-31 17:20:42 -07003200 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003201}
3202
Glenn Kastena7335632016-06-09 17:09:53 -07003203AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3204{
3205 size_t minFrameCount = 0;
3206 PlaybackThread *minThread = NULL;
3207 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3208 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3209 if (!thread->isDuplicating()) {
3210 size_t frameCount = thread->frameCountHAL();
3211 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3212 (frameCount == minFrameCount && thread->hasFastMixer() &&
3213 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3214 minFrameCount = frameCount;
3215 minThread = thread;
3216 }
3217 }
3218 }
3219 return minThread;
3220}
3221
Eric Laurenta011e352012-03-29 15:51:43 -07003222sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003223 audio_session_t triggerSession,
3224 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003225 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003226 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003227{
3228 Mutex::Autolock _l(mLock);
3229
3230 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3231 status_t playStatus = NAME_NOT_FOUND;
3232 status_t recStatus = NAME_NOT_FOUND;
3233 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3234 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3235 if (playStatus == NO_ERROR) {
3236 return event;
3237 }
3238 }
3239 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3240 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3241 if (recStatus == NO_ERROR) {
3242 return event;
3243 }
3244 }
3245 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3246 mPendingSyncEvents.add(event);
3247 } else {
3248 ALOGV("createSyncEvent() invalid event %d", event->type());
3249 event.clear();
3250 }
3251 return event;
3252}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003253
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254// ----------------------------------------------------------------------------
3255// Effect management
3256// ----------------------------------------------------------------------------
3257
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003258sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3259 return mEffectsFactoryHal;
3260}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261
Glenn Kastenf587ba52012-01-26 16:25:10 -08003262status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263{
3264 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003265 if (mEffectsFactoryHal.get()) {
3266 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3267 } else {
3268 return -ENODEV;
3269 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270}
3271
Glenn Kastenf587ba52012-01-26 16:25:10 -08003272status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273{
3274 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003275 if (mEffectsFactoryHal.get()) {
3276 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3277 } else {
3278 return -ENODEV;
3279 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280}
3281
Glenn Kasten5e92a782012-01-30 07:40:52 -08003282status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003283 const effect_uuid_t *pTypeUuid,
3284 uint32_t preferredTypeFlag,
3285 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003287 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3288 return BAD_VALUE;
3289 }
3290
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003292
3293 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003294 return -ENODEV;
3295 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003297 status_t status = NO_ERROR;
3298 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3299 // If uuid is specified, request effect descriptor from that.
3300 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3301 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3302 // If uuid is not specified, look for an available implementation
3303 // of the required type instead.
3304
3305 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3306 effect_descriptor_t desc;
3307 desc.flags = 0; // prevent compiler warning
3308
3309 uint32_t numEffects = 0;
3310 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3311 if (status < 0) {
3312 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3313 return status;
3314 }
3315
3316 bool found = false;
3317 for (uint32_t i = 0; i < numEffects; i++) {
3318 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3319 if (status < 0) {
3320 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3321 continue;
3322 }
3323 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3324 // If matching type found save effect descriptor.
3325 found = true;
3326 *descriptor = desc;
3327
3328 // If there's no preferred flag or this descriptor matches the preferred
3329 // flag, success! If this descriptor doesn't match the preferred
3330 // flag, continue enumeration in case a better matching version of this
3331 // effect type is available. Note that this means if no effect with a
3332 // correct flag is found, the descriptor returned will correspond to the
3333 // last effect that at least had a matching type uuid (if any).
3334 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3335 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3336 break;
3337 }
3338 }
3339 }
3340
3341 if (!found) {
3342 status = NAME_NOT_FOUND;
3343 ALOGW("getEffectDescriptor(): Effect not found by type.");
3344 }
3345 } else {
3346 status = BAD_VALUE;
3347 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3348 }
3349 return status;
3350}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003352sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 effect_descriptor_t *pDesc,
3354 const sp<IEffectClient>& effectClient,
3355 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003356 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003357 audio_session_t sessionId,
Eric Laurentb82e6b72019-11-22 17:25:04 -08003358 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003359 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003360 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 status_t *status,
3362 int *id,
3363 int *enabled)
3364{
3365 status_t lStatus = NO_ERROR;
3366 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368
Eric Laurentb6436272016-12-07 19:24:50 -08003369 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003370 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003371 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3372 ALOGW_IF(pid != -1 && pid != callingPid,
3373 "%s uid %d pid %d tried to pass itself off as pid %d",
3374 __func__, callingUid, callingPid, pid);
3375 pid = callingPid;
3376 }
3377
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003378 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3379 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380
3381 if (pDesc == NULL) {
3382 lStatus = BAD_VALUE;
3383 goto Exit;
3384 }
3385
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003386 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003387 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003388 lStatus = NO_INIT;
3389 goto Exit;
3390 }
3391
Andy Hung6096dcd2019-03-13 13:20:30 -07003392 // check audio settings permission for global effects
3393 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3394 if (!settingsAllowed()) {
3395 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3396 lStatus = PERMISSION_DENIED;
3397 goto Exit;
3398 }
3399 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3400 if (!isAudioServerUid(callingUid)) {
3401 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3402 lStatus = PERMISSION_DENIED;
3403 goto Exit;
3404 }
3405
3406 if (io == AUDIO_IO_HANDLE_NONE) {
3407 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3408 lStatus = BAD_VALUE;
3409 goto Exit;
3410 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003411 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3412 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3413 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3414 lStatus = PERMISSION_DENIED;
3415 goto Exit;
3416 }
Eric Laurent94876032019-11-13 12:45:28 -08003417 if (io != AUDIO_IO_HANDLE_NONE) {
3418 ALOGE("%s: io handle should not be specified for device effect", __func__);
3419 lStatus = BAD_VALUE;
3420 goto Exit;
3421 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003422 } else {
3423 // general sessionId.
3424
3425 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3426 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3427 lStatus = BAD_VALUE;
3428 goto Exit;
3429 }
3430
3431 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3432 // to prevent creating an effect when one doesn't actually have track with that session?
3433 }
3434
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003436 // Get the full effect descriptor from the uuid/type.
3437 // If the session is the output mix, prefer an auxiliary effect,
3438 // otherwise no preference.
3439 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3440 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3441 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3442 if (lStatus < 0) {
3443 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3444 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445 }
3446
3447 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003448 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3450 lStatus = INVALID_OPERATION;
3451 goto Exit;
3452 }
3453
Eric Laurent59255e42011-07-27 19:49:51 -07003454 // check recording permission for visualizer
3455 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003456 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003457 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003458 lStatus = PERMISSION_DENIED;
3459 goto Exit;
3460 }
3461
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003463 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003464 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003465 // if the output returned by getOutputForEffect() is removed before we lock the
3466 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3467 // and we will exit safely
3468 io = AudioSystem::getOutputForEffect(&desc);
3469 ALOGV("createEffect got output %d", io);
3470 }
3471
3472 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473
Eric Laurentb82e6b72019-11-22 17:25:04 -08003474 if (sessionId == AUDIO_SESSION_DEVICE) {
3475 sp<Client> client = registerPid(pid);
3476 ALOGV("%s device type %d address %s", __func__, device.mType, device.getAddress());
3477 handle = mDeviceEffectManager.createEffect_l(
3478 &desc, device, client, effectClient, mPatchPanel.patches_l(),
3479 enabled, &lStatus);
3480 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3481 // remove local strong reference to Client with mClientLock held
3482 Mutex::Autolock _cl(mClientLock);
3483 client.clear();
3484 } else {
3485 // handle must be valid here, but check again to be safe.
3486 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3487 }
3488 goto Register;
3489 }
3490
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 // If output is not specified try to find a matching audio session ID in one of the
3492 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003493 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3494 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003495 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3496 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003497 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003498 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003499 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3500 if (io == AUDIO_IO_HANDLE_NONE) {
3501 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003503 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003504 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003505 }
Andy Hung444bb552019-03-14 17:06:39 -07003506
3507 // If you wish to create a Record preprocessing AudioEffect in Java,
3508 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3509 // Otherwise it will fail when created on a Playback thread by legacy
3510 // handling below. Ditto with Mmap, the associated Mmap track must be created
3511 // before creating the AudioEffect or the io handle must be specified.
3512 //
3513 // Detect if the effect is created after an AudioRecord is destroyed.
3514 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3515 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3516 " for session %d no longer exists",
3517 __func__, desc.name, sessionId);
3518 lStatus = PERMISSION_DENIED;
3519 goto Exit;
3520 }
3521
3522 // Legacy handling of creating an effect on an expired or made-up
3523 // session id. We think that it is a Playback effect.
3524 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003525 // If no output thread contains the requested session ID, default to
3526 // first output. The effect chain will be moved to the correct output
3527 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003528 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003529 io = mPlaybackThreads.keyAt(0);
3530 }
Steve Block3856b092011-10-20 11:56:00 +01003531 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003532 } else if (checkPlaybackThread_l(io) != nullptr) {
3533 // allow only one effect chain per sessionId on mPlaybackThreads.
3534 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3535 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3536 if (io == checkIo) continue;
3537 const uint32_t sessionType =
3538 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3539 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3540 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3541 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3542 android_errorWriteLog(0x534e4554, "123237974");
3543 lStatus = BAD_VALUE;
3544 goto Exit;
3545 }
3546 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003547 }
3548 ThreadBase *thread = checkRecordThread_l(io);
3549 if (thread == NULL) {
3550 thread = checkPlaybackThread_l(io);
3551 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003552 thread = checkMmapThread_l(io);
3553 if (thread == NULL) {
3554 ALOGE("createEffect() unknown output thread");
3555 lStatus = BAD_VALUE;
3556 goto Exit;
3557 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003558 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003559 } else {
3560 // Check if one effect chain was awaiting for an effect to be created on this
3561 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003562 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003563 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003564 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003565 thread->addEffectChain_l(chain);
3566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003568
Eric Laurent021cf962014-05-13 10:18:14 -07003569 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003571 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003572 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003573 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003574 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003575 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003576 // remove local strong reference to Client with mClientLock held
3577 Mutex::Autolock _cl(mClientLock);
3578 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003579 } else {
3580 // handle must be valid here, but check again to be safe.
3581 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 }
3584
Eric Laurentb82e6b72019-11-22 17:25:04 -08003585Register:
Eric Laurent6c796322019-04-09 14:13:17 -07003586 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3587 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003588 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003589 if (effect != nullptr) {
3590 status_t rStatus = effect->updatePolicyState();
3591 if (rStatus != NO_ERROR) {
3592 lStatus = rStatus;
3593 }
3594 }
3595 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003596 handle.clear();
3597 }
3598
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003600 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 return handle;
3602}
3603
Glenn Kastend848eb42016-03-08 13:42:11 -08003604status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003605 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003606{
Steve Block3856b092011-10-20 11:56:00 +01003607 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003608 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003609 Mutex::Autolock _l(mLock);
3610 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003611 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003612 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613 }
Eric Laurentde070132010-07-13 04:45:46 -07003614 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3615 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003616 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003617 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 }
Eric Laurentde070132010-07-13 04:45:46 -07003619 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3620 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003621 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003622 return BAD_VALUE;
3623 }
3624
3625 Mutex::Autolock _dl(dstThread->mLock);
3626 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003627 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628}
3629
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003630
3631void AudioFlinger::setEffectSuspended(int effectId,
3632 audio_session_t sessionId,
3633 bool suspended)
3634{
3635 Mutex::Autolock _l(mLock);
3636
3637 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3638 if (thread == nullptr) {
3639 return;
3640 }
3641 Mutex::Autolock _sl(thread->mLock);
3642 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3643 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3644}
3645
3646
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003647// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003648status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003649 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003650 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003651{
Steve Block3856b092011-10-20 11:56:00 +01003652 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003653 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003654
Eric Laurent59255e42011-07-27 19:49:51 -07003655 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003656 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003657 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003658 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003659 return INVALID_OPERATION;
3660 }
3661
Eric Laurent4c415062016-06-17 16:14:16 -07003662 // Check whether the destination thread and all effects in the chain are compatible
3663 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003664 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003665 " destination thread %p is not compatible with effects in the chain",
3666 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003667 return INVALID_OPERATION;
3668 }
3669
Eric Laurent39e94f82010-07-28 01:32:47 -07003670 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003671 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003672 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003673 // removed.
3674 srcThread->removeEffectChain_l(chain);
3675
3676 // transfer all effects one by one so that new effect chain is created on new thread with
3677 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003678 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003679 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003680 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003681 Vector< sp<EffectModule> > removed;
3682 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003683 while (effect != 0) {
3684 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003685 removed.add(effect);
3686 status = dstThread->addEffect_l(effect);
3687 if (status != NO_ERROR) {
3688 break;
3689 }
Eric Laurentec35a142011-10-05 17:42:25 -07003690 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3691 if (effect->state() == EffectModule::ACTIVE ||
3692 effect->state() == EffectModule::STOPPING) {
3693 effect->start();
3694 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003695 // if the move request is not received from audio policy manager, the effect must be
3696 // re-registered with the new strategy and output
3697 if (dstChain == 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003698 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003699 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003700 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003701 status = NO_INIT;
3702 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003703 }
3704 strategy = dstChain->strategy();
3705 }
Eric Laurentde070132010-07-13 04:45:46 -07003706 effect = chain->getEffectFromId_l(0);
3707 }
3708
Eric Laurent5baf2af2013-09-12 17:37:00 -07003709 if (status != NO_ERROR) {
3710 for (size_t i = 0; i < removed.size(); i++) {
3711 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003712 }
3713 }
3714
3715 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716}
3717
Eric Laurent6c796322019-04-09 14:13:17 -07003718status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3719 const sp<PlaybackThread>& dstThread,
3720 sp<PlaybackThread> *srcThread)
3721{
3722 status_t status = NO_ERROR;
3723 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003724 sp<PlaybackThread> thread =
3725 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003726
3727 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3728 Mutex::Autolock _dl(dstThread->mLock);
3729 Mutex::Autolock _sl(thread->mLock);
3730 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3731 sp<EffectChain> dstChain;
3732 if (srcChain == 0) {
3733 return INVALID_OPERATION;
3734 }
3735
3736 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3737 if (effect == 0) {
3738 return INVALID_OPERATION;
3739 }
3740 thread->removeEffect_l(effect);
3741 status = dstThread->addEffect_l(effect);
3742 if (status != NO_ERROR) {
3743 thread->addEffect_l(effect);
3744 status = INVALID_OPERATION;
3745 goto Exit;
3746 }
3747
Eric Laurent6b446ce2019-12-13 10:56:31 -08003748 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003749 if (dstChain == 0) {
3750 thread->addEffect_l(effect);
3751 status = INVALID_OPERATION;
3752 }
3753
3754Exit:
3755 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3756 if (effect->state() == EffectModule::ACTIVE ||
3757 effect->state() == EffectModule::STOPPING) {
3758 effect->start();
3759 }
3760 }
3761
3762 if (status == NO_ERROR && srcThread != nullptr) {
3763 *srcThread = thread;
3764 }
3765 return status;
3766}
3767
Eric Laurent5baf2af2013-09-12 17:37:00 -07003768bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003769{
3770 if (mGlobalEffectEnableTime != 0 &&
3771 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3772 return true;
3773 }
3774
3775 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3776 sp<EffectChain> ec =
3777 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003778 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003779 return true;
3780 }
3781 }
3782 return false;
3783}
3784
Eric Laurent5baf2af2013-09-12 17:37:00 -07003785void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003786{
3787 Mutex::Autolock _l(mLock);
3788
3789 mGlobalEffectEnableTime = systemTime();
3790
3791 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3792 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3793 if (t->mType == ThreadBase::OFFLOAD) {
3794 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3795 }
3796 }
3797
3798}
3799
Eric Laurentaaa44472014-09-12 17:41:50 -07003800status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3801{
Eric Laurentd8365c52017-07-16 15:27:05 -07003802 // clear possible suspended state before parking the chain so that it starts in default state
3803 // when attached to a new record thread
3804 chain->setEffectSuspended_l(FX_IID_AEC, false);
3805 chain->setEffectSuspended_l(FX_IID_NS, false);
3806
Glenn Kastend848eb42016-03-08 13:42:11 -08003807 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003808 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003809 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003810 if (index >= 0) {
3811 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3812 return ALREADY_EXISTS;
3813 }
3814 mOrphanEffectChains.add(session, chain);
3815 return NO_ERROR;
3816}
3817
3818sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3819{
3820 sp<EffectChain> chain;
3821 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003822 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003823 if (index >= 0) {
3824 chain = mOrphanEffectChains.valueAt(index);
3825 mOrphanEffectChains.removeItemsAt(index);
3826 }
3827 return chain;
3828}
3829
3830bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3831{
3832 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003833 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003834 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003835 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003836 if (index >= 0) {
3837 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003838 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003839 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003840 mOrphanEffectChains.removeItemsAt(index);
3841 }
3842 return true;
3843 }
3844 return false;
3845}
3846
3847
Mathias Agopian65ab4712010-07-14 17:59:35 -07003848// ----------------------------------------------------------------------------
3849
3850status_t AudioFlinger::onTransact(
3851 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3852{
3853 return BnAudioFlinger::onTransact(code, data, reply, flags);
3854}
3855
Glenn Kasten63238ef2015-03-02 15:50:29 -08003856} // namespace android