blob: d6f553bd41d9b1d7b2a56bd78d98e0e047fac6db [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
jiabin8cb192f2019-09-23 10:34:20 -070022// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23#define AUDIO_ARRAYS_STATIC_CHECK 1
24
Glenn Kasten153b9fe2013-07-15 11:23:36 -070025#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080026#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <math.h>
28#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/time.h>
31#include <sys/resource.h>
Mikhail Naganov3de4f262020-03-06 17:02:19 -080032#include <thread>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033
jiabin57303cc2018-12-18 15:45:57 -080034#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080035#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <binder/IServiceManager.h>
37#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070038#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070040#include <media/audiohal/DeviceHalInterface.h>
41#include <media/audiohal/DevicesFactoryHalInterface.h>
42#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070043#include <media/AudioParameter.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 Laurentb680e952019-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) {
Eric Laurent488d5002020-05-14 09:13:30 -0700137 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800138 String16("external_vibrator_service"));
139 if (binder != 0) {
140 sExternalVibratorService =
141 interface_cast<os::IExternalVibratorService>(binder);
142 }
143 }
144 return sExternalVibratorService;
145}
146
Mikhail Naganov3de4f262020-03-06 17:02:19 -0800147class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
148 public:
149 void onNewDevicesAvailable() override {
150 // Start a detached thread to execute notification in parallel.
151 // This is done to prevent mutual blocking of audio_flinger and
152 // audio_policy services during system initialization.
153 std::thread notifier([]() {
154 AudioSystem::onNewAudioModulesAvailable();
155 });
156 notifier.detach();
157 }
158};
159
Mathias Agopian65ab4712010-07-14 17:59:35 -0700160// ----------------------------------------------------------------------------
161
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700162std::string formatToString(audio_format_t format) {
163 std::string result;
164 FormatConverter::toString(format, result);
165 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800166}
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168// ----------------------------------------------------------------------------
169
170AudioFlinger::AudioFlinger()
171 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800172 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800173 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800174 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700175 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800176 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700178 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800179 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700180 mBtNrecIsOff(false),
181 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700182 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800183 mTotalMemory(0),
184 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700185 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700186 mPatchPanel(this),
Eric Laurent9b2064c2019-11-22 17:25:04 -0800187 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700188 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700189{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700190 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
191 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
192 // zero ID has a special meaning, so unavailable
193 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
194 }
195
Glenn Kastenae0cff12016-02-24 13:57:49 -0800196 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800197 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800198 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
199 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700200 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800201 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700202
Wei Jia3f273d12015-11-24 09:06:49 -0800203 // reset battery stats.
204 // if the audio service has crashed, battery stats could be left
205 // in bad state, reset the state upon service start.
206 BatteryNotifier::getInstance().noteResetAudio();
207
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700208 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700209 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
210
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800211 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurentb680e952019-09-27 15:40:33 -0700212 std::vector<pid_t> halPids;
213 mDevicesFactoryHal->getHalPids(&halPids);
214 TimeCheck::setAudioHalPids(halPids);
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700215}
216
217void AudioFlinger::onFirstRef()
218{
Eric Laurent93575202011-01-18 18:39:02 -0800219 Mutex::Autolock _l(mLock);
220
Dima Zavin799a70e2011-04-18 16:57:27 -0700221 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800222 char val_str[PROPERTY_VALUE_MAX] = { 0 };
223 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
224 uint32_t int_val;
225 if (1 == sscanf(val_str, "%u", &int_val)) {
226 mStandbyTimeInNsecs = milliseconds(int_val);
227 ALOGI("Using %u mSec as standby time.", int_val);
228 } else {
229 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
230 ALOGI("Using default %u mSec as standby time.",
231 (uint32_t)(mStandbyTimeInNsecs / 1000000));
232 }
233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700234
Eric Laurenta4c5a552012-03-29 10:12:40 -0700235 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800236
237 gAudioFlinger = this;
Mikhail Naganov3de4f262020-03-06 17:02:19 -0800238
239 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
240 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241}
242
Eric Laurentb680e952019-09-27 15:40:33 -0700243status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
244 TimeCheck::setAudioHalPids(pids);
245 return NO_ERROR;
246}
247
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248AudioFlinger::~AudioFlinger()
249{
250 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700251 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700252 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253 }
254 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700255 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700256 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257 }
Andy Hungb4946b62019-03-14 11:19:28 -0700258 while (!mMmapThreads.isEmpty()) {
259 const audio_io_handle_t io = mMmapThreads.keyAt(0);
260 if (mMmapThreads.valueAt(0)->isOutput()) {
261 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
262 } else {
263 closeInput_nonvirtual(io); // removes entry from mMmapThreads
264 }
265 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700266
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800267 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
268 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700270 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700271
272 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700273 if (sMediaLogService != 0) {
274 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
275 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
276 mUnregisteredWriters.pop();
277 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700278 }
279 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700280}
281
Eric Laurentfc235202016-12-20 18:48:17 -0800282//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800283__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800284status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
285 const audio_attributes_t *attr,
286 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700287 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800288 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800289 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800290 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700291 sp<MmapStreamInterface>& interface,
292 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800293{
294 sp<AudioFlinger> af;
295 {
296 Mutex::Autolock _l(gLock);
297 af = gAudioFlinger.promote();
298 }
299 status_t ret = NO_INIT;
300 if (af != 0) {
301 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800302 direction, attr, config, client, deviceId,
303 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800304 }
305 return ret;
306}
307
Eric Laurent6acd1d42017-01-04 14:23:29 -0800308status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
309 const audio_attributes_t *attr,
310 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700311 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800312 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800313 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800314 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700315 sp<MmapStreamInterface>& interface,
316 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800317{
318 status_t ret = initCheck();
319 if (ret != NO_ERROR) {
320 return ret;
321 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800322 audio_session_t actualSessionId = *sessionId;
323 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
324 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
325 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800326 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700327 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800328 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700329 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800330 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
331 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
332 fullConfig.sample_rate = config->sample_rate;
333 fullConfig.channel_mask = config->channel_mask;
334 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800335 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700336
337 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800338 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200339 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800340 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800341 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
342 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800343 deviceId, &portId, &secondaryOutputs);
344 ALOGW_IF(!secondaryOutputs.empty(),
345 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800346 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700347 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700348 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800349 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800350 client.clientPid,
351 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800352 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800353 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700354 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800355 }
356 if (ret != NO_ERROR) {
357 return ret;
358 }
359
360 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
361 // audio policy manager and we can retrieve it
362 sp<MmapThread> thread = mMmapThreads.valueFor(io);
363 if (thread != 0) {
364 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700365 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700366 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800367 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800368 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700369 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700370 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700371 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800372 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700373 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800374 ret = NO_INIT;
375 }
376
377 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
378
Eric Laurentfc235202016-12-20 18:48:17 -0800379 return ret;
380}
381
jiabin57303cc2018-12-18 15:45:57 -0800382/* static */
383int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
384 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
385 if (evs != 0) {
386 int32_t ret;
387 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
388 if (status.isOk()) {
389 return ret;
390 }
391 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800392 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800393}
394
395/* static */
396void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
397 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
398 if (evs != 0) {
399 evs->onExternalVibrationStop(*externalVibration);
400 }
401}
402
Eric Laurent9b2064c2019-11-22 17:25:04 -0800403status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
404 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent488d5002020-05-14 09:13:30 -0700405 AutoMutex lock(mHardwareLock);
Eric Laurent9b2064c2019-11-22 17:25:04 -0800406 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
407 if (audioHwDevice == nullptr) {
408 return NO_INIT;
409 }
410 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
411}
412
413status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
414 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent488d5002020-05-14 09:13:30 -0700415 AutoMutex lock(mHardwareLock);
Eric Laurent9b2064c2019-11-22 17:25:04 -0800416 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
417 if (audioHwDevice == nullptr) {
418 return NO_INIT;
419 }
420 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
421}
422
Eric Laurenta4c5a552012-03-29 10:12:40 -0700423static const char * const audio_interfaces[] = {
424 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
425 AUDIO_HARDWARE_MODULE_ID_A2DP,
426 AUDIO_HARDWARE_MODULE_ID_USB,
427};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700428
Phil Burk062e67a2015-02-11 13:40:50 -0800429AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700430 audio_module_handle_t module,
jiabinc0106832019-10-24 14:58:31 -0700431 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700432{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700433 // if module is 0, the request comes from an old policy manager and we should load
434 // well known modules
Eric Laurent488d5002020-05-14 09:13:30 -0700435 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700436 if (module == 0) {
437 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700438 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700439 loadHwModule_l(audio_interfaces[i]);
440 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700441 // then try to find a module supporting the requested device.
442 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
443 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700444 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
445 uint32_t supportedDevices;
446 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabinc0106832019-10-24 14:58:31 -0700447 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700448 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700449 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700450 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700451 } else {
452 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700453 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
454 if (audioHwDevice != NULL) {
455 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700456 }
457 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700458
Dima Zavin799a70e2011-04-18 16:57:27 -0700459 return NULL;
460}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461
Glenn Kasten0f11b512014-01-31 16:18:54 -0800462void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463{
464 const size_t SIZE = 256;
465 char buffer[SIZE];
466 String8 result;
467
468 result.append("Clients:\n");
469 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800470 sp<Client> client = mClients.valueAt(i).promote();
471 if (client != 0) {
472 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
473 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 }
475 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700476
Eric Laurentd1b28d42013-09-18 18:47:13 -0700477 result.append("Notification Clients:\n");
478 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
479 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
480 result.append(buffer);
481 }
482
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700483 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800484 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700485 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
486 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800487 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700488 result.append(buffer);
489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491}
492
493
Glenn Kasten0f11b512014-01-31 16:18:54 -0800494void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495{
496 const size_t SIZE = 256;
497 char buffer[SIZE];
498 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800499 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500
John Grossman4ff14ba2012-02-08 16:37:41 -0800501 snprintf(buffer, SIZE, "Hardware status: %d\n"
502 "Standby Time mSec: %u\n",
503 hardwareStatus,
504 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505 result.append(buffer);
506 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507}
508
Glenn Kasten0f11b512014-01-31 16:18:54 -0800509void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510{
511 const size_t SIZE = 256;
512 char buffer[SIZE];
513 String8 result;
514 snprintf(buffer, SIZE, "Permission Denial: "
515 "can't dump AudioFlinger from pid=%d, uid=%d\n",
516 IPCThreadState::self()->getCallingPid(),
517 IPCThreadState::self()->getCallingUid());
518 result.append(buffer);
519 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520}
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700523{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700524 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
525 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700526}
527
528status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
529{
Glenn Kasten44deb052012-02-05 18:09:08 -0800530 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 dumpPermissionDenial(fd, args);
532 } else {
533 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800534 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700535 if (!hardwareLocked) {
536 String8 result(kHardwareLockedString);
537 write(fd, result.string(), result.size());
538 } else {
539 mHardwareLock.unlock();
540 }
541
Eric Tan7b651152018-07-13 10:17:19 -0700542 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543
544 // failed to lock - AudioFlinger is probably deadlocked
545 if (!locked) {
546 String8 result(kDeadlockedString);
547 write(fd, result.string(), result.size());
548 }
549
Eric Laurent021cf962014-05-13 10:18:14 -0700550 bool clientLocked = dumpTryLock(mClientLock);
551 if (!clientLocked) {
552 String8 result(kClientLockedString);
553 write(fd, result.string(), result.size());
554 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700555
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700556 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700557 mEffectsFactoryHal->dumpEffects(fd);
558 } else {
559 String8 result(kNoEffectsFactory);
560 write(fd, result.string(), result.size());
561 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700562
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700564 if (clientLocked) {
565 mClientLock.unlock();
566 }
567
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 dumpInternals(fd, args);
569
570 // dump playback threads
571 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
572 mPlaybackThreads.valueAt(i)->dump(fd, args);
573 }
574
575 // dump record threads
576 for (size_t i = 0; i < mRecordThreads.size(); i++) {
577 mRecordThreads.valueAt(i)->dump(fd, args);
578 }
579
Eric Laurent6acd1d42017-01-04 14:23:29 -0800580 // dump mmap threads
581 for (size_t i = 0; i < mMmapThreads.size(); i++) {
582 mMmapThreads.valueAt(i)->dump(fd, args);
583 }
584
Eric Laurentaaa44472014-09-12 17:41:50 -0700585 // dump orphan effect chains
586 if (mOrphanEffectChains.size() != 0) {
587 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
588 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
589 mOrphanEffectChains.valueAt(i)->dump(fd, args);
590 }
591 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700592 // dump all hardware devs
593 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700594 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
595 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700597
Mikhail Naganov201369b2018-05-16 16:52:32 -0700598 mPatchPanel.dump(fd);
599
Eric Laurent9b2064c2019-11-22 17:25:04 -0800600 mDeviceEffectManager.dump(fd);
601
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700602 // dump external setParameters
603 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
604 dprintf(fd, "\n%s setParameters:\n", name);
605 logger.dump(fd, " " /* prefix */);
606 };
607 dumpLogger(mRejectedSetParameterLog, "Rejected");
608 dumpLogger(mAppSetParameterLog, "App");
609 dumpLogger(mSystemSetParameterLog, "System");
610
Andy Hunga8115dc2018-08-24 15:51:59 -0700611 // dump historical threads in the last 10 seconds
612 const std::string threadLog = mThreadLog.dumpToString(
613 "Historical Thread Log ", 0 /* lines */,
614 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
615 write(fd, threadLog.c_str(), threadLog.size());
616
rago3bd1c872016-09-26 12:58:14 -0700617 BUFLOG_RESET;
618
Glenn Kastend65d73c2012-06-22 17:21:07 -0700619 if (locked) {
620 mLock.unlock();
621 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800622
Andy Hung8946a282018-04-19 20:04:56 -0700623#ifdef TEE_SINK
624 // NBAIO_Tee dump is safe to call outside of AF lock.
625 NBAIO_Tee::dumpAll(fd, "_DUMP");
626#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800627 // append a copy of media.log here by forwarding fd to it, but don't attempt
628 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700629 if (sMediaLogServiceAsBinder != 0) {
630 dprintf(fd, "\nmedia.log:\n");
631 Vector<String16> args;
632 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800633 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700634
635 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700636 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700637 bool unreachableMemory = false;
638 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700639 if (arg == String16("-m")) {
640 dumpMem = true;
641 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700642 unreachableMemory = true;
643 }
644 }
645
Andy Hung07b745e2016-05-23 16:21:07 -0700646 if (dumpMem) {
647 dprintf(fd, "\nDumping memory:\n");
648 std::string s = dumpMemoryAddresses(100 /* limit */);
649 write(fd, s.c_str(), s.size());
650 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700651 if (unreachableMemory) {
652 dprintf(fd, "\nDumping unreachable memory:\n");
653 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700654 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700655 write(fd, s.c_str(), s.size());
656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657 }
658 return NO_ERROR;
659}
660
Eric Laurent021cf962014-05-13 10:18:14 -0700661sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800662{
Eric Laurent021cf962014-05-13 10:18:14 -0700663 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800664 // If pid is already in the mClients wp<> map, then use that entry
665 // (for which promote() is always != 0), otherwise create a new entry and Client.
666 sp<Client> client = mClients.valueFor(pid).promote();
667 if (client == 0) {
668 client = new Client(this, pid);
669 mClients.add(pid, client);
670 }
671
672 return client;
673}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700674
Glenn Kasten9e58b552013-01-18 15:09:48 -0800675sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
676{
Jiabin Huang60766082020-07-28 22:03:56 +0000677 // If there is no memory allocated for logs, return a no-op writer that does nothing.
678 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700679 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800680 return new NBLog::Writer();
681 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700682 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
683 // If allocation fails, consult the vector of previously unregistered writers
684 // and garbage-collect one or more them until an allocation succeeds
685 if (shared == 0) {
686 Mutex::Autolock _l(mUnregisteredWritersLock);
687 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
688 {
689 // Pick the oldest stale writer to garbage-collect
690 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
691 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700692 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700693 // Now the media.log remote reference to IMemory is gone. When our last local
694 // reference to IMemory also drops to zero at end of this block,
695 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
696 }
697 // Re-attempt the allocation
698 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
699 if (shared != 0) {
700 goto success;
701 }
702 }
703 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +0000704 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -0700705 return new NBLog::Writer();
706 }
707success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800708 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
709 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
710 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700711 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800712 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800713}
714
715void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
716{
Glenn Kasten685ef092013-02-04 08:15:34 -0800717 if (writer == 0) {
718 return;
719 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800720 sp<IMemory> iMemory(writer->getIMemory());
721 if (iMemory == 0) {
722 return;
723 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700724 // Rather than removing the writer immediately, append it to a queue of old writers to
725 // be garbage-collected later. This allows us to continue to view old logs for a while.
726 Mutex::Autolock _l(mUnregisteredWritersLock);
727 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800728}
729
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730// IAudioFlinger interface
731
Eric Laurent21da6472017-11-09 16:29:26 -0800732sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
733 CreateTrackOutput& output,
734 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735{
736 sp<PlaybackThread::Track> track;
737 sp<TrackHandle> trackHandle;
738 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800740 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800741 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800742 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743
Eric Laurent21da6472017-11-09 16:29:26 -0800744 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700745 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800746 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700747 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
748 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700749 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700750
Andy Hung4ef19fa2018-05-15 19:35:29 -0700751 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800752 ALOGW_IF(clientUid != callingUid,
753 "%s uid %d tried to pass itself off as %d",
754 __FUNCTION__, callingUid, clientUid);
755 clientUid = callingUid;
756 updatePid = true;
757 }
758 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700759 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800760 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800761 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700762 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800763 __func__, callingUid, callingPid, clientPid);
764 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700765 }
766
Eric Laurent21da6472017-11-09 16:29:26 -0800767 audio_session_t sessionId = input.sessionId;
768 if (sessionId == AUDIO_SESSION_ALLOCATE) {
769 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800770 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
771 lStatus = BAD_VALUE;
772 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800773 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800774
Eric Laurent21da6472017-11-09 16:29:26 -0800775 output.sessionId = sessionId;
776 output.outputId = AUDIO_IO_HANDLE_NONE;
777 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700778 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200779 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800780 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800781
782 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
783 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
784 goto Exit;
785 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800786 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
787 // but if someone uses binder directly they could bypass that and cause us to crash
788 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000789 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 lStatus = BAD_VALUE;
791 goto Exit;
792 }
793
Glenn Kasten53b5d092014-02-05 10:00:23 -0800794 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800795 if (!audio_is_output_channel(input.config.channel_mask)) {
796 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800797 lStatus = BAD_VALUE;
798 goto Exit;
799 }
800
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700801 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800802 if (!audio_is_valid_format(input.config.format)) {
803 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700804 lStatus = BAD_VALUE;
805 goto Exit;
806 }
807
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 {
809 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800810 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800812 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 lStatus = BAD_VALUE;
814 goto Exit;
815 }
816
Eric Laurent21da6472017-11-09 16:29:26 -0800817 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818
Glenn Kastene848bd92014-03-13 15:00:32 -0700819 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800820 // check if an effect chain with the same session ID is present on another
821 // output thread and move it here.
822 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
823 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
824 if (mPlaybackThreads.keyAt(i) != output.outputId) {
825 uint32_t sessions = t->hasAudioSession(sessionId);
826 if (sessions & ThreadBase::EFFECT_SESSION) {
827 effectThread = t.get();
828 break;
Eric Laurentde070132010-07-13 04:45:46 -0700829 }
830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831 }
Eric Laurent21da6472017-11-09 16:29:26 -0800832 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833
Eric Laurent21da6472017-11-09 16:29:26 -0800834 output.sampleRate = input.config.sample_rate;
835 output.frameCount = input.frameCount;
836 output.notificationFrameCount = input.notificationFrameCount;
837 output.flags = input.flags;
838
Eric Laurent42984412019-05-09 17:57:03 -0700839 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700840 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800841 &output.frameCount, &output.notificationFrameCount,
842 input.notificationsPerBuffer, input.speed,
843 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700844 callingPid, input.clientInfo.clientTid, clientUid,
845 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800846 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700847 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700848
Eric Laurent21da6472017-11-09 16:29:26 -0800849 output.afFrameCount = thread->frameCount();
850 output.afSampleRate = thread->sampleRate();
851 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800852 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800853
Kevin Rocard153f92d2018-12-18 18:33:28 -0800854 if (lStatus == NO_ERROR) {
855 // Connect secondary outputs. Failure on a secondary output must not imped the primary
856 // Any secondary output setup failure will lead to a desync between the AP and AF until
857 // the track is destroyed.
858 TeePatches teePatches;
859 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
860 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
861 if (secondaryThread == NULL) {
862 ALOGE("no playback thread found for secondary output %d", output.outputId);
863 continue;
864 }
865
Kevin Rocard20a44f82019-09-18 11:24:52 +0100866 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
867 / thread->sampleRate();
868 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
869 / secondaryThread->sampleRate();
870 // If the secondary output has just been opened, the first secondaryThread write
871 // will not block as it will fill the empty startup buffer of the HAL,
872 // so a second sink buffer needs to be ready for the immediate next blocking write.
873 // Additionally, have a margin of one main thread buffer as the scheduling jitter
874 // can reorder the writes (eg if thread A&B have the same write intervale,
875 // the scheduler could schedule AB...BA)
876 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
877 // Total secondary output buffer must be at least as the read frames plus
878 // the margin of a few buffers on both sides in case the
879 // threads scheduling has some jitter.
880 // That value should not impact latency as the secondary track is started before
881 // its buffer is full, see frameCountToBeReady.
882 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
883 // The frameCount should also not be smaller than the secondary thread min frame
884 // count
885 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
886 [&] { Mutex::Autolock _l(secondaryThread->mLock);
887 return secondaryThread->latency_l(); }(),
888 secondaryThread->mNormalFrameCount,
889 secondaryThread->mSampleRate,
890 output.sampleRate,
891 input.speed);
892 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800893
894 using namespace std::chrono_literals;
895 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
896 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
897 output.sampleRate,
898 inChannelMask,
899 input.config.format,
900 frameCount,
901 NULL /* buffer */,
902 (size_t)0 /* bufferSize */,
903 AUDIO_INPUT_FLAG_DIRECT,
904 0ns /* timeout */);
905 status_t status = patchRecord->initCheck();
906 if (status != NO_ERROR) {
907 ALOGE("Secondary output patchRecord init failed: %d", status);
908 continue;
909 }
Andy Hungae22b482019-05-09 15:38:55 -0700910
911 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
912 // for fast usage: thread has fast mixer, sample rate matches, etc.;
913 // for now, we exclude fast tracks by removing the Fast flag.
914 const audio_output_flags_t outputFlags =
915 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800916 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
917 streamType,
918 output.sampleRate,
919 input.config.channel_mask,
920 input.config.format,
921 frameCount,
922 patchRecord->buffer(),
923 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700924 outputFlags,
Kevin Rocard20a44f82019-09-18 11:24:52 +0100925 0ns /* timeout */,
926 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800927 status = patchTrack->initCheck();
928 if (status != NO_ERROR) {
929 ALOGE("Secondary output patchTrack init failed: %d", status);
930 continue;
931 }
932 teePatches.push_back({patchRecord, patchTrack});
933 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800934 // In case the downstream patchTrack on the secondaryThread temporarily outlives
935 // our created track, ensure the corresponding patchRecord is still alive.
936 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
937 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800938 }
939 track->setTeePatches(std::move(teePatches));
940 }
941
Eric Laurent39e94f82010-07-28 01:32:47 -0700942 // move effect chain to this output thread if an effect on same session was waiting
943 // for a track to be created
944 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700945 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700946 Mutex::Autolock _dl(thread->mLock);
947 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700948 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
949 effectThreadId = thread->id();
950 effectIds = thread->getEffectIds_l(sessionId);
951 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700952 }
Eric Laurenta011e352012-03-29 15:51:43 -0700953
954 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700955 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800956 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700957 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700958 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700959 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700960 } else {
961 mPendingSyncEvents[i]->cancel();
962 }
Eric Laurenta011e352012-03-29 15:51:43 -0700963 mPendingSyncEvents.removeAt(i);
964 i--;
965 }
966 }
967 }
Glenn Kastene198c362013-08-13 09:13:36 -0700968
Eric Laurent21da6472017-11-09 16:29:26 -0800969 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970 }
Glenn Kastene198c362013-08-13 09:13:36 -0700971
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700972 if (lStatus != NO_ERROR) {
973 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700974 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700975 // Don't hold mClientLock when releasing the reference on the track as the
976 // destructor will acquire it.
977 {
978 Mutex::Autolock _cl(mClientLock);
979 client.clear();
980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700982 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983 }
984
Eric Laurent6c796322019-04-09 14:13:17 -0700985 // effectThreadId is not NONE if an effect chain corresponding to the track session
986 // was found on another thread and must be moved on this thread
987 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
988 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
989 }
990
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700991 // return handle to client
992 trackHandle = new TrackHandle(track);
993
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800995 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700996 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800997 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700998 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999 return trackHandle;
1000}
1001
Glenn Kasten2c073da2016-02-26 09:14:08 -08001002uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003{
1004 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001005 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001007 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 return 0;
1009 }
1010 return thread->sampleRate();
1011}
1012
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001013audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014{
1015 Mutex::Autolock _l(mLock);
1016 PlaybackThread *thread = checkPlaybackThread_l(output);
1017 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001018 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001019 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020 }
1021 return thread->format();
1022}
1023
Glenn Kasten2c073da2016-02-26 09:14:08 -08001024size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025{
1026 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001027 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001029 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 return 0;
1031 }
Glenn Kasten58912562012-04-03 10:45:00 -07001032 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1033 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034 return thread->frameCount();
1035}
1036
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001037size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1038{
1039 Mutex::Autolock _l(mLock);
1040 ThreadBase *thread = checkThread_l(ioHandle);
1041 if (thread == NULL) {
1042 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1043 return 0;
1044 }
1045 return thread->frameCountHAL();
1046}
1047
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001048uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049{
1050 Mutex::Autolock _l(mLock);
1051 PlaybackThread *thread = checkPlaybackThread_l(output);
1052 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001053 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 return 0;
1055 }
1056 return thread->latency();
1057}
1058
1059status_t AudioFlinger::setMasterVolume(float value)
1060{
Eric Laurenta1884f92011-08-23 08:25:03 -07001061 status_t ret = initCheck();
1062 if (ret != NO_ERROR) {
1063 return ret;
1064 }
1065
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 // check calling permissions
1067 if (!settingsAllowed()) {
1068 return PERMISSION_DENIED;
1069 }
1070
Eric Laurenta4c5a552012-03-29 10:12:40 -07001071 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001072 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001073
John Grossmanee578c02012-07-23 17:05:46 -07001074 // Set master volume in the HALs which support it.
Eric Laurent488d5002020-05-14 09:13:30 -07001075 {
John Grossmanee578c02012-07-23 17:05:46 -07001076 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001077 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1078 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001079
Eric Laurent488d5002020-05-14 09:13:30 -07001080 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1081 if (dev->canSetMasterVolume()) {
1082 dev->hwDevice()->setMasterVolume(value);
1083 }
1084 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 }
John Grossmanee578c02012-07-23 17:05:46 -07001087 // Now set the master volume in each playback thread. Playback threads
1088 // assigned to HALs which do not have master volume support will apply
1089 // master volume during the mix operation. Threads with HALs which do
1090 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001091 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1092 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1093 continue;
1094 }
John Grossmanee578c02012-07-23 17:05:46 -07001095 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097
1098 return NO_ERROR;
1099}
1100
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001101status_t AudioFlinger::setMasterBalance(float balance)
1102{
1103 status_t ret = initCheck();
1104 if (ret != NO_ERROR) {
1105 return ret;
1106 }
1107
1108 // check calling permissions
1109 if (!settingsAllowed()) {
1110 return PERMISSION_DENIED;
1111 }
1112
1113 // check range
1114 if (isnan(balance) || fabs(balance) > 1.f) {
1115 return BAD_VALUE;
1116 }
1117
1118 Mutex::Autolock _l(mLock);
1119
1120 // short cut.
1121 if (mMasterBalance == balance) return NO_ERROR;
1122
1123 mMasterBalance = balance;
1124
1125 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1126 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1127 continue;
1128 }
1129 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1130 }
1131
1132 return NO_ERROR;
1133}
1134
Glenn Kastenf78aee72012-01-04 11:00:47 -08001135status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136{
Eric Laurenta1884f92011-08-23 08:25:03 -07001137 status_t ret = initCheck();
1138 if (ret != NO_ERROR) {
1139 return ret;
1140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141
1142 // check calling permissions
1143 if (!settingsAllowed()) {
1144 return PERMISSION_DENIED;
1145 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001146 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001147 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 return BAD_VALUE;
1149 }
1150
1151 { // scope for the lock
1152 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001153 if (mPrimaryHardwareDev == nullptr) {
1154 return INVALID_OPERATION;
1155 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001156 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001158 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159 mHardwareStatus = AUDIO_HW_IDLE;
1160 }
1161
1162 if (NO_ERROR == ret) {
1163 Mutex::Autolock _l(mLock);
1164 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001165 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001166 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 }
1168
1169 return ret;
1170}
1171
1172status_t AudioFlinger::setMicMute(bool state)
1173{
Eric Laurenta1884f92011-08-23 08:25:03 -07001174 status_t ret = initCheck();
1175 if (ret != NO_ERROR) {
1176 return ret;
1177 }
1178
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 // check calling permissions
1180 if (!settingsAllowed()) {
1181 return PERMISSION_DENIED;
1182 }
1183
1184 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001185 if (mPrimaryHardwareDev == nullptr) {
1186 return INVALID_OPERATION;
1187 }
Eric Laurenta135dd82020-05-14 09:07:39 -07001188 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1189 if (primaryDev == nullptr) {
1190 ALOGW("%s: no primary HAL device", __func__);
1191 return INVALID_OPERATION;
1192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta135dd82020-05-14 09:07:39 -07001194 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001195 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001196 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurenta135dd82020-05-14 09:07:39 -07001197 if (dev != primaryDev) {
1198 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001199 }
1200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta135dd82020-05-14 09:07:39 -07001202 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 return ret;
1204}
1205
1206bool AudioFlinger::getMicMute() const
1207{
Eric Laurenta1884f92011-08-23 08:25:03 -07001208 status_t ret = initCheck();
1209 if (ret != NO_ERROR) {
1210 return false;
1211 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001212 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001213 if (mPrimaryHardwareDev == nullptr) {
1214 return false;
1215 }
Eric Laurenta135dd82020-05-14 09:07:39 -07001216 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1217 if (primaryDev == nullptr) {
1218 ALOGW("%s: no primary HAL device", __func__);
1219 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001220 }
Eric Laurenta135dd82020-05-14 09:07:39 -07001221 bool state;
1222 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1223 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta135dd82020-05-14 09:07:39 -07001225 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1226 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227}
1228
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001229void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1230{
1231 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1232
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001233 AutoMutex lock(mLock);
1234 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001235 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1236 }
1237 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1238 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001239 }
1240}
1241
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242status_t AudioFlinger::setMasterMute(bool muted)
1243{
John Grossmand8f178d2012-07-20 14:51:35 -07001244 status_t ret = initCheck();
1245 if (ret != NO_ERROR) {
1246 return ret;
1247 }
1248
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 // check calling permissions
1250 if (!settingsAllowed()) {
1251 return PERMISSION_DENIED;
1252 }
1253
John Grossmanee578c02012-07-23 17:05:46 -07001254 Mutex::Autolock _l(mLock);
1255 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001256
John Grossmanee578c02012-07-23 17:05:46 -07001257 // Set master mute in the HALs which support it.
Eric Laurent488d5002020-05-14 09:13:30 -07001258 {
John Grossmanee578c02012-07-23 17:05:46 -07001259 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001260 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1261 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001262
Eric Laurent488d5002020-05-14 09:13:30 -07001263 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1264 if (dev->canSetMasterMute()) {
1265 dev->hwDevice()->setMasterMute(muted);
1266 }
1267 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001268 }
John Grossmand8f178d2012-07-20 14:51:35 -07001269 }
1270
John Grossmanee578c02012-07-23 17:05:46 -07001271 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001272 // assigned to HALs which do not have master mute support will apply master mute
1273 // during the mix operation. Threads with HALs which do support master mute
1274 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001275 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1276 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1277 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279
1280 return NO_ERROR;
1281}
1282
1283float AudioFlinger::masterVolume() const
1284{
Glenn Kasten98067102011-12-13 11:47:54 -08001285 Mutex::Autolock _l(mLock);
1286 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287}
1288
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001289status_t AudioFlinger::getMasterBalance(float *balance) const
1290{
1291 Mutex::Autolock _l(mLock);
1292 *balance = getMasterBalance_l();
1293 return NO_ERROR; // if called through binder, may return a transactional error
1294}
1295
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296bool AudioFlinger::masterMute() const
1297{
Glenn Kasten98067102011-12-13 11:47:54 -08001298 Mutex::Autolock _l(mLock);
1299 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300}
1301
John Grossman4ff14ba2012-02-08 16:37:41 -08001302float AudioFlinger::masterVolume_l() const
1303{
John Grossman4ff14ba2012-02-08 16:37:41 -08001304 return mMasterVolume;
1305}
1306
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001307float AudioFlinger::getMasterBalance_l() const
1308{
1309 return mMasterBalance;
1310}
1311
John Grossmand8f178d2012-07-20 14:51:35 -07001312bool AudioFlinger::masterMute_l() const
1313{
John Grossmanee578c02012-07-23 17:05:46 -07001314 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001315}
1316
Eric Laurent223fd5c2014-11-11 13:43:36 -08001317status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1318{
1319 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001320 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001321 return BAD_VALUE;
1322 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001323 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1324 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1325 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001326 return PERMISSION_DENIED;
1327 }
1328
1329 return NO_ERROR;
1330}
1331
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001332status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1333 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334{
1335 // check calling permissions
1336 if (!settingsAllowed()) {
1337 return PERMISSION_DENIED;
1338 }
1339
Eric Laurent223fd5c2014-11-11 13:43:36 -08001340 status_t status = checkStreamType(stream);
1341 if (status != NO_ERROR) {
1342 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001343 }
Eric Laurent98e38192018-02-15 18:31:53 -08001344 if (output == AUDIO_IO_HANDLE_NONE) {
1345 return BAD_VALUE;
1346 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001347 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1348 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001349
1350 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001351 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1352 if (volumeInterface == NULL) {
1353 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354 }
Eric Laurent98e38192018-02-15 18:31:53 -08001355 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356
1357 return NO_ERROR;
1358}
1359
Glenn Kastenfff6d712012-01-12 16:38:12 -08001360status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361{
1362 // check calling permissions
1363 if (!settingsAllowed()) {
1364 return PERMISSION_DENIED;
1365 }
1366
Eric Laurent223fd5c2014-11-11 13:43:36 -08001367 status_t status = checkStreamType(stream);
1368 if (status != NO_ERROR) {
1369 return status;
1370 }
1371 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1372
1373 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001374 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375 return BAD_VALUE;
1376 }
1377
Eric Laurent93575202011-01-18 18:39:02 -08001378 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001380 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1381 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1382 volumeInterfaces[i]->setStreamMute(stream, muted);
1383 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384
1385 return NO_ERROR;
1386}
1387
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001388float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001390 status_t status = checkStreamType(stream);
1391 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392 return 0.0f;
1393 }
Eric Laurent98e38192018-02-15 18:31:53 -08001394 if (output == AUDIO_IO_HANDLE_NONE) {
1395 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 }
1397
Eric Laurent98e38192018-02-15 18:31:53 -08001398 AutoMutex lock(mLock);
1399 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1400 if (volumeInterface == NULL) {
1401 return 0.0f;
1402 }
1403
1404 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405}
1406
Glenn Kastenfff6d712012-01-12 16:38:12 -08001407bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001409 status_t status = checkStreamType(stream);
1410 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411 return true;
1412 }
1413
Glenn Kasten6637baa2012-01-09 09:40:36 -08001414 AutoMutex lock(mLock);
1415 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416}
1417
Eric Laurent054d9d32015-04-24 08:48:48 -07001418
1419void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1420{
1421 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1422 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1423 }
1424}
1425
jiabin10d86fd2019-10-31 17:20:42 -07001426void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1427{
1428 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1429 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1430 }
1431}
1432
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001433// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1434void AudioFlinger::forwardParametersToDownstreamPatches_l(
1435 audio_io_handle_t upStream, const String8& keyValuePairs,
1436 std::function<bool(const sp<PlaybackThread>&)> useThread)
1437{
1438 std::vector<PatchPanel::SoftwarePatch> swPatches;
1439 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1440 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1441 __func__, swPatches.size(), upStream);
1442 for (const auto& swPatch : swPatches) {
1443 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1444 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1445 downStream->setParameters(keyValuePairs);
1446 }
1447 }
1448}
1449
Eric Laurentf1047e82018-04-16 19:18:20 -07001450// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1451// Some keys are used for audio routing and audio path configuration and should be reserved for use
1452// by audio policy and audio flinger for functional, privacy and security reasons.
1453void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1454{
1455 static const String8 kReservedParameters[] = {
1456 String8(AudioParameter::keyRouting),
1457 String8(AudioParameter::keySamplingRate),
1458 String8(AudioParameter::keyFormat),
1459 String8(AudioParameter::keyChannels),
1460 String8(AudioParameter::keyFrameCount),
1461 String8(AudioParameter::keyInputSource),
1462 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovbb3b1602019-07-08 15:28:43 -07001463 String8(AudioParameter::keyDeviceConnect),
1464 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001465 String8(AudioParameter::keyStreamSupportedFormats),
1466 String8(AudioParameter::keyStreamSupportedChannels),
1467 String8(AudioParameter::keyStreamSupportedSamplingRates),
1468 };
1469
Andy Hung4ef19fa2018-05-15 19:35:29 -07001470 if (isAudioServerUid(callingUid)) {
1471 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001472 }
1473
1474 AudioParameter param = AudioParameter(keyValuePairs);
1475 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001476 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001477 for (auto& key : kReservedParameters) {
1478 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001479 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001480 param.remove(key);
1481 }
1482 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001483 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1484 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001485 keyValuePairs = param.toString();
1486}
1487
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001488void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1489 size_t rejectedKVPSize, const String8& rejectedKVPs,
1490 uid_t callingUid) {
1491 auto prefix = String8::format("UID %5d", callingUid);
1492 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1493 if (rejectedKVPSize != 0) {
1494 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1495 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1496 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1497 } else {
1498 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1499 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1500 }
1501}
1502
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001503status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504{
Eric Laurentf1047e82018-04-16 19:18:20 -07001505 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1506 ioHandle, keyValuePairs.string(),
1507 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001508
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 // check calling permissions
1510 if (!settingsAllowed()) {
1511 return PERMISSION_DENIED;
1512 }
1513
Eric Laurentf1047e82018-04-16 19:18:20 -07001514 String8 filteredKeyValuePairs = keyValuePairs;
1515 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1516
1517 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1518
Glenn Kasten142f5192014-03-25 17:44:59 -07001519 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1520 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001521 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001522 // result will remain NO_INIT if no audio device is present
1523 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001524 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001525 AutoMutex lock(mHardwareLock);
1526 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1527 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001528 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001529 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001530 // return success if at least one audio device accepts the parameters as not all
1531 // HALs are requested to support all parameters. If no audio device supports the
1532 // requested parameters, the last error is reported.
1533 if (final_result != NO_ERROR) {
1534 final_result = result;
1535 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001536 }
1537 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001538 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001539 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001540 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001541 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001542 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1543 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001544 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001545 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001546 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001547 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001548 }
1549 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001550 String8 screenState;
1551 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001552 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001553 if (isOff != (AudioFlinger::mScreenState & 1)) {
1554 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001555 }
1556 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001557 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558 }
1559
1560 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1561 // and the thread is exited once the lock is released
1562 sp<ThreadBase> thread;
1563 {
1564 Mutex::Autolock _l(mLock);
1565 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001566 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001568 if (thread == 0) {
1569 thread = checkMmapThread_l(ioHandle);
1570 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001571 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001572 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001573 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001574 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001575 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1576 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001577 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001578 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 }
1580 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001581 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001582 status_t result = thread->setParameters(filteredKeyValuePairs);
1583 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1584 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 }
1586 return BAD_VALUE;
1587}
1588
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001589String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001591 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1592 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593
Eric Laurenta4c5a552012-03-29 10:12:40 -07001594 Mutex::Autolock _l(mLock);
1595
Glenn Kasten142f5192014-03-25 17:44:59 -07001596 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001597 String8 out_s8;
1598
Eric Laurent488d5002020-05-14 09:13:30 -07001599 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001600 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001601 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001602 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001603 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent488d5002020-05-14 09:13:30 -07001604 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001605 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001606 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001607 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001608 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 }
1610
Eric Laurent6acd1d42017-01-04 14:23:29 -08001611 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1612 if (thread == NULL) {
1613 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1614 if (thread == NULL) {
1615 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1616 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001617 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001618 }
1619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001621 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622}
1623
Glenn Kastendd8104c2012-07-02 12:42:44 -07001624size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1625 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626{
Eric Laurenta1884f92011-08-23 08:25:03 -07001627 status_t ret = initCheck();
1628 if (ret != NO_ERROR) {
1629 return 0;
1630 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001631 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001632 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001633 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001634 return 0;
1635 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001636
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001637 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001638 if (mPrimaryHardwareDev == nullptr) {
1639 return 0;
1640 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001641 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001642 audio_config_t config, proposed;
1643 memset(&proposed, 0, sizeof(proposed));
1644 proposed.sample_rate = sampleRate;
1645 proposed.channel_mask = channelMask;
1646 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001647
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001648 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Tao Wu1eb82df2019-11-05 10:20:18 -08001649 size_t frames = 0;
Andy Hung6770c6f2015-04-07 13:43:36 -07001650 for (;;) {
1651 // Note: config is currently a const parameter for get_input_buffer_size()
1652 // but we use a copy from proposed in case config changes from the call.
1653 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001654 status_t result = dev->getInputBufferSize(&config, &frames);
1655 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001656 break; // hal success, config is the result
1657 }
1658 // change one parameter of the configuration each iteration to a more "common" value
1659 // to see if the device will support it.
1660 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1661 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1662 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1663 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1664 } else {
1665 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1666 "format %#x, channelMask 0x%X",
1667 sampleRate, format, channelMask);
1668 break; // retries failed, break out of loop with frames == 0.
1669 }
1670 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001671 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001672 if (frames > 0 && config.sample_rate != sampleRate) {
1673 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1674 }
1675 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676}
1677
Glenn Kasten5f972c02014-01-13 09:59:31 -08001678uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 Mutex::Autolock _l(mLock);
1681
1682 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1683 if (recordThread != NULL) {
1684 return recordThread->getInputFramesLost();
1685 }
1686 return 0;
1687}
1688
1689status_t AudioFlinger::setVoiceVolume(float value)
1690{
Eric Laurenta1884f92011-08-23 08:25:03 -07001691 status_t ret = initCheck();
1692 if (ret != NO_ERROR) {
1693 return ret;
1694 }
1695
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696 // check calling permissions
1697 if (!settingsAllowed()) {
1698 return PERMISSION_DENIED;
1699 }
1700
1701 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001702 if (mPrimaryHardwareDev == nullptr) {
1703 return INVALID_OPERATION;
1704 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001705 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001706 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001707 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 mHardwareStatus = AUDIO_HW_IDLE;
1709
1710 return ret;
1711}
1712
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001713status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001714 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 Mutex::Autolock _l(mLock);
1717
1718 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1719 if (playbackThread != NULL) {
1720 return playbackThread->getRenderPosition(halFrames, dspFrames);
1721 }
1722
1723 return BAD_VALUE;
1724}
1725
1726void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1727{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001729 if (client == 0) {
1730 return;
1731 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001732 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001733 {
1734 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001735 if (mNotificationClients.indexOfKey(pid) < 0) {
1736 sp<NotificationClient> notificationClient = new NotificationClient(this,
1737 client,
1738 pid);
1739 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740
Eric Laurent021cf962014-05-13 10:18:14 -07001741 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742
Marco Nelissen06b46062014-11-14 07:58:25 -08001743 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001744 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001745 }
1746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747
Eric Laurent021cf962014-05-13 10:18:14 -07001748 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001749 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001750 // the config change is always sent from playback or record threads to avoid deadlock
1751 // with AudioSystem::gLock
1752 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001753 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001756 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001757 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758 }
1759}
1760
1761void AudioFlinger::removeNotificationClient(pid_t pid)
1762{
Eric Laurent6c796322019-04-09 14:13:17 -07001763 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001764 {
Eric Laurent6c796322019-04-09 14:13:17 -07001765 Mutex::Autolock _l(mLock);
1766 {
1767 Mutex::Autolock _cl(mClientLock);
1768 mNotificationClients.removeItem(pid);
1769 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001770
Eric Laurent6c796322019-04-09 14:13:17 -07001771 ALOGV("%d died, releasing its sessions", pid);
1772 size_t num = mAudioSessionRefs.size();
1773 bool removed = false;
1774 for (size_t i = 0; i < num; ) {
1775 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1776 ALOGV(" pid %d @ %zu", ref->mPid, i);
1777 if (ref->mPid == pid) {
1778 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1779 mAudioSessionRefs.removeAt(i);
1780 delete ref;
1781 removed = true;
1782 num--;
1783 } else {
1784 i++;
1785 }
1786 }
1787 if (removed) {
1788 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001789 }
1790 }
Eric Laurent6c796322019-04-09 14:13:17 -07001791 for (auto& effect : removedEffects) {
1792 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794}
1795
Eric Laurent73e26b62015-04-27 16:55:58 -07001796void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001797 const sp<AudioIoDescriptor>& ioDesc,
1798 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799{
Eric Laurent021cf962014-05-13 10:18:14 -07001800 Mutex::Autolock _l(mClientLock);
1801 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001803 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1804 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 }
1807}
1808
Eric Laurent021cf962014-05-13 10:18:14 -07001809// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810void AudioFlinger::removeClient_l(pid_t pid)
1811{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001812 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001813 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 mClients.removeItem(pid);
1815}
1816
Eric Laurent717e1282012-06-29 16:36:52 -07001817// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001818sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1819 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001820{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001821 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001822
1823 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001824 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001825 ALOG_ASSERT(thread == 0);
1826 thread = mPlaybackThreads.valueAt(i);
1827 }
1828 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001829 if (thread != nullptr) {
1830 return thread;
1831 }
1832 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1833 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1834 ALOG_ASSERT(thread == 0);
1835 thread = mRecordThreads.valueAt(i);
1836 }
1837 }
1838 if (thread != nullptr) {
1839 return thread;
1840 }
1841 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1842 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1843 ALOG_ASSERT(thread == 0);
1844 thread = mMmapThreads.valueAt(i);
1845 }
1846 }
Eric Laurent717e1282012-06-29 16:36:52 -07001847 return thread;
1848}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851
1852// ----------------------------------------------------------------------------
1853
1854AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1855 : RefBase(),
1856 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001857 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858{
Andy Hung6f248bb2018-01-23 14:04:37 -08001859 mMemoryDealer = new MemoryDealer(
1860 audioFlinger->getClientSharedHeapSize(),
1861 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862}
1863
Eric Laurent021cf962014-05-13 10:18:14 -07001864// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865AudioFlinger::Client::~Client()
1866{
1867 mAudioFlinger->removeClient_l(mPid);
1868}
1869
Glenn Kasten435dbe62012-01-30 10:15:48 -08001870sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871{
1872 return mMemoryDealer;
1873}
1874
1875// ----------------------------------------------------------------------------
1876
1877AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1878 const sp<IAudioFlingerClient>& client,
1879 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001880 : mAudioFlinger(audioFlinger), mPid(pid), 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 Trivib0de5692019-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);
Eric Laurent488d5002020-05-14 09:13:30 -07002109 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002110 return loadHwModule_l(name);
2111}
2112
Eric Laurent488d5002020-05-14 09:13:30 -07002113// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002114audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2115{
2116 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2117 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2118 ALOGW("loadHwModule() module %s already loaded", name);
2119 return mAudioHwDevs.keyAt(i);
2120 }
2121 }
2122
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002123 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002124
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002125 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002126 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002127 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002128 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002129 }
2130
2131 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002132 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002133 mHardwareStatus = AUDIO_HW_IDLE;
2134 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002135 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002136 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002137 }
2138
John Grossmanee578c02012-07-23 17:05:46 -07002139 // Check and cache this HAL's level of support for master mute and master
2140 // volume. If this is the first HAL opened, and it supports the get
2141 // methods, use the initial values provided by the HAL as the current
2142 // master mute and volume settings.
2143
2144 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent488d5002020-05-14 09:13:30 -07002145 if (0 == mAudioHwDevs.size()) {
2146 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2147 float mv;
2148 if (OK == dev->getMasterVolume(&mv)) {
2149 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002150 }
2151
Eric Laurent488d5002020-05-14 09:13:30 -07002152 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2153 bool mm;
2154 if (OK == dev->getMasterMute(&mm)) {
2155 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002156 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002157 }
Eric Laurent488d5002020-05-14 09:13:30 -07002158
2159 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2160 if (OK == dev->setMasterVolume(mMasterVolume)) {
2161 flags = static_cast<AudioHwDevice::Flags>(flags |
2162 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2163 }
2164
2165 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2166 if (OK == dev->setMasterMute(mMasterMute)) {
2167 flags = static_cast<AudioHwDevice::Flags>(flags |
2168 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2169 }
2170
2171 mHardwareStatus = AUDIO_HW_IDLE;
2172
Mikhail Naganov97373b02018-07-23 13:27:24 -07002173 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002174 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2175 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2176 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002177
Glenn Kastena13cde92016-03-28 15:26:02 -07002178 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent488d5002020-05-14 09:13:30 -07002179 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2180 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2181 mPrimaryHardwareDev = audioDevice;
2182 mHardwareStatus = AUDIO_HW_SET_MODE;
2183 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2184 mHardwareStatus = AUDIO_HW_IDLE;
2185 }
2186
2187 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002188
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002189 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002190
2191 return handle;
2192
2193}
2194
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002195// ----------------------------------------------------------------------------
2196
Glenn Kasten3b16c762012-11-14 08:44:39 -08002197uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002198{
2199 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002200 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002201 return thread != NULL ? thread->sampleRate() : 0;
2202}
2203
Glenn Kastene33054e2012-11-14 12:54:39 -08002204size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002205{
2206 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002207 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002208 return thread != NULL ? thread->frameCountHAL() : 0;
2209}
2210
2211// ----------------------------------------------------------------------------
2212
Andy Hung6f248bb2018-01-23 14:04:37 -08002213status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002214{
2215 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002216 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002217 return PERMISSION_DENIED;
2218 }
2219 Mutex::Autolock _l(mLock);
2220 if (mIsDeviceTypeKnown) {
2221 return INVALID_OPERATION;
2222 }
2223 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002224 mTotalMemory = totalMemory;
2225 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2226 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2227 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2228 // though actual setting is determined through device configuration.
2229 constexpr int64_t GB = 1024 * 1024 * 1024;
2230 mClientSharedHeapSize =
2231 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2232 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2233 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2234 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2235 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002236 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002237
2238 // TODO: Cache the client shared heap size in a persistent property.
2239 // It's possible that a native process or Java service or app accesses audioserver
2240 // after it is registered by system server, but before AudioService updates
2241 // the memory info. This would occur immediately after boot or an audioserver
2242 // crash and restore. Before update from AudioService, the client would get the
2243 // minimum heap size.
2244
2245 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2246 (isLowRamDevice ? "true" : "false"),
2247 (long long)mTotalMemory,
2248 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002249 return NO_ERROR;
2250}
2251
Andy Hung6f248bb2018-01-23 14:04:37 -08002252size_t AudioFlinger::getClientSharedHeapSize() const
2253{
2254 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2255 if (heapSizeInBytes != 0) { // read-only property overrides all.
2256 return heapSizeInBytes;
2257 }
2258 return mClientSharedHeapSize;
2259}
2260
Mikhail Naganovdea53042018-04-26 13:10:21 -07002261status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2262{
2263 ALOGV(__func__);
2264
2265 audio_module_handle_t module;
2266 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2267 module = config->ext.device.hw_module;
2268 } else {
2269 module = config->ext.mix.hw_module;
2270 }
2271
2272 Mutex::Autolock _l(mLock);
Eric Laurent488d5002020-05-14 09:13:30 -07002273 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002274 ssize_t index = mAudioHwDevs.indexOfKey(module);
2275 if (index < 0) {
2276 ALOGW("%s() bad hw module %d", __func__, module);
2277 return BAD_VALUE;
2278 }
2279
2280 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2281 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2282}
2283
Eric Laurent93c3d412014-08-01 14:48:35 -07002284audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2285{
2286 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002287
2288 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2289 if (index >= 0) {
2290 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2291 mHwAvSyncIds.valueAt(index), sessionId);
2292 return mHwAvSyncIds.valueAt(index);
2293 }
2294
Eric Laurent488d5002020-05-14 09:13:30 -07002295 sp<DeviceHalInterface> dev;
2296 {
2297 AutoMutex lock(mHardwareLock);
2298 if (mPrimaryHardwareDev == nullptr) {
2299 return AUDIO_HW_SYNC_INVALID;
2300 }
2301 dev = mPrimaryHardwareDev->hwDevice();
2302 }
2303 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002304 return AUDIO_HW_SYNC_INVALID;
2305 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002306 String8 reply;
2307 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002308 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002309 param = AudioParameter(reply);
2310 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002311
2312 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002313 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002314 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2315 return AUDIO_HW_SYNC_INVALID;
2316 }
2317
2318 // allow only one session for a given HW A/V sync ID.
2319 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2320 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2321 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2322 value, mHwAvSyncIds.keyAt(i));
2323 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002324 break;
2325 }
2326 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002327
2328 mHwAvSyncIds.add(sessionId, value);
2329
2330 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2331 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2332 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002333 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002334 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002335 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002336 String8 keyValuePairs = param.toString();
2337 thread->setParameters(keyValuePairs);
2338 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2339 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002340 break;
2341 }
2342 }
2343
2344 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2345 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002346}
2347
Eric Laurent72e3f392015-05-20 14:43:50 -07002348status_t AudioFlinger::systemReady()
2349{
2350 Mutex::Autolock _l(mLock);
2351 ALOGI("%s", __FUNCTION__);
2352 if (mSystemReady) {
2353 ALOGW("%s called twice", __FUNCTION__);
2354 return NO_ERROR;
2355 }
2356 mSystemReady = true;
2357 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2358 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2359 thread->systemReady();
2360 }
2361 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2362 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2363 thread->systemReady();
2364 }
2365 return NO_ERROR;
2366}
2367
jiabin46a76fa2018-01-05 10:18:21 -08002368status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2369{
jiabin9ff780e2018-03-19 18:19:52 -07002370 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07002371 status_t status = INVALID_OPERATION;
2372
2373 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2374 std::vector<media::MicrophoneInfo> mics;
2375 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2376 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2377 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2378 mHardwareStatus = AUDIO_HW_IDLE;
2379 if (devStatus == NO_ERROR) {
2380 microphones->insert(microphones->begin(), mics.begin(), mics.end());
2381 // report success if at least one HW module supports the function.
2382 status = NO_ERROR;
2383 }
2384 }
2385
jiabin9ff780e2018-03-19 18:19:52 -07002386 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002387}
2388
Eric Laurentfa90e842014-10-17 18:12:31 -07002389// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2390void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2391{
2392 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2393 if (index >= 0) {
2394 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2395 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2396 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002397 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002398 String8 keyValuePairs = param.toString();
2399 thread->setParameters(keyValuePairs);
2400 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2401 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002402 }
2403}
2404
2405
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002406// ----------------------------------------------------------------------------
2407
Eric Laurent83b88082014-06-20 18:31:16 -07002408
Eric Laurent6acd1d42017-01-04 14:23:29 -08002409sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabinc0106832019-10-24 14:58:31 -07002410 audio_io_handle_t *output,
2411 audio_config_t *config,
2412 audio_devices_t deviceType,
2413 const String8& address,
2414 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002415{
jiabinc0106832019-10-24 14:58:31 -07002416 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002417 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002418 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002419 }
2420
Eric Laurentcf2c0212014-07-25 16:20:43 -07002421 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002422 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2423 } else {
2424 // Audio Policy does not currently request a specific output handle.
2425 // If this is ever needed, see openInput_l() for example code.
2426 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2427 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002428 }
Eric Laurent83b88082014-06-20 18:31:16 -07002429
2430 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2431
Eric Laurent83b88082014-06-20 18:31:16 -07002432 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002433 // This if statement allows overriding the audio policy settings
2434 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2435 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2436 // Check only for Normal Mixing mode
2437 if (kEnableExtendedPrecision) {
2438 // Specify format (uncomment one below to choose)
2439 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2440 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2441 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2442 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002443 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002444 }
2445 if (kEnableExtendedChannels) {
2446 // Specify channel mask (uncomment one below to choose)
2447 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2448 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2449 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2450 }
Eric Laurent83b88082014-06-20 18:31:16 -07002451 }
2452
Phil Burk062e67a2015-02-11 13:40:50 -08002453 AudioStreamOut *outputStream = NULL;
2454 status_t status = outHwDev->openOutputStream(
2455 &outputStream,
2456 *output,
jiabinc0106832019-10-24 14:58:31 -07002457 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002458 flags,
2459 config,
2460 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002461
2462 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002463
Phil Burk062e67a2015-02-11 13:40:50 -08002464 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002465 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2466 sp<MmapPlaybackThread> thread =
jiabin10d86fd2019-10-31 17:20:42 -07002467 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002468 mMmapThreads.add(*output, thread);
2469 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2470 *output, thread.get());
2471 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002472 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002473 sp<PlaybackThread> thread;
2474 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabin10d86fd2019-10-31 17:20:42 -07002475 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002476 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2477 *output, thread.get());
2478 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2479 || !isValidPcmSinkFormat(config->format)
2480 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabin10d86fd2019-10-31 17:20:42 -07002481 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002482 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2483 *output, thread.get());
2484 } else {
jiabin10d86fd2019-10-31 17:20:42 -07002485 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002486 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2487 *output, thread.get());
2488 }
2489 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002490 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002491 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002492 }
Eric Laurent83b88082014-06-20 18:31:16 -07002493 }
2494
2495 return 0;
2496}
2497
Eric Laurentcf2c0212014-07-25 16:20:43 -07002498status_t AudioFlinger::openOutput(audio_module_handle_t module,
2499 audio_io_handle_t *output,
2500 audio_config_t *config,
jiabinc0106832019-10-24 14:58:31 -07002501 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002502 uint32_t *latencyMs,
2503 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504{
jiabinc0106832019-10-24 14:58:31 -07002505 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002506 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002507 this, module,
jiabinc0106832019-10-24 14:58:31 -07002508 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002509 config->sample_rate,
2510 config->format,
2511 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002512 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513
jiabinc0106832019-10-24 14:58:31 -07002514 audio_devices_t deviceType = device->type();
2515 const String8 address = String8(device->address().c_str());
2516
2517 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002518 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002519 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 Mutex::Autolock _l(mLock);
2522
jiabinc0106832019-10-24 14:58:31 -07002523 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002524 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002525 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2526 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2527 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 // notify client processes of the new output creation
2530 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002531
Eric Laurent488d5002020-05-14 09:13:30 -07002532 // the first primary output opened designates the primary hw device if no HW module
2533 // named "primary" was already loaded.
2534 AutoMutex lock(mHardwareLock);
2535 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002536 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002537 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002538
Eric Laurent6acd1d42017-01-04 14:23:29 -08002539 mHardwareStatus = AUDIO_HW_SET_MODE;
2540 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2541 mHardwareStatus = AUDIO_HW_IDLE;
2542 }
2543 } else {
2544 MmapThread *mmapThread = (MmapThread *)thread.get();
2545 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002546 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002547 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 }
2549
Eric Laurentcf2c0212014-07-25 16:20:43 -07002550 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002551}
2552
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002553audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2554 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555{
2556 Mutex::Autolock _l(mLock);
2557 MixerThread *thread1 = checkMixerThread_l(output1);
2558 MixerThread *thread2 = checkMixerThread_l(output2);
2559
2560 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002561 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2562 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002563 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 }
2565
Glenn Kasteneeecb982016-02-26 10:44:04 -08002566 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002567 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 thread->addOutputTrack(thread2);
2569 mPlaybackThreads.add(id, thread);
2570 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002571 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 return id;
2573}
2574
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002575status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576{
Glenn Kastend96c5722012-04-25 13:44:49 -07002577 return closeOutput_nonvirtual(output);
2578}
2579
2580status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2581{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 // keep strong reference on the playback thread so that
2583 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002584 sp<PlaybackThread> playbackThread;
2585 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586 {
2587 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002588 playbackThread = checkPlaybackThread_l(output);
2589 if (playbackThread != NULL) {
2590 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591
Andy Hungdc099c22018-09-18 13:46:39 -07002592 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002593
Eric Laurent6acd1d42017-01-04 14:23:29 -08002594 if (playbackThread->type() == ThreadBase::MIXER) {
2595 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2596 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2597 DuplicatingThread *dupThread =
2598 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2599 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2600 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 }
2602 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603
2604
Eric Laurent6acd1d42017-01-04 14:23:29 -08002605 mPlaybackThreads.removeItem(output);
2606 // save all effects to the default thread
2607 if (mPlaybackThreads.size()) {
2608 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2609 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002610 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002611 Mutex::Autolock _dl(dstThread->mLock);
2612 Mutex::Autolock _sl(playbackThread->mLock);
2613 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2614 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002615 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002616 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 }
2619 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002620 } else {
2621 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2622 if (mmapThread == 0) {
2623 return BAD_VALUE;
2624 }
Andy Hungdc099c22018-09-18 13:46:39 -07002625 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002626 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002627 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002629 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2630 ioDesc->mIoHandle = output;
2631 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002632 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002634 // The thread entity (active unit of execution) is no longer running here,
2635 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636
Eric Laurent6acd1d42017-01-04 14:23:29 -08002637 if (playbackThread != 0) {
2638 playbackThread->exit();
2639 if (!playbackThread->isDuplicating()) {
2640 closeOutputFinish(playbackThread);
2641 }
2642 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002643 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002644 mmapThread->exit();
2645 AudioStreamOut *out = mmapThread->clearOutput();
2646 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2647 // from now on thread->mOutput is NULL
2648 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 }
2650 return NO_ERROR;
2651}
2652
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002653void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002654{
2655 AudioStreamOut *out = thread->clearOutput();
2656 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2657 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002658 delete out;
2659}
2660
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002661void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002662{
2663 mPlaybackThreads.removeItem(thread->mId);
2664 thread->exit();
2665 closeOutputFinish(thread);
2666}
2667
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002668status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669{
2670 Mutex::Autolock _l(mLock);
2671 PlaybackThread *thread = checkPlaybackThread_l(output);
2672
2673 if (thread == NULL) {
2674 return BAD_VALUE;
2675 }
2676
Steve Block3856b092011-10-20 11:56:00 +01002677 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 thread->suspend();
2679
2680 return NO_ERROR;
2681}
2682
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002683status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684{
2685 Mutex::Autolock _l(mLock);
2686 PlaybackThread *thread = checkPlaybackThread_l(output);
2687
2688 if (thread == NULL) {
2689 return BAD_VALUE;
2690 }
2691
Steve Block3856b092011-10-20 11:56:00 +01002692 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693
2694 thread->restore();
2695
2696 return NO_ERROR;
2697}
2698
Eric Laurentcf2c0212014-07-25 16:20:43 -07002699status_t AudioFlinger::openInput(audio_module_handle_t module,
2700 audio_io_handle_t *input,
2701 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002702 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002703 const String8& address,
2704 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002705 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706{
Eric Laurent83b88082014-06-20 18:31:16 -07002707 Mutex::Autolock _l(mLock);
2708
Glenn Kastene7d66712015-03-05 13:46:52 -08002709 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002710 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002711 }
2712
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002713 sp<ThreadBase> thread = openInput_l(
2714 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002715
2716 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002717 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002718 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002719 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002721 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002722}
Dima Zavin799a70e2011-04-18 16:57:27 -07002723
Eric Laurent6acd1d42017-01-04 14:23:29 -08002724sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002725 audio_io_handle_t *input,
2726 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002727 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002728 const String8& address,
2729 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002730 audio_input_flags_t flags,
2731 audio_devices_t outputDevice,
2732 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002733{
Glenn Kastene7d66712015-03-05 13:46:52 -08002734 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002735 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002736 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002737 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002738 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002739
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002740 // Some flags are specific to framework and must not leak to the HAL.
2741 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2742
Glenn Kasteneeecb982016-02-26 10:44:04 -08002743 // Audio Policy can request a specific handle for hardware hotword.
2744 // The goal here is not to re-open an already opened input.
2745 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002746 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002747 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2748 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2749 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2750 return 0;
2751 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2752 // This should not happen in a transient state with current design.
2753 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2754 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002755 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002756
Eric Laurentcf2c0212014-07-25 16:20:43 -07002757 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002758 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002759 sp<StreamInHalInterface> inStream;
2760 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002761 *input, devices, &halconfig, flags, address.string(), source,
2762 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002763 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2764 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002765 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002766 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002767 halconfig.sample_rate,
2768 halconfig.format,
2769 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002770 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002771 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002773 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002774 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002775 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002776 audio_is_linear_pcm(config->format) &&
2777 audio_is_linear_pcm(halconfig.format) &&
2778 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002779 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2780 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002781 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002782 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002783 inStream.clear();
2784 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002785 *input, devices, &halconfig, flags, address.string(), source,
2786 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002787 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 }
2789
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002790 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002791 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002792 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2793 sp<MmapCaptureThread> thread =
jiabin10d86fd2019-10-31 17:20:42 -07002794 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002795 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002796 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2797 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002798 return thread;
2799 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002800 // Start record thread
2801 // RecordThread requires both input and output device indication to forward to audio
2802 // pre processing modules
jiabin10d86fd2019-10-31 17:20:42 -07002803 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002804 mRecordThreads.add(*input, thread);
2805 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2806 return thread;
2807 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 }
2809
Eric Laurentcf2c0212014-07-25 16:20:43 -07002810 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811 return 0;
2812}
2813
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002814status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815{
Glenn Kastend96c5722012-04-25 13:44:49 -07002816 return closeInput_nonvirtual(input);
2817}
2818
2819status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2820{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 // keep strong reference on the record thread so that
2822 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002823 sp<RecordThread> recordThread;
2824 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825 {
2826 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002827 recordThread = checkRecordThread_l(input);
2828 if (recordThread != 0) {
2829 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830
Andy Hungdc099c22018-09-18 13:46:39 -07002831 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002832
Eric Laurent6acd1d42017-01-04 14:23:29 -08002833 // If we still have effect chains, it means that a client still holds a handle
2834 // on at least one effect. We must either move the chain to an existing thread with the
2835 // same session ID or put it aside in case a new record thread is opened for a
2836 // new capture on the same session
2837 sp<EffectChain> chain;
2838 {
2839 Mutex::Autolock _sl(recordThread->mLock);
2840 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2841 // Note: maximum one chain per record thread
2842 if (effectChains.size() != 0) {
2843 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002844 }
2845 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002846 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002847 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002848 // This should only happen in case of overlap between one thread tear down and the
2849 // creation of its replacement
2850 size_t i;
2851 for (i = 0; i < mRecordThreads.size(); i++) {
2852 sp<RecordThread> t = mRecordThreads.valueAt(i);
2853 if (t == recordThread) {
2854 continue;
2855 }
2856 if (t->hasAudioSession(chain->sessionId()) != 0) {
2857 Mutex::Autolock _l(t->mLock);
2858 ALOGV("closeInput() found thread %d for effect session %d",
2859 t->id(), chain->sessionId());
2860 t->addEffectChain_l(chain);
2861 break;
2862 }
2863 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002864 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002865 if (i == mRecordThreads.size()) {
2866 putOrphanEffectChain_l(chain);
2867 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002868 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002869 mRecordThreads.removeItem(input);
2870 } else {
2871 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2872 if (mmapThread == 0) {
2873 return BAD_VALUE;
2874 }
Andy Hungdc099c22018-09-18 13:46:39 -07002875 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002876 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002877 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002878 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2879 ioDesc->mIoHandle = input;
2880 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 }
Eric Laurent83b88082014-06-20 18:31:16 -07002882 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2883 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002884 if (recordThread != 0) {
2885 closeInputFinish(recordThread);
2886 } else if (mmapThread != 0) {
2887 mmapThread->exit();
2888 AudioStreamIn *in = mmapThread->clearInput();
2889 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2890 // from now on thread->mInput is NULL
2891 delete in;
2892 }
Eric Laurent83b88082014-06-20 18:31:16 -07002893 return NO_ERROR;
2894}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002896void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002897{
2898 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002899 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002900 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002901 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002902 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002903}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002904
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002905void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002906{
2907 mRecordThreads.removeItem(thread->mId);
2908 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909}
2910
Glenn Kastend2304db2014-02-03 07:40:31 -08002911status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912{
2913 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002914 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915
2916 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2917 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002918 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002919 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002920 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2921 mMmapThreads[i]->invalidateTracks(stream);
2922 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 return NO_ERROR;
2924}
2925
2926
Glenn Kasteneeecb982016-02-26 10:44:04 -08002927audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002928{
Glenn Kasten9d003132016-04-06 14:38:09 -07002929 // This is a binder API, so a malicious client could pass in a bad parameter.
2930 // Check for that before calling the internal API nextUniqueId().
2931 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2932 ALOGE("newAudioUniqueId invalid use %d", use);
2933 return AUDIO_UNIQUE_ID_ALLOCATE;
2934 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002935 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936}
2937
Glenn Kastend848eb42016-03-08 13:42:11 -08002938void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002939{
2940 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002941 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002942 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002943 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2944 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002945 caller = pid;
2946 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002947
Eric Laurent021cf962014-05-13 10:18:14 -07002948 {
2949 Mutex::Autolock _cl(mClientLock);
2950 // Ignore requests received from processes not known as notification client. The request
2951 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2952 // called from a different pid leaving a stale session reference. Also we don't know how
2953 // to clear this reference if the client process dies.
2954 if (mNotificationClients.indexOfKey(caller) < 0) {
2955 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2956 return;
2957 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002958 }
2959
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002960 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002961 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002962 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002963 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2964 ref->mCnt++;
2965 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002966 return;
2967 }
2968 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002969 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2970 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002971}
2972
Glenn Kastend848eb42016-03-08 13:42:11 -08002973void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002974{
Eric Laurent6c796322019-04-09 14:13:17 -07002975 std::vector< sp<EffectModule> > removedEffects;
2976 {
2977 Mutex::Autolock _l(mLock);
2978 pid_t caller = IPCThreadState::self()->getCallingPid();
2979 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2980 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2981 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2982 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002983 }
Eric Laurent6c796322019-04-09 14:13:17 -07002984 size_t num = mAudioSessionRefs.size();
2985 for (size_t i = 0; i < num; i++) {
2986 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2987 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2988 ref->mCnt--;
2989 ALOGV(" decremented refcount to %d", ref->mCnt);
2990 if (ref->mCnt == 0) {
2991 mAudioSessionRefs.removeAt(i);
2992 delete ref;
2993 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2994 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2995 }
2996 goto Exit;
2997 }
2998 }
2999 // If the caller is audioserver it is likely that the session being released was acquired
3000 // on behalf of a process not in notification clients and we ignore the warning.
3001 ALOGW_IF(!isAudioServerUid(callerUid),
3002 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003003 }
Eric Laurent6c796322019-04-09 14:13:17 -07003004
3005Exit:
3006 for (auto& effect : removedEffects) {
3007 effect->updatePolicyState();
3008 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003009}
3010
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003011bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3012{
3013 size_t num = mAudioSessionRefs.size();
3014 for (size_t i = 0; i < num; i++) {
3015 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3016 if (ref->mSessionid == audioSession) {
3017 return true;
3018 }
3019 }
3020 return false;
3021}
3022
Eric Laurent6c796322019-04-09 14:13:17 -07003023std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003024
Steve Block3856b092011-10-20 11:56:00 +01003025 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003026
3027 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003028 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003029
3030 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3031 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003032 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003033 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3034 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurenta20c4e92019-11-12 15:55:51 -08003035 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003036 chains.push(ec);
3037 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003038 }
3039 }
Eric Laurent6c796322019-04-09 14:13:17 -07003040
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003041 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3042 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003043 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003044 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3045 sp<EffectChain> ec = t->mEffectChains[j];
3046 chains.push(ec);
3047 }
3048 }
3049
Eric Laurent6c796322019-04-09 14:13:17 -07003050 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3051 sp<MmapThread> t = mMmapThreads.valueAt(i);
3052 Mutex::Autolock _l(t->mLock);
3053 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3054 sp<EffectChain> ec = t->mEffectChains[j];
3055 chains.push(ec);
3056 }
3057 }
3058
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003059 for (size_t i = 0; i < chains.size(); i++) {
3060 sp<EffectChain> ec = chains[i];
3061 int sessionid = ec->sessionId();
Eric Laurent5d885392019-12-13 10:56:31 -08003062 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003063 if (t == 0) {
3064 continue;
3065 }
3066 size_t numsessionrefs = mAudioSessionRefs.size();
3067 bool found = false;
3068 for (size_t k = 0; k < numsessionrefs; k++) {
3069 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003070 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003071 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003072 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003073 found = true;
3074 break;
3075 }
3076 }
3077 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003078 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003079 // remove all effects from the chain
3080 while (ec->mEffects.size()) {
3081 sp<EffectModule> effect = ec->mEffects[0];
3082 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003083 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003084 if (effect->purgeHandles()) {
Eric Laurent5d885392019-12-13 10:56:31 -08003085 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003086 }
Eric Laurent6c796322019-04-09 14:13:17 -07003087 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003088 }
3089 }
3090 }
Eric Laurent6c796322019-04-09 14:13:17 -07003091 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003092}
3093
Andy Hungdc099c22018-09-18 13:46:39 -07003094// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3095void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3096{
3097 audio_utils::FdToString fdToString;
3098 const int fd = fdToString.fd();
3099 if (fd >= 0) {
3100 thread->dump(fd, {} /* args */);
3101 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3102 }
3103}
3104
Glenn Kasteneeecb982016-02-26 10:44:04 -08003105// checkThread_l() must be called with AudioFlinger::mLock held
3106AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3107{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003108 ThreadBase *thread = checkMmapThread_l(ioHandle);
3109 if (thread == 0) {
3110 switch (audio_unique_id_get_use(ioHandle)) {
3111 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3112 thread = checkPlaybackThread_l(ioHandle);
3113 break;
3114 case AUDIO_UNIQUE_ID_USE_INPUT:
3115 thread = checkRecordThread_l(ioHandle);
3116 break;
3117 default:
3118 break;
3119 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003120 }
3121 return thread;
3122}
3123
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003125AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126{
Glenn Kastena1117922012-01-26 10:53:32 -08003127 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128}
3129
3130// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003131AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132{
3133 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003134 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135}
3136
3137// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003138AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139{
Glenn Kastena1117922012-01-26 10:53:32 -08003140 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141}
3142
Eric Laurent6acd1d42017-01-04 14:23:29 -08003143// checkMmapThread_l() must be called with AudioFlinger::mLock held
3144AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3145{
3146 return mMmapThreads.valueFor(io).get();
3147}
3148
3149
3150// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3151AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3152{
Eric Laurent7459b902017-04-19 18:10:41 -07003153 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003154 if (volumeInterface == nullptr) {
3155 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3156 if (mmapThread != nullptr) {
3157 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003158 MmapPlaybackThread *mmapPlaybackThread =
3159 static_cast<MmapPlaybackThread *>(mmapThread);
3160 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003161 }
3162 }
3163 }
3164 return volumeInterface;
3165}
3166
3167Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3168{
3169 Vector <VolumeInterface *> volumeInterfaces;
3170 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003171 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003172 }
3173 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3174 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003175 MmapPlaybackThread *mmapPlaybackThread =
3176 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3177 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003178 }
3179 }
3180 return volumeInterfaces;
3181}
3182
Glenn Kasteneeecb982016-02-26 10:44:04 -08003183audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184{
Glenn Kasten9d003132016-04-06 14:38:09 -07003185 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003186 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003187 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3188 for (int retry = 0; retry < maxRetries; retry++) {
3189 // The cast allows wraparound from max positive to min negative instead of abort
3190 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3191 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3192 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3193 // allow wrap by skipping 0 and -1 for session ids
3194 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3195 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3196 return (audio_unique_id_t) (base | use);
3197 }
3198 }
3199 // We have no way of recovering from wraparound
3200 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3201 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202}
3203
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003204AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003205{
Eric Laurent488d5002020-05-14 09:13:30 -07003206 AutoMutex lock(mHardwareLock);
3207 if (mPrimaryHardwareDev == nullptr) {
3208 return nullptr;
3209 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003210 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3211 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003212 if(thread->isDuplicating()) {
3213 continue;
3214 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003215 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003216 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003217 return thread;
3218 }
3219 }
Eric Laurent488d5002020-05-14 09:13:30 -07003220 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003221}
3222
jiabin10d86fd2019-10-31 17:20:42 -07003223DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003224{
3225 PlaybackThread *thread = primaryPlaybackThread_l();
3226
3227 if (thread == NULL) {
jiabin10d86fd2019-10-31 17:20:42 -07003228 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003229 }
3230
jiabin10d86fd2019-10-31 17:20:42 -07003231 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003232}
3233
Glenn Kastena7335632016-06-09 17:09:53 -07003234AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3235{
3236 size_t minFrameCount = 0;
3237 PlaybackThread *minThread = NULL;
3238 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3239 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3240 if (!thread->isDuplicating()) {
3241 size_t frameCount = thread->frameCountHAL();
3242 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3243 (frameCount == minFrameCount && thread->hasFastMixer() &&
3244 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3245 minFrameCount = frameCount;
3246 minThread = thread;
3247 }
3248 }
3249 }
3250 return minThread;
3251}
3252
Eric Laurenta011e352012-03-29 15:51:43 -07003253sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003254 audio_session_t triggerSession,
3255 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003256 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003257 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003258{
3259 Mutex::Autolock _l(mLock);
3260
3261 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3262 status_t playStatus = NAME_NOT_FOUND;
3263 status_t recStatus = NAME_NOT_FOUND;
3264 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3265 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3266 if (playStatus == NO_ERROR) {
3267 return event;
3268 }
3269 }
3270 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3271 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3272 if (recStatus == NO_ERROR) {
3273 return event;
3274 }
3275 }
3276 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3277 mPendingSyncEvents.add(event);
3278 } else {
3279 ALOGV("createSyncEvent() invalid event %d", event->type());
3280 event.clear();
3281 }
3282 return event;
3283}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003284
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285// ----------------------------------------------------------------------------
3286// Effect management
3287// ----------------------------------------------------------------------------
3288
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003289sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3290 return mEffectsFactoryHal;
3291}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292
Glenn Kastenf587ba52012-01-26 16:25:10 -08003293status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294{
3295 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003296 if (mEffectsFactoryHal.get()) {
3297 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3298 } else {
3299 return -ENODEV;
3300 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301}
3302
Glenn Kastenf587ba52012-01-26 16:25:10 -08003303status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304{
3305 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003306 if (mEffectsFactoryHal.get()) {
3307 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3308 } else {
3309 return -ENODEV;
3310 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311}
3312
Glenn Kasten5e92a782012-01-30 07:40:52 -08003313status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003314 const effect_uuid_t *pTypeUuid,
3315 uint32_t preferredTypeFlag,
3316 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003318 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3319 return BAD_VALUE;
3320 }
3321
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003323
3324 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003325 return -ENODEV;
3326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003328 status_t status = NO_ERROR;
3329 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3330 // If uuid is specified, request effect descriptor from that.
3331 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3332 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3333 // If uuid is not specified, look for an available implementation
3334 // of the required type instead.
3335
3336 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3337 effect_descriptor_t desc;
3338 desc.flags = 0; // prevent compiler warning
3339
3340 uint32_t numEffects = 0;
3341 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3342 if (status < 0) {
3343 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3344 return status;
3345 }
3346
3347 bool found = false;
3348 for (uint32_t i = 0; i < numEffects; i++) {
3349 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3350 if (status < 0) {
3351 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3352 continue;
3353 }
3354 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3355 // If matching type found save effect descriptor.
3356 found = true;
3357 *descriptor = desc;
3358
3359 // If there's no preferred flag or this descriptor matches the preferred
3360 // flag, success! If this descriptor doesn't match the preferred
3361 // flag, continue enumeration in case a better matching version of this
3362 // effect type is available. Note that this means if no effect with a
3363 // correct flag is found, the descriptor returned will correspond to the
3364 // last effect that at least had a matching type uuid (if any).
3365 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3366 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3367 break;
3368 }
3369 }
3370 }
3371
3372 if (!found) {
3373 status = NAME_NOT_FOUND;
3374 ALOGW("getEffectDescriptor(): Effect not found by type.");
3375 }
3376 } else {
3377 status = BAD_VALUE;
3378 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3379 }
3380 return status;
3381}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003383sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 effect_descriptor_t *pDesc,
3385 const sp<IEffectClient>& effectClient,
3386 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003387 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003388 audio_session_t sessionId,
Eric Laurent9b2064c2019-11-22 17:25:04 -08003389 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003390 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003391 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 status_t *status,
3393 int *id,
3394 int *enabled)
3395{
3396 status_t lStatus = NO_ERROR;
3397 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399
Eric Laurentb6436272016-12-07 19:24:50 -08003400 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003401 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003402 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3403 ALOGW_IF(pid != -1 && pid != callingPid,
3404 "%s uid %d pid %d tried to pass itself off as pid %d",
3405 __func__, callingUid, callingPid, pid);
3406 pid = callingPid;
3407 }
3408
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003409 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3410 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411
3412 if (pDesc == NULL) {
3413 lStatus = BAD_VALUE;
3414 goto Exit;
3415 }
3416
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003417 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003418 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003419 lStatus = NO_INIT;
3420 goto Exit;
3421 }
3422
Andy Hung6096dcd2019-03-13 13:20:30 -07003423 // check audio settings permission for global effects
3424 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3425 if (!settingsAllowed()) {
3426 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3427 lStatus = PERMISSION_DENIED;
3428 goto Exit;
3429 }
3430 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3431 if (!isAudioServerUid(callingUid)) {
3432 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3433 lStatus = PERMISSION_DENIED;
3434 goto Exit;
3435 }
3436
3437 if (io == AUDIO_IO_HANDLE_NONE) {
3438 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3439 lStatus = BAD_VALUE;
3440 goto Exit;
3441 }
Eric Laurenta20c4e92019-11-12 15:55:51 -08003442 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3443 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3444 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3445 lStatus = PERMISSION_DENIED;
3446 goto Exit;
3447 }
Eric Laurentfefebb52019-11-13 12:45:28 -08003448 if (io != AUDIO_IO_HANDLE_NONE) {
3449 ALOGE("%s: io handle should not be specified for device effect", __func__);
3450 lStatus = BAD_VALUE;
3451 goto Exit;
3452 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003453 } else {
3454 // general sessionId.
3455
3456 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3457 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3458 lStatus = BAD_VALUE;
3459 goto Exit;
3460 }
3461
3462 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3463 // to prevent creating an effect when one doesn't actually have track with that session?
3464 }
3465
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003467 // Get the full effect descriptor from the uuid/type.
3468 // If the session is the output mix, prefer an auxiliary effect,
3469 // otherwise no preference.
3470 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3471 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3472 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3473 if (lStatus < 0) {
3474 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3475 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 }
3477
3478 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003479 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3481 lStatus = INVALID_OPERATION;
3482 goto Exit;
3483 }
3484
Eric Laurent59255e42011-07-27 19:49:51 -07003485 // check recording permission for visualizer
3486 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003487 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurenta20c4e92019-11-12 15:55:51 -08003488 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003489 lStatus = PERMISSION_DENIED;
3490 goto Exit;
3491 }
3492
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003494 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003495 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003496 // if the output returned by getOutputForEffect() is removed before we lock the
3497 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3498 // and we will exit safely
3499 io = AudioSystem::getOutputForEffect(&desc);
3500 ALOGV("createEffect got output %d", io);
3501 }
3502
3503 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504
Eric Laurent9b2064c2019-11-22 17:25:04 -08003505 if (sessionId == AUDIO_SESSION_DEVICE) {
3506 sp<Client> client = registerPid(pid);
3507 ALOGV("%s device type %d address %s", __func__, device.mType, device.getAddress());
3508 handle = mDeviceEffectManager.createEffect_l(
3509 &desc, device, client, effectClient, mPatchPanel.patches_l(),
3510 enabled, &lStatus);
3511 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3512 // remove local strong reference to Client with mClientLock held
3513 Mutex::Autolock _cl(mClientLock);
3514 client.clear();
3515 } else {
3516 // handle must be valid here, but check again to be safe.
3517 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3518 }
3519 goto Register;
3520 }
3521
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 // If output is not specified try to find a matching audio session ID in one of the
3523 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003524 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3525 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003526 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3527 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003528 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003529 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003530 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3531 if (io == AUDIO_IO_HANDLE_NONE) {
3532 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003534 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003535 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003536 }
Andy Hung444bb552019-03-14 17:06:39 -07003537
3538 // If you wish to create a Record preprocessing AudioEffect in Java,
3539 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3540 // Otherwise it will fail when created on a Playback thread by legacy
3541 // handling below. Ditto with Mmap, the associated Mmap track must be created
3542 // before creating the AudioEffect or the io handle must be specified.
3543 //
3544 // Detect if the effect is created after an AudioRecord is destroyed.
3545 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3546 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3547 " for session %d no longer exists",
3548 __func__, desc.name, sessionId);
3549 lStatus = PERMISSION_DENIED;
3550 goto Exit;
3551 }
3552
3553 // Legacy handling of creating an effect on an expired or made-up
3554 // session id. We think that it is a Playback effect.
3555 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003556 // If no output thread contains the requested session ID, default to
3557 // first output. The effect chain will be moved to the correct output
3558 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003559 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003560 io = mPlaybackThreads.keyAt(0);
3561 }
Steve Block3856b092011-10-20 11:56:00 +01003562 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003563 } else if (checkPlaybackThread_l(io) != nullptr) {
3564 // allow only one effect chain per sessionId on mPlaybackThreads.
3565 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3566 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3567 if (io == checkIo) continue;
3568 const uint32_t sessionType =
3569 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3570 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3571 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3572 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3573 android_errorWriteLog(0x534e4554, "123237974");
3574 lStatus = BAD_VALUE;
3575 goto Exit;
3576 }
3577 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003578 }
3579 ThreadBase *thread = checkRecordThread_l(io);
3580 if (thread == NULL) {
3581 thread = checkPlaybackThread_l(io);
3582 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003583 thread = checkMmapThread_l(io);
3584 if (thread == NULL) {
3585 ALOGE("createEffect() unknown output thread");
3586 lStatus = BAD_VALUE;
3587 goto Exit;
3588 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003589 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003590 } else {
3591 // Check if one effect chain was awaiting for an effect to be created on this
3592 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003593 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003594 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003595 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003596 thread->addEffectChain_l(chain);
3597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003599
Eric Laurent021cf962014-05-13 10:18:14 -07003600 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003602 // create effect on selected output thread
Eric Laurenta20c4e92019-11-12 15:55:51 -08003603 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003604 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003605 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003606 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003607 // remove local strong reference to Client with mClientLock held
3608 Mutex::Autolock _cl(mClientLock);
3609 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003610 } else {
3611 // handle must be valid here, but check again to be safe.
3612 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003613 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 }
3615
Eric Laurent9b2064c2019-11-22 17:25:04 -08003616Register:
Eric Laurent6c796322019-04-09 14:13:17 -07003617 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3618 // Check CPU and memory usage
Eric Laurente0b9a362019-12-16 19:34:05 -08003619 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003620 if (effect != nullptr) {
3621 status_t rStatus = effect->updatePolicyState();
3622 if (rStatus != NO_ERROR) {
3623 lStatus = rStatus;
3624 }
3625 }
3626 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003627 handle.clear();
3628 }
3629
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003631 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 return handle;
3633}
3634
Glenn Kastend848eb42016-03-08 13:42:11 -08003635status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003636 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003637{
Steve Block3856b092011-10-20 11:56:00 +01003638 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003639 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003640 Mutex::Autolock _l(mLock);
3641 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003642 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003643 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644 }
Eric Laurentde070132010-07-13 04:45:46 -07003645 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3646 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003647 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003648 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649 }
Eric Laurentde070132010-07-13 04:45:46 -07003650 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3651 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003652 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003653 return BAD_VALUE;
3654 }
3655
3656 Mutex::Autolock _dl(dstThread->mLock);
3657 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003658 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659}
3660
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003661
3662void AudioFlinger::setEffectSuspended(int effectId,
3663 audio_session_t sessionId,
3664 bool suspended)
3665{
3666 Mutex::Autolock _l(mLock);
3667
3668 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3669 if (thread == nullptr) {
3670 return;
3671 }
3672 Mutex::Autolock _sl(thread->mLock);
3673 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3674 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3675}
3676
3677
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003678// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003679status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003680 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003681 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003682{
Steve Block3856b092011-10-20 11:56:00 +01003683 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003684 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003685
Eric Laurent59255e42011-07-27 19:49:51 -07003686 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003687 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003688 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003689 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003690 return INVALID_OPERATION;
3691 }
3692
Eric Laurent4c415062016-06-17 16:14:16 -07003693 // Check whether the destination thread and all effects in the chain are compatible
3694 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003695 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003696 " destination thread %p is not compatible with effects in the chain",
3697 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003698 return INVALID_OPERATION;
3699 }
3700
Eric Laurent39e94f82010-07-28 01:32:47 -07003701 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003702 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003703 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003704 // removed.
3705 srcThread->removeEffectChain_l(chain);
3706
3707 // transfer all effects one by one so that new effect chain is created on new thread with
3708 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003709 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003710 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003711 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003712 Vector< sp<EffectModule> > removed;
3713 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003714 while (effect != 0) {
3715 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003716 removed.add(effect);
3717 status = dstThread->addEffect_l(effect);
3718 if (status != NO_ERROR) {
3719 break;
3720 }
Eric Laurentec35a142011-10-05 17:42:25 -07003721 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3722 if (effect->state() == EffectModule::ACTIVE ||
3723 effect->state() == EffectModule::STOPPING) {
3724 effect->start();
3725 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003726 // if the move request is not received from audio policy manager, the effect must be
3727 // re-registered with the new strategy and output
3728 if (dstChain == 0) {
Eric Laurent5d885392019-12-13 10:56:31 -08003729 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003730 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003731 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003732 status = NO_INIT;
3733 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003734 }
3735 strategy = dstChain->strategy();
3736 }
Eric Laurentde070132010-07-13 04:45:46 -07003737 effect = chain->getEffectFromId_l(0);
3738 }
3739
Eric Laurent5baf2af2013-09-12 17:37:00 -07003740 if (status != NO_ERROR) {
3741 for (size_t i = 0; i < removed.size(); i++) {
3742 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003743 }
3744 }
3745
3746 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747}
3748
Eric Laurent6c796322019-04-09 14:13:17 -07003749status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3750 const sp<PlaybackThread>& dstThread,
3751 sp<PlaybackThread> *srcThread)
3752{
3753 status_t status = NO_ERROR;
3754 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003755 sp<PlaybackThread> thread =
3756 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003757
3758 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3759 Mutex::Autolock _dl(dstThread->mLock);
3760 Mutex::Autolock _sl(thread->mLock);
3761 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3762 sp<EffectChain> dstChain;
3763 if (srcChain == 0) {
3764 return INVALID_OPERATION;
3765 }
3766
3767 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3768 if (effect == 0) {
3769 return INVALID_OPERATION;
3770 }
3771 thread->removeEffect_l(effect);
3772 status = dstThread->addEffect_l(effect);
3773 if (status != NO_ERROR) {
3774 thread->addEffect_l(effect);
3775 status = INVALID_OPERATION;
3776 goto Exit;
3777 }
3778
Eric Laurent5d885392019-12-13 10:56:31 -08003779 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003780 if (dstChain == 0) {
3781 thread->addEffect_l(effect);
3782 status = INVALID_OPERATION;
3783 }
3784
3785Exit:
3786 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3787 if (effect->state() == EffectModule::ACTIVE ||
3788 effect->state() == EffectModule::STOPPING) {
3789 effect->start();
3790 }
3791 }
3792
3793 if (status == NO_ERROR && srcThread != nullptr) {
3794 *srcThread = thread;
3795 }
3796 return status;
3797}
3798
Eric Laurent5baf2af2013-09-12 17:37:00 -07003799bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003800{
3801 if (mGlobalEffectEnableTime != 0 &&
3802 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3803 return true;
3804 }
3805
3806 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3807 sp<EffectChain> ec =
3808 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003809 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003810 return true;
3811 }
3812 }
3813 return false;
3814}
3815
Eric Laurent5baf2af2013-09-12 17:37:00 -07003816void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003817{
3818 Mutex::Autolock _l(mLock);
3819
3820 mGlobalEffectEnableTime = systemTime();
3821
3822 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3823 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3824 if (t->mType == ThreadBase::OFFLOAD) {
3825 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3826 }
3827 }
3828
3829}
3830
Eric Laurentaaa44472014-09-12 17:41:50 -07003831status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3832{
Eric Laurentd8365c52017-07-16 15:27:05 -07003833 // clear possible suspended state before parking the chain so that it starts in default state
3834 // when attached to a new record thread
3835 chain->setEffectSuspended_l(FX_IID_AEC, false);
3836 chain->setEffectSuspended_l(FX_IID_NS, false);
3837
Glenn Kastend848eb42016-03-08 13:42:11 -08003838 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003839 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003840 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003841 if (index >= 0) {
3842 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3843 return ALREADY_EXISTS;
3844 }
3845 mOrphanEffectChains.add(session, chain);
3846 return NO_ERROR;
3847}
3848
3849sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3850{
3851 sp<EffectChain> chain;
3852 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003853 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003854 if (index >= 0) {
3855 chain = mOrphanEffectChains.valueAt(index);
3856 mOrphanEffectChains.removeItemsAt(index);
3857 }
3858 return chain;
3859}
3860
3861bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3862{
3863 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003864 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003865 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003866 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003867 if (index >= 0) {
3868 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003869 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003870 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003871 mOrphanEffectChains.removeItemsAt(index);
3872 }
3873 return true;
3874 }
3875 return false;
3876}
3877
3878
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879// ----------------------------------------------------------------------------
3880
3881status_t AudioFlinger::onTransact(
3882 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3883{
3884 return BnAudioFlinger::onTransact(code, data, reply, flags);
3885}
3886
Glenn Kasten63238ef2015-03-02 15:50:29 -08003887} // namespace android