blob: 13ee5cfa6ac65af06a1577eb8df46c41d1fb3bf9 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioPolicyService"
18//#define LOG_NDEBUG 0
19
Glenn Kasten153b9fe2013-07-15 11:23:36 -070020#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070021#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070022#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053023#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070024
25#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070026#include <binder/IServiceManager.h>
27#include <utils/Log.h>
28#include <cutils/properties.h>
29#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080030#include <binder/PermissionController.h>
31#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Atneya Nair5b1ed642023-06-23 14:43:37 -070034#include "AudioRecordClient.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080037#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070038#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080039#include <media/AudioParameter.h>
Andy Hungc747c532022-03-07 21:41:14 -080040#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070041#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080042#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080043#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
Dima Zavin64760242011-05-11 14:15:23 -070045#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070046#include <system/audio_policy.h>
Mikhail Naganov68e3f642023-04-28 13:06:32 -070047#include <AudioPolicyConfig.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053048#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080051using binder::Status;
Shunkai Yao49bc61f2023-10-10 19:31:10 +000052using media::audio::common::Spatialization;
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Glenn Kasten8dad0e32012-01-09 08:41:22 -080054static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
55static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053056static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mikhail Naganov959e2d02019-03-28 11:08:19 -070058static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Eric Laurent0ede8922014-05-09 18:04:42 -070060static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010061
Svet Ganovf4ddfef2018-01-16 07:37:58 -080062static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070063
Atneya Nairdb6ef1e2024-09-16 20:26:30 +000064namespace {
65constexpr auto PERMISSION_GRANTED = permission::PermissionChecker::PERMISSION_GRANTED;
66}
67
Andy Hungc747c532022-03-07 21:41:14 -080068// Creates an association between Binder code to name for IAudioPolicyService.
69#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
70BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
71BINDER_METHOD_ENTRY(setDeviceConnectionState) \
72BINDER_METHOD_ENTRY(getDeviceConnectionState) \
73BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
74BINDER_METHOD_ENTRY(setPhoneState) \
75BINDER_METHOD_ENTRY(setForceUse) \
76BINDER_METHOD_ENTRY(getForceUse) \
77BINDER_METHOD_ENTRY(getOutput) \
78BINDER_METHOD_ENTRY(getOutputForAttr) \
79BINDER_METHOD_ENTRY(startOutput) \
80BINDER_METHOD_ENTRY(stopOutput) \
81BINDER_METHOD_ENTRY(releaseOutput) \
82BINDER_METHOD_ENTRY(getInputForAttr) \
83BINDER_METHOD_ENTRY(startInput) \
84BINDER_METHOD_ENTRY(stopInput) \
85BINDER_METHOD_ENTRY(releaseInput) \
Vlad Popa87e0e582024-05-20 18:49:20 -070086BINDER_METHOD_ENTRY(setDeviceAbsoluteVolumeEnabled) \
Andy Hungc747c532022-03-07 21:41:14 -080087BINDER_METHOD_ENTRY(initStreamVolume) \
88BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
89BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
90BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
91BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
92BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
93BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
94BINDER_METHOD_ENTRY(getStrategyForStream) \
95BINDER_METHOD_ENTRY(getDevicesForAttributes) \
96BINDER_METHOD_ENTRY(getOutputForEffect) \
97BINDER_METHOD_ENTRY(registerEffect) \
98BINDER_METHOD_ENTRY(unregisterEffect) \
99BINDER_METHOD_ENTRY(setEffectEnabled) \
100BINDER_METHOD_ENTRY(moveEffectsToIo) \
101BINDER_METHOD_ENTRY(isStreamActive) \
102BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
103BINDER_METHOD_ENTRY(isSourceActive) \
104BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
105BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
106BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
107BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
108BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
109BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
110BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
111BINDER_METHOD_ENTRY(getOffloadSupport) \
112BINDER_METHOD_ENTRY(isDirectOutputSupported) \
113BINDER_METHOD_ENTRY(listAudioPorts) \
114BINDER_METHOD_ENTRY(getAudioPort) \
115BINDER_METHOD_ENTRY(createAudioPatch) \
116BINDER_METHOD_ENTRY(releaseAudioPatch) \
117BINDER_METHOD_ENTRY(listAudioPatches) \
118BINDER_METHOD_ENTRY(setAudioPortConfig) \
119BINDER_METHOD_ENTRY(registerClient) \
120BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
121BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
122BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
123BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
124BINDER_METHOD_ENTRY(getPhoneState) \
125BINDER_METHOD_ENTRY(registerPolicyMixes) \
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +0200126BINDER_METHOD_ENTRY(updatePolicyMixes) \
Andy Hungc747c532022-03-07 21:41:14 -0800127BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
128BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
129BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
130BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
131BINDER_METHOD_ENTRY(startAudioSource) \
132BINDER_METHOD_ENTRY(stopAudioSource) \
133BINDER_METHOD_ENTRY(setMasterMono) \
134BINDER_METHOD_ENTRY(getMasterMono) \
135BINDER_METHOD_ENTRY(getStreamVolumeDB) \
136BINDER_METHOD_ENTRY(getSurroundFormats) \
137BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
138BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
139BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
140BINDER_METHOD_ENTRY(setAssistantServicesUids) \
141BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
142BINDER_METHOD_ENTRY(setA11yServicesUids) \
143BINDER_METHOD_ENTRY(setCurrentImeUid) \
144BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
145BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800146BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800147BINDER_METHOD_ENTRY(listAudioProductStrategies) \
148BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
149BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
150BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
151BINDER_METHOD_ENTRY(setRttEnabled) \
152BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
153BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
154BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000155BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800156BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
157BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
158BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
159BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
160BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
161BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
162BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
163BINDER_METHOD_ENTRY(getSpatializer) \
164BINDER_METHOD_ENTRY(canBeSpatialized) \
165BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000166BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
167BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
168BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
169BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
170BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100171BINDER_METHOD_ENTRY(getRegisteredPolicyMixes) \
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700172BINDER_METHOD_ENTRY(getPermissionController) \
jiabin7ed22ff2024-10-04 20:51:21 +0000173BINDER_METHOD_ENTRY(getMmapPolicyInfos) \
174BINDER_METHOD_ENTRY(getMmapPolicyForDevice) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100175 \
Andy Hungc747c532022-03-07 21:41:14 -0800176// singleton for Binder Method Statistics for IAudioPolicyService
177static auto& getIAudioPolicyServiceStatistics() {
178 using Code = int;
179
180#pragma push_macro("BINDER_METHOD_ENTRY")
181#undef BINDER_METHOD_ENTRY
182#define BINDER_METHOD_ENTRY(ENTRY) \
183 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
184
185 static mediautils::MethodStatistics<Code> methodStatistics{
186 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
187 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
188 };
189#pragma pop_macro("BINDER_METHOD_ENTRY")
190
191 return methodStatistics;
192}
193
Mathias Agopian65ab4712010-07-14 17:59:35 -0700194// ----------------------------------------------------------------------------
195
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530196static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
197{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700198 AudioPolicyManager *apm = nullptr;
199 media::AudioPolicyConfig apmConfig;
200 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
201 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
François Gaffiead3dce92024-03-26 17:20:04 +0100202 ALOGD("%s loading APM engine %s", __func__, config->getEngineLibraryNameSuffix().c_str());
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700203 apm = new AudioPolicyManager(config,
204 loadApmEngineLibraryAndCreateEngine(
205 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
206 clientInterface);
207 } else {
208 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
209 apm = new AudioPolicyManager(config,
210 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
211 clientInterface);
212 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530213 status_t status = apm->initialize();
214 if (status != NO_ERROR) {
215 delete apm;
216 apm = nullptr;
217 }
218 return apm;
219}
220
221static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
222{
223 delete interface;
224}
225// ----------------------------------------------------------------------------
226
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700228 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700229 mAudioPolicyManager(NULL),
230 mAudioPolicyClient(NULL),
231 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530232 mCaptureStateNotifier(false),
233 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100234 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700235 mUsecaseValidator(media::createUsecaseValidator()),
236 mPermissionController(sp<NativePermissionController>::make())
237{
Andy Hung225aef62022-12-06 16:33:20 -0800238 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Andy Hung58b01b12024-03-26 18:04:29 -0700239 setInheritRt(true);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530240}
241
242void AudioPolicyService::loadAudioPolicyManager()
243{
244 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
245 if (mLibraryHandle != nullptr) {
246 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
247 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
248 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
249 const char *lastError = dlerror();
250 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
251 __func__, lastError != nullptr ? lastError : "no error");
252
253 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
254 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
255 lastError = dlerror();
256 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
257 __func__, lastError != nullptr ? lastError : "no error");
258 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
259 unloadAudioPolicyManager();
260 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
261 }
262 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700263}
264
265void AudioPolicyService::onFirstRef()
266{
Andy Hungd47aca22022-03-15 11:50:51 -0700267 // Log an AudioPolicy "constructor" mediametrics event on first ref.
268 // This records the time it takes to load the audio modules and devices.
269 mediametrics::Defer defer([beginNs = systemTime()] {
270 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
271 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
272 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
273 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700274 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800275 audio_utils::lock_guard _l(mMutex);
Eric Laurent93575202011-01-18 18:39:02 -0800276
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700277 // start audio commands thread
278 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
279 // start output activity command thread
280 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700281
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700282 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530283
284 loadAudioPolicyManager();
285 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700286 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200287
bryant_liuba2b4392014-06-11 16:49:30 +0800288 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000289 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
Andy Hungd3595ed2023-12-19 15:34:46 -0800290 auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
291 auto uidPolicy = sp<UidPolicy>::make(this);
292 auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700293 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800294 audio_utils::lock_guard _l(mMutex);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700295 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000296 mUidPolicy = uidPolicy;
297 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700298 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000299 uidPolicy->registerSelf();
300 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200301
Eric Laurent81dd0f52021-07-05 11:54:40 +0200302 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200303 if (mAudioPolicyManager != nullptr) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800304 audio_utils::lock_guard _l(mMutex);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200305 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
306 AudioDeviceTypeAddrVector devices;
307 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
308 if (hasSpatializer) {
Andy Hung1040da52023-12-06 20:59:06 -0800309 // Unlock as Spatializer::create() will use the callback and acquire the
310 // AudioPolicyService_Mutex.
Andy Hung79eacdb2023-11-30 19:34:24 -0800311 mMutex.unlock();
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000312 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Andy Hung79eacdb2023-11-30 19:34:24 -0800313 mMutex.lock();
Eric Laurent52b0bd52021-09-27 15:25:40 +0200314 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700315 if (mSpatializer == nullptr) {
316 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
317 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
318 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
319 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200320 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200321 AudioSystem::audioPolicyReady();
Andy Hungb08b3752024-01-09 19:05:23 -0800322}
323
Atneya Nair87818d32024-05-23 10:59:30 -0700324const IPermissionProvider& AudioPolicyService::getPermissionProvider() const {
325 return *mPermissionController;
326}
327
Andy Hungb08b3752024-01-09 19:05:23 -0800328void AudioPolicyService::onAudioSystemReady() {
329 sp<AudioPolicyEffects> audioPolicyEffects;
330 {
331 audio_utils::lock_guard _l(mMutex);
332
333 audioPolicyEffects = mAudioPolicyEffects;
334 }
335 audioPolicyEffects->initDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336}
337
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530338void AudioPolicyService::unloadAudioPolicyManager()
339{
340 ALOGV("%s ", __func__);
341 if (mLibraryHandle != nullptr) {
342 dlclose(mLibraryHandle);
343 }
344 mLibraryHandle = nullptr;
345 mCreateAudioPolicyManager = nullptr;
346 mDestroyAudioPolicyManager = nullptr;
347}
348
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349AudioPolicyService::~AudioPolicyService()
350{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700352 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700353
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530354 mDestroyAudioPolicyManager(mAudioPolicyManager);
355 unloadAudioPolicyManager();
356
Eric Laurentdce54a12014-03-10 12:19:46 -0700357 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700358
359 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800360 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800361
362 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800363 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000364
365 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800366 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700367}
368
369// A notification client is always registered by AudioSystem when the client process
370// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800371Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700372{
Eric Laurent12590252015-08-21 18:40:20 -0700373 if (client == 0) {
374 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800375 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700376 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800377 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700378
379 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800380 pid_t pid = IPCThreadState::self()->getCallingPid();
381 int64_t token = ((int64_t)uid<<32) | pid;
382
383 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700384 sp<NotificationClient> notificationClient = new NotificationClient(this,
385 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800386 uid,
387 pid);
388 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700389
luochaojiang908c7d72018-06-21 14:58:04 +0800390 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700391
Marco Nelissenf8880202014-11-14 07:58:25 -0800392 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700393 binder->linkToDeath(notificationClient);
394 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800395 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700396}
397
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800398Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700399{
Andy Hung79eacdb2023-11-30 19:34:24 -0800400 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurente8726fe2015-06-26 09:39:24 -0700401
402 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800403 pid_t pid = IPCThreadState::self()->getCallingPid();
404 int64_t token = ((int64_t)uid<<32) | pid;
405
406 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800407 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700408 }
luochaojiang908c7d72018-06-21 14:58:04 +0800409 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800410 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700411}
412
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800413Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100414{
Andy Hung79eacdb2023-11-30 19:34:24 -0800415 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100416
417 uid_t uid = IPCThreadState::self()->getCallingUid();
418 pid_t pid = IPCThreadState::self()->getCallingPid();
419 int64_t token = ((int64_t)uid<<32) | pid;
420
421 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800422 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100423 }
424 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800425 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100426}
427
Eric Laurentb52c1522014-05-20 11:27:36 -0700428// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800429void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700430{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000431 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800432 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800433 audio_utils::lock_guard _l(mNotificationClientsMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800434 int64_t token = ((int64_t)uid<<32) | pid;
435 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800436 for (size_t i = 0; i < mNotificationClients.size(); i++) {
437 if (mNotificationClients.valueAt(i)->uid() == uid) {
438 hasSameUid = true;
439 break;
440 }
441 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000442 }
443 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800444 audio_utils::lock_guard _l(mMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800445 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700446 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700447 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700448 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800449 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700450}
451
452void AudioPolicyService::onAudioPortListUpdate()
453{
454 mOutputCommandThread->updateAudioPortListCommand();
455}
456
457void AudioPolicyService::doOnAudioPortListUpdate()
458{
Andy Hung79eacdb2023-11-30 19:34:24 -0800459 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700460 for (size_t i = 0; i < mNotificationClients.size(); i++) {
461 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
462 }
463}
464
465void AudioPolicyService::onAudioPatchListUpdate()
466{
467 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468}
469
Eric Laurentb52c1522014-05-20 11:27:36 -0700470void AudioPolicyService::doOnAudioPatchListUpdate()
471{
Andy Hung79eacdb2023-11-30 19:34:24 -0800472 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700473 for (size_t i = 0; i < mNotificationClients.size(); i++) {
474 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
475 }
476}
477
François Gaffiecfe17322018-11-07 13:41:29 +0100478void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
479{
480 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
481}
482
483void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
484{
Andy Hung79eacdb2023-11-30 19:34:24 -0800485 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100486 for (size_t i = 0; i < mNotificationClients.size(); i++) {
487 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
488 }
489}
490
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700491void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700492{
493 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000494 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700495 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
496}
497
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700498void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700499{
Andy Hung79eacdb2023-11-30 19:34:24 -0800500 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700501 for (size_t i = 0; i < mNotificationClients.size(); i++) {
502 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
503 }
504}
505
Eric Laurenta9f86652018-11-28 17:23:11 -0800506void AudioPolicyService::onRecordingConfigurationUpdate(
507 int event,
508 const record_client_info_t *clientInfo,
509 const audio_config_base_t *clientConfig,
510 std::vector<effect_descriptor_t> clientEffects,
511 const audio_config_base_t *deviceConfig,
512 std::vector<effect_descriptor_t> effects,
513 audio_patch_handle_t patchHandle,
514 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800515{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800516 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800517 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800518}
519
Eric Laurenta9f86652018-11-28 17:23:11 -0800520void AudioPolicyService::doOnRecordingConfigurationUpdate(
521 int event,
522 const record_client_info_t *clientInfo,
523 const audio_config_base_t *clientConfig,
524 std::vector<effect_descriptor_t> clientEffects,
525 const audio_config_base_t *deviceConfig,
526 std::vector<effect_descriptor_t> effects,
527 audio_patch_handle_t patchHandle,
528 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800529{
Andy Hung79eacdb2023-11-30 19:34:24 -0800530 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800531 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800532 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800533 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800534 }
535}
536
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700537void AudioPolicyService::onRoutingUpdated()
538{
539 mOutputCommandThread->routingChangedCommand();
540}
541
542void AudioPolicyService::doOnRoutingUpdated()
543{
Andy Hung79eacdb2023-11-30 19:34:24 -0800544 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700545 for (size_t i = 0; i < mNotificationClients.size(); i++) {
546 mNotificationClients.valueAt(i)->onRoutingUpdated();
547 }
548}
549
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000550void AudioPolicyService::onVolumeRangeInitRequest()
551{
552 mOutputCommandThread->volRangeInitReqCommand();
553}
554
555void AudioPolicyService::doOnVolumeRangeInitRequest()
556{
Andy Hung79eacdb2023-11-30 19:34:24 -0800557 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000558 for (size_t i = 0; i < mNotificationClients.size(); i++) {
559 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
560 }
561}
562
Eric Laurent81dd0f52021-07-05 11:54:40 +0200563void AudioPolicyService::onCheckSpatializer()
564{
Andy Hung79eacdb2023-11-30 19:34:24 -0800565 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200566 onCheckSpatializer_l();
567}
568
569void AudioPolicyService::onCheckSpatializer_l()
570{
571 if (mSpatializer != nullptr) {
572 mOutputCommandThread->checkSpatializerCommand();
573 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200574}
575
576void AudioPolicyService::doOnCheckSpatializer()
577{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200578 ALOGV("%s mSpatializer %p level %d",
579 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200580
Eric Laurent39095982021-08-24 18:29:27 +0200581 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200582 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000583 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200584 audio_io_handle_t currentOutput = mSpatializer->getOutput();
585 audio_io_handle_t newOutput;
586 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
587 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200588
Andy Hung79eacdb2023-11-30 19:34:24 -0800589 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200590 status_t status =
591 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100592 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
593 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200594 if (status == NO_ERROR && currentOutput == newOutput) {
595 return;
596 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000597 std::vector<audio_channel_mask_t> activeTracksMasks =
598 getActiveTracksMasks_l(newOutput);
Andy Hung79eacdb2023-11-30 19:34:24 -0800599 mMutex.unlock();
Eric Laurent39095982021-08-24 18:29:27 +0200600 // It is OK to call detachOutput() is none is already attached.
601 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200602 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000603 status = mSpatializer->attachOutput(newOutput, activeTracksMasks);
Eric Laurent39095982021-08-24 18:29:27 +0200604 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800605 mMutex.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200606 if (status != NO_ERROR) {
607 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
608 }
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000609 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
610 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200611 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200612
Eric Laurent39095982021-08-24 18:29:27 +0200613 if (output != AUDIO_IO_HANDLE_NONE) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800614 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200615 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200616 }
617 }
618 }
619}
620
Eric Laurentb16eac52024-08-02 16:46:08 +0000621std::vector<audio_channel_mask_t> AudioPolicyService::getActiveTracksMasks_l(
Eric Laurent11094172022-04-05 18:27:42 +0200622 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000623 std::vector<audio_channel_mask_t> activeTrackMasks;
Eric Laurent15903592022-02-24 20:44:36 +0100624 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
625 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200626 if (client->io == output && client->active
627 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000628 activeTrackMasks.push_back(client->channelMask);
Eric Laurent15903592022-02-24 20:44:36 +0100629 }
630 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000631 return activeTrackMasks;
Eric Laurent15903592022-02-24 20:44:36 +0100632}
633
634void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
635 if (mSpatializer == nullptr) {
636 return;
637 }
638 mOutputCommandThread->updateActiveSpatializerTracksCommand();
639}
640
641void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
642{
Eric Laurent21270b62022-07-04 15:11:29 +0200643 if (mSpatializer == nullptr) {
644 return;
645 }
646 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurentb16eac52024-08-02 16:46:08 +0000647 std::vector<audio_channel_mask_t> activeTracksMasks;
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200648 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800649 audio_utils::lock_guard _l(mMutex);
Eric Laurentb16eac52024-08-02 16:46:08 +0000650 activeTracksMasks = getActiveTracksMasks_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100651 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000652 mSpatializer->updateActiveTracks(activeTracksMasks);
Eric Laurent15903592022-02-24 20:44:36 +0100653}
654
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800655status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
656 audio_patch_handle_t *handle,
657 int delayMs)
658{
659 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
660}
661
662status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
663 int delayMs)
664{
665 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
666}
667
Eric Laurente1715a42014-05-20 11:30:42 -0700668status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
669 int delayMs)
670{
671 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
672}
673
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800674AudioPolicyService::NotificationClient::NotificationClient(
675 const sp<AudioPolicyService>& service,
676 const sp<media::IAudioPolicyServiceClient>& client,
677 uid_t uid,
678 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800679 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100680 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700681{
682}
683
684AudioPolicyService::NotificationClient::~NotificationClient()
685{
686}
687
688void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
689{
690 sp<NotificationClient> keep(this);
691 sp<AudioPolicyService> service = mService.promote();
692 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800693 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700694 }
695}
696
697void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
698{
Eric Laurente8726fe2015-06-26 09:39:24 -0700699 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700700 mAudioPolicyServiceClient->onAudioPortListUpdate();
701 }
702}
703
704void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
705{
Eric Laurente8726fe2015-06-26 09:39:24 -0700706 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700707 mAudioPolicyServiceClient->onAudioPatchListUpdate();
708 }
709}
Eric Laurent57dae992011-07-24 13:36:09 -0700710
Pattydd807582021-11-04 21:01:03 +0800711void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100712 int flags)
713{
714 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
715 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
716 }
717}
718
719
Jean-Michel Trivide801052015-04-14 19:10:14 -0700720void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700721 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700722{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700723 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800724 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
725 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800726 }
727}
728
729void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800730 int event,
731 const record_client_info_t *clientInfo,
732 const audio_config_base_t *clientConfig,
733 std::vector<effect_descriptor_t> clientEffects,
734 const audio_config_base_t *deviceConfig,
735 std::vector<effect_descriptor_t> effects,
736 audio_patch_handle_t patchHandle,
737 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800738{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700739 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800740 status_t status = [&]() -> status_t {
741 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
742 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
743 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700744 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700745 legacy2aidl_audio_config_base_t_AudioConfigBase(
746 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800747 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
748 convertContainer<std::vector<media::EffectDescriptor>>(
749 clientEffects,
750 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700751 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700752 legacy2aidl_audio_config_base_t_AudioConfigBase(
753 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800754 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
755 convertContainer<std::vector<media::EffectDescriptor>>(
756 effects,
757 legacy2aidl_effect_descriptor_t_EffectDescriptor));
758 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
759 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700760 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
761 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800762 return aidl_utils::statusTFromBinderStatus(
763 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
764 clientInfoAidl,
765 clientConfigAidl,
766 clientEffectsAidl,
767 deviceConfigAidl,
768 effectsAidl,
769 patchHandleAidl,
770 sourceAidl));
771 }();
772 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700773 }
774}
775
Eric Laurente8726fe2015-06-26 09:39:24 -0700776void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
777{
778 mAudioPortCallbacksEnabled = enabled;
779}
780
François Gaffiecfe17322018-11-07 13:41:29 +0100781void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
782{
783 mAudioVolumeGroupCallbacksEnabled = enabled;
784}
Eric Laurente8726fe2015-06-26 09:39:24 -0700785
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700786void AudioPolicyService::NotificationClient::onRoutingUpdated()
787{
788 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
789 mAudioPolicyServiceClient->onRoutingUpdated();
790 }
791}
792
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000793void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
794{
795 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
796 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
797 }
798}
799
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700801 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700802 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803}
804
Andy Hung79eacdb2023-11-30 19:34:24 -0800805static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
806 RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000807{
808 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809}
810
811status_t AudioPolicyService::dumpInternals(int fd)
812{
813 const size_t SIZE = 256;
814 char buffer[SIZE];
815 String8 result;
816
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000817 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800818 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000819 std::stringstream msg;
820 size_t i = 0;
821 for (auto usage : mSupportedSystemUsages) {
822 if (i++ != 0) msg << ", ";
823 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
824 msg << strUsage;
825 } else {
826 msg << usage << " (unknown)";
827 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800828 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000829 if (i == 0) {
830 msg << "None";
831 }
832 msg << std::endl;
833 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800834
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000835 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800836
837 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 return NO_ERROR;
839}
840
Eric Laurente8c8b432018-10-17 10:08:02 -0700841void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800842{
Andy Hung79eacdb2023-11-30 19:34:24 -0800843 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -0700844 updateUidStates_l();
845}
846
847void AudioPolicyService::updateUidStates_l()
848{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800849// Go over all active clients and allow capture (does not force silence) in the
850// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800851// The client is in the active assistant list
852// AND is TOP
853// AND an accessibility service is TOP
854// AND source is either VOICE_RECOGNITION OR HOTWORD
855// OR there is no active privacy sensitive capture or call
856// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
857// AND source is VOICE_RECOGNITION OR HOTWORD
858// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800859// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700860// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800861// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800862// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800863// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
864// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800865// OR The client is an accessibility service
866// AND Is on TOP
867// AND the source is VOICE_RECOGNITION or HOTWORD
868// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700869// AND there is no active privacy sensitive capture or call
870// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800871// AND is on TOP
872// AND the source is VOICE_RECOGNITION or HOTWORD
873// OR the client source is virtual (remote submix, call audio TX or RX...)
874// OR the client source is HOTWORD
875// AND is on TOP
876// OR all active clients are using HOTWORD source
877// AND no call is active
878// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
879// OR the client is the current InputMethodService
880// AND a RTT call is active AND the source is VOICE_RECOGNITION
Shunkai Yao7c868ca2024-05-07 01:08:11 +0000881// OR The client is an active communication owner
882// AND is on TOP or latest started
Evan Severson1f700cd2021-02-10 13:10:37 -0800883// OR Any client
884// AND The assistant is not on TOP
885// AND is on TOP or latest started
886// AND there is no active privacy sensitive capture or call
887// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800888
Eric Laurent4e947da2019-10-17 15:24:06 -0700889
Eric Laurent4eb58f12018-12-07 16:41:02 -0800890 sp<AudioRecordClient> topActive;
891 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800892 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700893 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800894 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700895
Eric Laurenta46bedb2018-12-07 18:01:26 -0800896 nsecs_t topStartNs = 0;
897 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800898 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800899 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800900 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800901 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
902 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800903 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800904 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700905 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800906 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
907 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700908 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700909 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700910 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800911
Michael Groovercfd28302018-12-11 19:16:46 -0800912 // if Sensor Privacy is enabled then all recordings should be silenced.
913 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
914 silenceAllRecordings_l();
915 return;
916 }
917
Eric Laurente8c8b432018-10-17 10:08:02 -0700918 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
919 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000920 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
921 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800922 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700923 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800924 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700925
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700926 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700927 // clients which app is in IDLE state are not eligible for top active or
928 // latest active
929 if (appState == APP_STATE_IDLE) {
930 continue;
931 }
932
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700933 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700934 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800935 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700936 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700937 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800938 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800939 bool isPrivacySensitive =
940 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700941
Eric Laurentc21d5692020-02-25 10:24:36 -0800942 if (appState == APP_STATE_TOP) {
943 if (isPrivacySensitive) {
944 if (current->startTimeNs > topSensitiveStartNs) {
945 topSensitiveActive = current;
946 topSensitiveStartNs = current->startTimeNs;
947 }
948 } else {
949 if (current->startTimeNs > topStartNs) {
950 topActive = current;
951 topStartNs = current->startTimeNs;
952 }
953 }
954 if (isAssistant) {
955 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800956 if (isActiveAssistant) {
957 useActiveAssistantList = true;
958 } else if (!useActiveAssistantList) {
959 if (current->startTimeNs > latestAssistantStartNs) {
960 latestActiveAssistant = current;
961 latestAssistantStartNs = current->startTimeNs;
962 }
963 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800964 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800965 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800966 // Clients capturing for HOTWORD are not considered
967 // for latest active to avoid masking regular clients started before
968 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
969 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
970 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700971 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
972 // is marked latest sensitive active even if another app qualifies.
973 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700974 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700975 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700976 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000977 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700978 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700979 latestSensitiveActiveOrComm = current;
980 latestSensitiveStartNs = current->startTimeNs;
981 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800982 }
983 isSensitiveActive = true;
984 } else {
985 if (current->startTimeNs > latestStartNs) {
986 latestActive = current;
987 latestStartNs = current->startTimeNs;
988 }
989 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800990 }
991 }
François Gaffiedb1a4412023-10-10 17:32:33 +0000992 if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
993 !isVirtualSource(current->attributes.source)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700994 onlyHotwordActive = false;
995 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100996 if (currentUid == mPhoneStateOwnerUid &&
997 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700998 isPhoneStateOwnerActive = true;
999 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001000 }
1001
Eric Laurent1ff16a72019-03-14 18:35:04 -07001002 // if no active client with UI on Top, consider latest active as top
1003 if (topActive == nullptr) {
1004 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -08001005 topStartNs = latestStartNs;
1006 }
1007 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -07001008 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -08001009 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -07001010 } else if (latestSensitiveActiveOrComm != nullptr) {
1011 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
1012 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001013 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +00001014 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001015 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -07001016 topSensitiveActive = latestSensitiveActiveOrComm;
1017 topSensitiveStartNs = latestSensitiveStartNs;
1018 }
Eric Laurentc21d5692020-02-25 10:24:36 -08001019 }
1020
1021 // If both privacy sensitive and regular capture are active:
1022 // if the regular capture is privileged
1023 // allow concurrency
1024 // else
1025 // favor the privacy sensitive case
1026 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001027 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001028 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001029 }
1030
1031 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1032 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001033 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001034 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001035 if (!current->active) {
1036 continue;
1037 }
1038
Eric Laurent4eb58f12018-12-07 16:41:02 -08001039 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001040 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001041 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001042 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001043 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001044 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1045 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001046
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001047 // TODO: b/339112720
1048 // Refine this logic when we have the correct phone state owner UID. The current issue is
1049 // when a VOIP APP use Telecom API to manage calls, the mPhoneStateOwnerUid is AID_SYSTEM
1050 // instead of the actual VOIP APP UID, so isPhoneStateOwnerActive here is not accurate.
1051 const bool canCaptureIfInCallOrCommunication = [&](const auto& recordClient) REQUIRES(
1052 mMutex) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001053 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001054 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001055 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001056 bool canCaptureCommunication = recordClient->canCaptureOutput
1057 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001058 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001059 return !(isInCall && !canCaptureCall)
1060 && !(isInCommunication && !canCaptureCommunication);
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001061 }(current);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001062
1063 // By default allow capture if:
1064 // The assistant is not on TOP
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001065 // AND is on TOP or latest started
1066 // AND there is no active privacy sensitive capture or call
Eric Laurent1ff16a72019-03-14 18:35:04 -07001067 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001068 // The assistant is on TOP
1069 // AND is ongoing communication owner
1070 // AND is on TOP or latest started
1071 const bool allowSensitiveCapture =
Eric Laurent4ab18412022-11-07 16:25:32 +01001072 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001073 bool allowCapture = false;
1074 if (!isAssistantOnTop) {
1075 allowCapture = (isTopOrLatestActive || isTopOrLatestSensitive) &&
1076 allowSensitiveCapture && canCaptureIfInCallOrCommunication;
1077 } else {
1078 allowCapture = isInCommunication && isTopOrLatestSensitive &&
1079 canCaptureIfInCallOrCommunication;
1080 }
Eric Laurent2dc962b2019-03-01 08:25:25 -08001081
Eric Laurented726cc2021-07-01 14:26:41 +02001082 if (!current->hasOp()) {
1083 // Never allow capture if app op is denied
1084 allowCapture = false;
1085 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001086 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1087 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001088 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001089 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001090 // Active assistant list is not being used
1091 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001092 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001093 // OR there is no active privacy sensitive capture or call
1094 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1095 // AND is latest TOP assistant AND
1096 // uses VOICE_RECOGNITION OR uses HOTWORD
1097 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001098 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001099 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001100 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001101 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001102 } else if (allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001103 && canCaptureIfInCallOrCommunication) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001104 if (isTopOrLatestAssistant
1105 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1106 || source == AUDIO_SOURCE_HOTWORD)) {
1107 allowCapture = true;
1108 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1109 allowCapture = true;
1110 }
1111 }
1112 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1113 // For assistant on active list and on top allow capture if:
1114 // An accessibility service is on TOP
1115 // AND the source is VOICE_RECOGNITION or HOTWORD
1116 // OR there is no active privacy sensitive capture or call
1117 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1118 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1119 if (isA11yOnTop) {
1120 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1121 allowCapture = true;
1122 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001123 } else if (allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001124 && canCaptureIfInCallOrCommunication) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001125 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1126 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001127 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001128 }
1129 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001130 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001131 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001132 // The assistant is not on TOP
1133 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001134 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001135 // OR
1136 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1137 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001138 && allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001139 && canCaptureIfInCallOrCommunication) {
Eric Laurent47670c92019-08-28 16:59:05 -07001140 allowCapture = true;
1141 }
Eric Laurent589171c2019-07-25 18:04:29 -07001142 if (isA11yOnTop) {
1143 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1144 allowCapture = true;
1145 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001146 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001147 } else if (source == AUDIO_SOURCE_HOTWORD) {
1148 // For HOTWORD source allow capture when not on TOP if:
1149 // All active clients are using HOTWORD source
1150 // AND no call is active
1151 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001152 if (onlyHotwordActive
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001153 && canCaptureIfInCallOrCommunication) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001154 allowCapture = true;
1155 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001156 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001157 // For current InputMethodService allow capture if:
1158 // A RTT call is active AND the source is VOICE_RECOGNITION
1159 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1160 allowCapture = true;
1161 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001162 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001163 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001164 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001165 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001166 }
1167}
1168
Michael Groovercfd28302018-12-11 19:16:46 -08001169void AudioPolicyService::silenceAllRecordings_l() {
1170 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1171 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001172 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001173 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001174 }
Michael Groovercfd28302018-12-11 19:16:46 -08001175 }
1176}
1177
Eric Laurente8c8b432018-10-17 10:08:02 -07001178/* static */
1179app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001180
1181 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001182 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001183 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1184 // include persistent services
1185 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001186 }
1187 return APP_STATE_FOREGROUND;
1188}
1189
Eric Laurent4eb58f12018-12-07 16:41:02 -08001190/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001191bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001192{
1193 switch (source) {
1194 case AUDIO_SOURCE_VOICE_UPLINK:
1195 case AUDIO_SOURCE_VOICE_DOWNLINK:
1196 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001197 case AUDIO_SOURCE_REMOTE_SUBMIX:
1198 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001199 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001200 return true;
1201 default:
1202 break;
1203 }
1204 return false;
1205}
1206
Eric Laurent8c7ef892021-06-10 13:32:16 +02001207void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001208{
1209 AutoCallerClear acc;
1210
1211 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001212 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001213 }
1214 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1215 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001216 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001217 if (client->silenced != silenced) {
1218 if (client->active) {
1219 if (silenced) {
Marvin Raminb03b49f2024-04-04 16:25:31 +02001220 finishRecording(client->attributionSource, client->virtualDeviceId,
1221 client->attributes.source);
Eric Laurent8c7ef892021-06-10 13:32:16 +02001222 } else {
1223 std::stringstream msg;
1224 msg << "Audio recording un-silenced on session " << client->session;
Atneya Nairdb6ef1e2024-09-16 20:26:30 +00001225 if (startRecording(client->attributionSource, client->virtualDeviceId,
1226 String16(msg.str().c_str()), client->attributes.source)
1227 != PERMISSION_GRANTED) {
1228 return;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001229 }
1230 }
1231 }
1232 af->setRecordSilenced(client->portId, silenced);
1233 client->silenced = silenced;
1234 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001235 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001236}
1237
Glenn Kasten0f11b512014-01-31 16:18:54 -08001238status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Andy Hung79eacdb2023-11-30 19:34:24 -08001239NO_THREAD_SAFETY_ANALYSIS // update for trylock.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240{
Glenn Kasten44deb052012-02-05 18:09:08 -08001241 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 dumpPermissionDenial(fd);
1243 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001244 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 if (!locked) {
1246 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001247 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 }
1249
1250 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001251
1252 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001253 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001254 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255 mAudioCommandThread->dump(fd);
1256 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001258 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001259 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001260 if (mOutputCommandThread != 0) {
1261 mOutputCommandThread->dump(fd);
1262 }
1263
Eric Laurentdce54a12014-03-10 12:19:46 -07001264 if (mAudioPolicyManager) {
1265 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001266 } else {
1267 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001268 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001269 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270
Kevin Rocard8be94972019-02-22 13:26:25 -08001271 mPackageManager.dump(fd);
1272
Andy Hung79eacdb2023-11-30 19:34:24 -08001273 dumpReleaseLock(mMutex, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001274
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001275 if (mSpatializer != nullptr) {
1276 std::string dumpString = mSpatializer->toString(1 /* level */);
1277 write(fd, dumpString.c_str(), dumpString.size());
1278 } else {
1279 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1280 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1281 }
1282
Andy Hungc747c532022-03-07 21:41:14 -08001283 {
1284 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1285 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1286 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288 }
1289 return NO_ERROR;
1290}
1291
1292status_t AudioPolicyService::dumpPermissionDenial(int fd)
1293{
1294 const size_t SIZE = 256;
1295 char buffer[SIZE];
1296 String8 result;
1297 snprintf(buffer, SIZE, "Permission Denial: "
1298 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1299 IPCThreadState::self()->getCallingPid(),
1300 IPCThreadState::self()->getCallingUid());
1301 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001302 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303 return NO_ERROR;
1304}
1305
1306status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001307 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001308 // make sure transactions reserved to AudioFlinger do not come from other processes
1309 switch (code) {
1310 case TRANSACTION_startOutput:
1311 case TRANSACTION_stopOutput:
1312 case TRANSACTION_releaseOutput:
1313 case TRANSACTION_getInputForAttr:
1314 case TRANSACTION_startInput:
1315 case TRANSACTION_stopInput:
1316 case TRANSACTION_releaseInput:
1317 case TRANSACTION_getOutputForEffect:
1318 case TRANSACTION_registerEffect:
1319 case TRANSACTION_unregisterEffect:
1320 case TRANSACTION_setEffectEnabled:
1321 case TRANSACTION_getStrategyForStream:
1322 case TRANSACTION_getOutputForAttr:
1323 case TRANSACTION_moveEffectsToIo:
1324 ALOGW("%s: transaction %d received from PID %d",
1325 __func__, code, IPCThreadState::self()->getCallingPid());
1326 return INVALID_OPERATION;
1327 default:
1328 break;
1329 }
1330
1331 // make sure the following transactions come from system components
1332 switch (code) {
1333 case TRANSACTION_setDeviceConnectionState:
1334 case TRANSACTION_handleDeviceConfigChange:
1335 case TRANSACTION_setPhoneState:
1336//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1337// case TRANSACTION_setForceUse:
Vlad Popa87e0e582024-05-20 18:49:20 -07001338 case TRANSACTION_setDeviceAbsoluteVolumeEnabled:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001339 case TRANSACTION_initStreamVolume:
1340 case TRANSACTION_setStreamVolumeIndex:
1341 case TRANSACTION_setVolumeIndexForAttributes:
1342 case TRANSACTION_getStreamVolumeIndex:
1343 case TRANSACTION_getVolumeIndexForAttributes:
1344 case TRANSACTION_getMinVolumeIndexForAttributes:
1345 case TRANSACTION_getMaxVolumeIndexForAttributes:
1346 case TRANSACTION_isStreamActive:
1347 case TRANSACTION_isStreamActiveRemotely:
1348 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001349 case TRANSACTION_registerPolicyMixes:
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02001350 case TRANSACTION_updatePolicyMixes:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001351 case TRANSACTION_setMasterMono:
1352 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001353 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001354 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001355 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001356 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001357 case TRANSACTION_setA11yServicesUids:
1358 case TRANSACTION_setUidDeviceAffinities:
1359 case TRANSACTION_removeUidDeviceAffinities:
1360 case TRANSACTION_setUserIdDeviceAffinities:
1361 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001362 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001363 case TRANSACTION_listAudioVolumeGroups:
1364 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1365 case TRANSACTION_acquireSoundTriggerSession:
1366 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001367 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001368 case TRANSACTION_setRttEnabled:
1369 case TRANSACTION_isCallScreenModeSupported:
1370 case TRANSACTION_setDevicesRoleForStrategy:
1371 case TRANSACTION_setSupportedSystemUsages:
1372 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001373 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001374 case TRANSACTION_getDevicesForRoleAndStrategy:
1375 case TRANSACTION_getDevicesForAttributes:
1376 case TRANSACTION_setAllowedCapturePolicy:
1377 case TRANSACTION_onNewAudioModulesAvailable:
1378 case TRANSACTION_setCurrentImeUid:
1379 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1380 case TRANSACTION_setDevicesRoleForCapturePreset:
1381 case TRANSACTION_addDevicesRoleForCapturePreset:
1382 case TRANSACTION_removeDevicesRoleForCapturePreset:
1383 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001384 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001385 case TRANSACTION_getSpatializer:
1386 case TRANSACTION_setPreferredMixerAttributes:
Marvin Raminbdefaf02023-11-01 09:10:32 +01001387 case TRANSACTION_clearPreferredMixerAttributes:
1388 case TRANSACTION_getRegisteredPolicyMixes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001389 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1390 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1391 __func__, code, IPCThreadState::self()->getCallingPid(),
1392 IPCThreadState::self()->getCallingUid());
1393 return INVALID_OPERATION;
1394 }
1395 } break;
1396 default:
1397 break;
1398 }
1399
Atneya Nair9f91a5e2024-05-09 16:25:05 -07001400 switch (code) {
1401 case TRANSACTION_getPermissionController: {
1402 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1403 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1404 __func__, code, IPCThreadState::self()->getCallingPid(),
1405 IPCThreadState::self()->getCallingUid());
1406 return INVALID_OPERATION;
1407 }
1408 }
1409 }
1410
Andy Hungc747c532022-03-07 21:41:14 -08001411 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1412 mediautils::TimeCheck check(
1413 std::string("IAudioPolicyService::").append(methodName),
1414 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1415 if (timeout) {
1416 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1417 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1418 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1419 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1420 .record();
1421 } else {
1422 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1423 }
Andy Hung7cd77742024-08-06 15:17:16 -07001424 }, mediautils::TimeCheck::getDefaultTimeoutDuration(),
1425 mediautils::TimeCheck::getDefaultSecondChanceDuration(),
Atneya Nairc5b34362024-08-27 17:31:38 -07001426 !property_get_bool("audio.timecheck.disabled", false) /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001427
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001428 switch (code) {
1429 case SHELL_COMMAND_TRANSACTION: {
1430 int in = data.readFileDescriptor();
1431 int out = data.readFileDescriptor();
1432 int err = data.readFileDescriptor();
1433 int argc = data.readInt32();
1434 Vector<String16> args;
1435 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1436 args.add(data.readString16());
1437 }
1438 sp<IBinder> unusedCallback;
1439 sp<IResultReceiver> resultReceiver;
1440 status_t status;
1441 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1442 return status;
1443 }
1444 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1445 return status;
1446 }
1447 status = shellCommand(in, out, err, args);
1448 if (resultReceiver != nullptr) {
1449 resultReceiver->send(status);
1450 }
1451 return NO_ERROR;
1452 }
1453 }
1454
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1456}
1457
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001458// ------------------- Shell command implementation -------------------
1459
1460// NOTE: This is a remote API - make sure all args are validated
1461status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1462 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1463 return PERMISSION_DENIED;
1464 }
1465 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1466 return BAD_VALUE;
1467 }
Atneya Nair56a436a2024-04-03 11:11:58 -07001468 if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
Eric Laurent269acb42021-04-23 16:53:22 +02001469 purgePermissionCache();
1470 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001471 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001472 return BAD_VALUE;
1473}
1474
Eric Laurent0d13fea2022-11-04 17:12:08 +01001475status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1476 const audio_config_base_t& config,
1477 const audio_output_flags_t flags) {
1478 return mUsecaseValidator->registerStream(output, config, flags);
1479}
1480
1481status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1482 return mUsecaseValidator->unregisterStream(output);
1483}
1484
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001485// ----------- AudioPolicyService::UidPolicy implementation ----------
1486
1487void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001488 status_t res = mAm.linkToDeath(this);
1489 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001490 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001491 | ActivityManager::UID_OBSERVER_ACTIVE
1492 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001493 ActivityManager::PROCESS_STATE_UNKNOWN,
1494 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001495 if (!res) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001496 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001497 mObserverRegistered = true;
1498 } else {
1499 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001500
Steven Moreland2f348142019-07-02 15:59:07 -07001501 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001502 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001503}
1504
1505void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001506 mAm.unlinkToDeath(this);
1507 mAm.unregisterUidObserver(this);
Andy Hung79eacdb2023-11-30 19:34:24 -08001508 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001509 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001510}
1511
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001512void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001513 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001514 mCachedUids.clear();
1515 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001516}
1517
Eric Laurente8c8b432018-10-17 10:08:02 -07001518void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001519 bool needToReregister = false;
1520 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001521 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001522 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001523 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001524 if (needToReregister) {
1525 // Looks like ActivityManager has died previously, attempt to re-register.
1526 registerSelf();
1527 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001528}
1529
1530bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1531 if (isServiceUid(uid)) return true;
1532 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001533 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001534 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001535 // In an absense of the ActivityManager, assume everything to be active.
1536 if (!mObserverRegistered) return true;
1537 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001538 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001539 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001540 }
1541 }
1542 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001543 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001544 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001545 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001546 mCachedUids.insert(std::pair<uid_t,
1547 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1548 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001549 }
1550 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001551}
1552
Eric Laurente8c8b432018-10-17 10:08:02 -07001553int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1554 if (isServiceUid(uid)) {
1555 return ActivityManager::PROCESS_STATE_TOP;
1556 }
1557 checkRegistered();
1558 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001559 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001560 // In an absense of the ActivityManager, assume everything to be active.
1561 if (!mObserverRegistered) {
1562 return ActivityManager::PROCESS_STATE_TOP;
1563 }
1564 auto cacheIter = mCachedUids.find(uid);
1565 if (cacheIter != mCachedUids.end()) {
1566 if (cacheIter->second.first) {
1567 return cacheIter->second.second;
1568 } else {
1569 return ActivityManager::PROCESS_STATE_UNKNOWN;
1570 }
1571 }
1572 }
1573 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001574 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001575 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1576 if (active) {
1577 state = am.getUidProcessState(uid, String16("audioserver"));
1578 }
1579 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001580 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001581 mCachedUids.insert(std::pair<uid_t,
1582 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1583 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001584
Eric Laurente8c8b432018-10-17 10:08:02 -07001585 return state;
1586}
1587
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001588void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001589 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001590}
1591
1592void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001593 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001594}
1595
1596void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001597 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001598}
1599
Eric Laurente8c8b432018-10-17 10:08:02 -07001600void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1601 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001602 int64_t procStateSeq __unused,
1603 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001604 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1605 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001606 }
1607}
1608
Austin Borgerdddb7552023-03-30 17:53:01 -07001609void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001610}
1611
Eric Laurente8c8b432018-10-17 10:08:02 -07001612void AudioPolicyService::UidPolicy::notifyService() {
1613 sp<AudioPolicyService> service = mService.promote();
1614 if (service != nullptr) {
1615 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001616 }
1617}
1618
Eric Laurente8c8b432018-10-17 10:08:02 -07001619void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1620 std::pair<bool, int>> *uids,
1621 uid_t uid,
1622 bool active,
1623 int state,
1624 bool insert) {
1625 if (isServiceUid(uid)) {
1626 return;
1627 }
1628 bool wasActive = isUidActive(uid);
1629 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001630 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001631 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001632 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001633 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001634 if (wasActive != isUidActive(uid) || state != previousState) {
1635 notifyService();
1636 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001637}
1638
Eric Laurente8c8b432018-10-17 10:08:02 -07001639void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1640 std::pair<bool, int>> *uids,
1641 uid_t uid,
1642 bool active,
1643 int state,
1644 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001645 auto it = uids->find(uid);
1646 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001647 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001648 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1649 it->second.first = active;
1650 }
1651 if (it->second.first) {
1652 it->second.second = state;
1653 } else {
1654 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1655 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001656 } else {
1657 uids->erase(it);
1658 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001659 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1660 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1661 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001662 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001663}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664
Eric Laurent4eb58f12018-12-07 16:41:02 -08001665bool AudioPolicyService::UidPolicy::isA11yOnTop() {
Andy Hung79eacdb2023-11-30 19:34:24 -08001666 audio_utils::lock_guard _l(mMutex);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001667 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001668 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001669 continue;
1670 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001671 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1672 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001673 return true;
1674 }
1675 }
1676 return false;
1677}
1678
Eric Laurentb78763e2018-10-17 10:08:02 -07001679bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1680{
1681 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1682 return it != mA11yUids.end();
1683}
1684
Oscar Azucena829d90d2022-01-28 17:17:56 -08001685void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1686 mAssistantUids.clear();
1687 mAssistantUids = uids;
1688}
1689
1690bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1691{
1692 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1693 return it != mAssistantUids.end();
1694}
1695
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001696void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1697 mActiveAssistantUids = activeUids;
1698}
1699
1700bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1701{
1702 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1703 mActiveAssistantUids.end(), uid);
1704 return it != mActiveAssistantUids.end();
1705}
1706
Oscar Azucena829d90d2022-01-28 17:17:56 -08001707void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1708 const size_t SIZE = 256;
1709 char buffer[SIZE];
1710 String8 result;
1711 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1712 snprintf(buffer, SIZE, "\t%s: \n", title);
1713 result.append(buffer);
1714 int counter = 0;
1715 if (uids.empty()) {
1716 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1717 result.append(buffer);
1718 return;
1719 }
1720 for (const auto &uid : uids) {
1721 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1722 result.append(buffer);
1723 }
1724 };
1725
1726 snprintf(buffer, SIZE, "UID Policy:\n");
1727 result.append(buffer);
1728 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1729 result.append(buffer);
1730
1731 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001732 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001733
1734 appendUidsToResult("Accessibility UIDs", mA11yUids);
1735
1736 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1737 result.append(buffer);
1738
1739 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1740 result.append(buffer);
1741
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001742 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001743}
1744
Michael Groovercfd28302018-12-11 19:16:46 -08001745// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1746void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1747 SensorPrivacyManager spm;
1748 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1749 spm.addSensorPrivacyListener(this);
1750}
1751
1752void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1753 SensorPrivacyManager spm;
1754 spm.removeSensorPrivacyListener(this);
1755}
1756
1757bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1758 return mSensorPrivacyEnabled;
1759}
1760
Evan Seversond8dc6832022-01-27 10:47:03 -08001761binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1762 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001763 mSensorPrivacyEnabled = enabled;
1764 sp<AudioPolicyService> service = mService.promote();
1765 if (service != nullptr) {
1766 service->updateUidStates();
1767 }
1768 return binder::Status::ok();
1769}
1770
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1772
Eric Laurentbfb1b832013-01-07 09:53:42 -08001773AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1774 const wp<AudioPolicyService>& service)
1775 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777}
1778
1779
1780AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1781{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001782 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001783 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 }
1785 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786}
1787
1788void AudioPolicyService::AudioCommandThread::onFirstRef()
1789{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001790 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791}
1792
1793bool AudioPolicyService::AudioCommandThread::threadLoop()
1794{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001795 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796
Andy Hung79eacdb2023-11-30 19:34:24 -08001797 audio_utils::unique_lock ul(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 while (!exitPending())
1799 {
Eric Laurent59a89232014-06-08 14:14:17 -07001800 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001801 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001802 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 nsecs_t curTime = systemTime();
1804 // commands are sorted by increasing time stamp: execute them from index 0 and up
1805 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001806 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001808 if (mAudioCommands.isEmpty()) {
1809 ++numTimesBecameEmpty;
1810 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001811 mLastCommand = command;
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02001812 status_t createAudioPatchStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813
1814 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001816 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001817 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001818 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001819 ul.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001820 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1821 data->mVolume,
1822 data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001823 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 }break;
Andy Hung6b137d12024-08-27 22:35:17 +00001825 case SET_PORTS_VOLUME: {
1826 VolumePortsData *data = (VolumePortsData *)command->mParam.get();
1827 ALOGV("AudioCommandThread() processing set volume Ports %s volume %f, \
1828 output %d", data->dumpPorts().c_str(), data->mVolume, data->mIO);
1829 ul.unlock();
1830 command->mStatus = AudioSystem::setPortsVolume(data->mPorts,
1831 data->mVolume,
1832 data->mIO);
1833 ul.lock();
1834 } break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001836 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001837 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001838 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001839 ul.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001840 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hung79eacdb2023-11-30 19:34:24 -08001841 ul.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001842 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001844 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001845 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001846 data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001847 ul.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001849 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001851 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001852 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001853 ALOGV("AudioCommandThread() processing stop output portId %d",
1854 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001855 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856 if (svc == 0) {
1857 break;
1858 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001859 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001860 svc->doStopOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001861 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862 }break;
1863 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001864 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001865 ALOGV("AudioCommandThread() processing release output portId %d",
1866 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001867 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868 if (svc == 0) {
1869 break;
1870 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001871 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001872 svc->doReleaseOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001873 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001874 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001875 case CREATE_AUDIO_PATCH: {
1876 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1877 ALOGV("AudioCommandThread() processing create audio patch");
1878 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1879 if (af == 0) {
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02001880 createAudioPatchStatus = PERMISSION_DENIED;
Eric Laurent951f4552014-05-20 10:48:17 -07001881 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001882 ul.unlock();
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02001883 createAudioPatchStatus = af->createAudioPatch(&data->mPatch,
1884 &data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001885 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001886 }
1887 } break;
1888 case RELEASE_AUDIO_PATCH: {
1889 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1890 ALOGV("AudioCommandThread() processing release audio patch");
1891 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1892 if (af == 0) {
1893 command->mStatus = PERMISSION_DENIED;
1894 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001895 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001896 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001897 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001898 }
1899 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001900 case UPDATE_AUDIOPORT_LIST: {
1901 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001902 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001903 if (svc == 0) {
1904 break;
1905 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001906 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001907 svc->doOnAudioPortListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001908 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001909 }break;
1910 case UPDATE_AUDIOPATCH_LIST: {
1911 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001912 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001913 if (svc == 0) {
1914 break;
1915 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001916 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001917 svc->doOnAudioPatchListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001918 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001919 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001920 case CHANGED_AUDIOVOLUMEGROUP: {
1921 AudioVolumeGroupData *data =
1922 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1923 ALOGV("AudioCommandThread() processing update audio volume group");
1924 svc = mService.promote();
1925 if (svc == 0) {
1926 break;
1927 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001928 ul.unlock();
François Gaffiecfe17322018-11-07 13:41:29 +01001929 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
Andy Hung79eacdb2023-11-30 19:34:24 -08001930 ul.lock();
François Gaffiecfe17322018-11-07 13:41:29 +01001931 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001932 case SET_AUDIOPORT_CONFIG: {
1933 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1934 ALOGV("AudioCommandThread() processing set port config");
1935 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1936 if (af == 0) {
1937 command->mStatus = PERMISSION_DENIED;
1938 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001939 ul.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001940 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hung79eacdb2023-11-30 19:34:24 -08001941 ul.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001942 }
1943 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001944 case DYN_POLICY_MIX_STATE_UPDATE: {
1945 DynPolicyMixStateUpdateData *data =
1946 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001947 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001948 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07001949 svc = mService.promote();
1950 if (svc == 0) {
1951 break;
1952 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001953 ul.unlock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001954 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
Andy Hung79eacdb2023-11-30 19:34:24 -08001955 ul.lock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001956 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001957 case RECORDING_CONFIGURATION_UPDATE: {
1958 RecordingConfigurationUpdateData *data =
1959 (RecordingConfigurationUpdateData *)command->mParam.get();
1960 ALOGV("AudioCommandThread() processing recording configuration update");
1961 svc = mService.promote();
1962 if (svc == 0) {
1963 break;
1964 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001965 ul.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001966 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001967 &data->mClientConfig, data->mClientEffects,
1968 &data->mDeviceConfig, data->mEffects,
1969 data->mPatchHandle, data->mSource);
Andy Hung79eacdb2023-11-30 19:34:24 -08001970 ul.lock();
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001971 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001972 case SET_EFFECT_SUSPENDED: {
1973 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1974 ALOGV("AudioCommandThread() processing set effect suspended");
1975 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1976 if (af != 0) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001977 ul.unlock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001978 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
Andy Hung79eacdb2023-11-30 19:34:24 -08001979 ul.lock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001980 }
1981 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001982 case AUDIO_MODULES_UPDATE: {
1983 ALOGV("AudioCommandThread() processing audio modules update");
1984 svc = mService.promote();
1985 if (svc == 0) {
1986 break;
1987 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001988 ul.unlock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001989 svc->doOnNewAudioModulesAvailable();
Andy Hung79eacdb2023-11-30 19:34:24 -08001990 ul.lock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001991 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001992 case ROUTING_UPDATED: {
1993 ALOGV("AudioCommandThread() processing routing update");
1994 svc = mService.promote();
1995 if (svc == 0) {
1996 break;
1997 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001998 ul.unlock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001999 svc->doOnRoutingUpdated();
Andy Hung79eacdb2023-11-30 19:34:24 -08002000 ul.lock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002001 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002002
Eric Laurented726cc2021-07-01 14:26:41 +02002003 case UPDATE_UID_STATES: {
2004 ALOGV("AudioCommandThread() processing updateUID states");
2005 svc = mService.promote();
2006 if (svc == 0) {
2007 break;
2008 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002009 ul.unlock();
Eric Laurented726cc2021-07-01 14:26:41 +02002010 svc->updateUidStates();
Andy Hung79eacdb2023-11-30 19:34:24 -08002011 ul.lock();
Eric Laurented726cc2021-07-01 14:26:41 +02002012 } break;
2013
Eric Laurent15903592022-02-24 20:44:36 +01002014 case CHECK_SPATIALIZER_OUTPUT: {
2015 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002016 svc = mService.promote();
2017 if (svc == 0) {
2018 break;
2019 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002020 ul.unlock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002021 svc->doOnCheckSpatializer();
Andy Hung79eacdb2023-11-30 19:34:24 -08002022 ul.lock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002023 } break;
2024
Eric Laurent15903592022-02-24 20:44:36 +01002025 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2026 ALOGV("AudioCommandThread() processing update spatializer tracks");
2027 svc = mService.promote();
2028 if (svc == 0) {
2029 break;
2030 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002031 ul.unlock();
Eric Laurent15903592022-02-24 20:44:36 +01002032 svc->doOnUpdateActiveSpatializerTracks();
Andy Hung79eacdb2023-11-30 19:34:24 -08002033 ul.lock();
Eric Laurent15903592022-02-24 20:44:36 +01002034 } break;
2035
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002036 case VOL_RANGE_INIT_REQUEST: {
2037 ALOGV("AudioCommandThread() processing volume range init request");
2038 svc = mService.promote();
2039 if (svc == 0) {
2040 break;
2041 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002042 ul.unlock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002043 svc->doOnVolumeRangeInitRequest();
Andy Hung79eacdb2023-11-30 19:34:24 -08002044 ul.lock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002045 } break;
2046
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002048 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002050 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002051 audio_utils::lock_guard _l(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002052 if (command->mWaitStatus) {
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02002053 if (command->mCommand == CREATE_AUDIO_PATCH) {
2054 command->mStatus = createAudioPatchStatus;
2055 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002056 command->mWaitStatus = false;
Andy Hung79eacdb2023-11-30 19:34:24 -08002057 command->mCond.notify_one();
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02002058 } else if (command->mCommand == CREATE_AUDIO_PATCH &&
2059 command->mStatus == TIMED_OUT &&
2060 createAudioPatchStatus == NO_ERROR) {
2061 // Because of special handling in insertCommand_l() the CREATE_AUDIO_PATCH
2062 // command wait status can be only false in case timeout (see TIMED_OUT)
2063 // happened.
2064 CreateAudioPatchData *createData =
2065 (CreateAudioPatchData *)command->mParam.get();
2066 ALOGW("AudioCommandThread() no caller awaiting for handle(%d) after \
2067 processing create audio patch, going to release it",
2068 createData->mHandle);
2069 sp<AudioCommand> releaseCommand = new AudioCommand();
2070 releaseCommand->mCommand = RELEASE_AUDIO_PATCH;
2071 ReleaseAudioPatchData *releaseData = new ReleaseAudioPatchData();
2072 releaseData->mHandle = createData->mHandle;
2073 releaseCommand->mParam = releaseData;
2074 insertCommand_l(releaseCommand, 0);
Eric Laurent0ede8922014-05-09 18:04:42 -07002075 }
2076 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002077 waitTime = -1;
Andy Hung79eacdb2023-11-30 19:34:24 -08002078 // release ul before releasing strong reference on the service as
Zach Janga754b4f2015-10-27 01:29:34 +00002079 // AudioPolicyService destructor calls AudioCommandThread::exit() which
Andy Hung79eacdb2023-11-30 19:34:24 -08002080 // acquires ul.
2081 ul.unlock();
Zach Janga754b4f2015-10-27 01:29:34 +00002082 svc.clear();
Andy Hung79eacdb2023-11-30 19:34:24 -08002083 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 } else {
2085 waitTime = mAudioCommands[0]->mTime - curTime;
2086 break;
2087 }
2088 }
Zach Janga754b4f2015-10-27 01:29:34 +00002089
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002090 // release delayed commands wake lock as many times as we made the queue is
2091 // empty during popping.
2092 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002093 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002094 }
2095
2096 // At this stage we have either an empty command queue or the first command in the queue
2097 // has a finite delay. So unless we are exiting it is safe to wait.
2098 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002099 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002100 if (waitTime == -1) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002101 mWaitWorkCV.wait(ul);
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002102 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002103 // discard return value.
2104 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002105 }
Eric Laurent59a89232014-06-08 14:14:17 -07002106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002108 // release delayed commands wake lock before quitting
2109 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002110 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002111 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 return false;
2113}
2114
2115status_t AudioPolicyService::AudioCommandThread::dump(int fd)
Andy Hung79eacdb2023-11-30 19:34:24 -08002116NO_THREAD_SAFETY_ANALYSIS // trylock
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117{
2118 const size_t SIZE = 256;
2119 char buffer[SIZE];
2120 String8 result;
2121
Andy Hung79eacdb2023-11-30 19:34:24 -08002122 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 if (!locked) {
2124 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002125 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 }
2127
2128 snprintf(buffer, SIZE, "- Commands:\n");
2129 result = String8(buffer);
2130 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002131 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 mAudioCommands[i]->dump(buffer, SIZE);
2133 result.append(buffer);
2134 }
2135 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002136 if (mLastCommand != 0) {
2137 mLastCommand->dump(buffer, SIZE);
2138 result.append(buffer);
2139 } else {
2140 result.append(" none\n");
2141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002143 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144
Andy Hung79eacdb2023-11-30 19:34:24 -08002145 dumpReleaseLock(mMutex, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146
2147 return NO_ERROR;
2148}
2149
Glenn Kastenfff6d712012-01-12 16:38:12 -08002150status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002151 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002152 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002153 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002154{
Eric Laurent0ede8922014-05-09 18:04:42 -07002155 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002157 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 data->mStream = stream;
2159 data->mVolume = volume;
2160 data->mIO = output;
2161 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002162 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002163 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002164 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002165 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166}
2167
Andy Hung6b137d12024-08-27 22:35:17 +00002168status_t AudioPolicyService::AudioCommandThread::volumePortsCommand(
2169 const std::vector<audio_port_handle_t> &ports, float volume, audio_io_handle_t output,
2170 int delayMs)
2171{
2172 sp<AudioCommand> command = new AudioCommand();
2173 command->mCommand = SET_PORTS_VOLUME;
2174 sp<VolumePortsData> data = new VolumePortsData();
2175 data->mPorts = ports;
2176 data->mVolume = volume;
2177 data->mIO = output;
2178 command->mParam = data;
2179 command->mWaitStatus = true;
2180 ALOGV("AudioCommandThread() adding set volume ports %s, volume %f, output %d",
2181 data->dumpPorts().c_str(), volume, output);
2182 return sendCommand(command, delayMs);
2183}
2184
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002185status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002186 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002187 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188{
Eric Laurent0ede8922014-05-09 18:04:42 -07002189 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002191 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002193 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002195 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002196 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002197 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002198 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199}
2200
2201status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2202{
Eric Laurent0ede8922014-05-09 18:04:42 -07002203 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002205 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 data->mVolume = volume;
2207 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002208 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002209 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002210 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211}
2212
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002213void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2214 audio_session_t sessionId,
2215 bool suspended)
2216{
2217 sp<AudioCommand> command = new AudioCommand();
2218 command->mCommand = SET_EFFECT_SUSPENDED;
2219 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2220 data->mEffectId = effectId;
2221 data->mSessionId = sessionId;
2222 data->mSuspended = suspended;
2223 command->mParam = data;
2224 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2225 effectId, sessionId, suspended);
2226 sendCommand(command);
2227}
2228
2229
Eric Laurentd7fe0862018-07-14 16:48:01 -07002230void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002231{
Eric Laurent0ede8922014-05-09 18:04:42 -07002232 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002233 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002234 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002235 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002236 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002237 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002238 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002239}
2240
Eric Laurentd7fe0862018-07-14 16:48:01 -07002241void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002242{
Eric Laurent0ede8922014-05-09 18:04:42 -07002243 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002244 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002245 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002246 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002247 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002248 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002249 sendCommand(command);
2250}
2251
Eric Laurent951f4552014-05-20 10:48:17 -07002252status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2253 const struct audio_patch *patch,
2254 audio_patch_handle_t *handle,
2255 int delayMs)
2256{
2257 status_t status = NO_ERROR;
2258
2259 sp<AudioCommand> command = new AudioCommand();
2260 command->mCommand = CREATE_AUDIO_PATCH;
2261 CreateAudioPatchData *data = new CreateAudioPatchData();
2262 data->mPatch = *patch;
2263 data->mHandle = *handle;
2264 command->mParam = data;
2265 command->mWaitStatus = true;
2266 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2267 status = sendCommand(command, delayMs);
2268 if (status == NO_ERROR) {
2269 *handle = data->mHandle;
2270 }
2271 return status;
2272}
2273
2274status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2275 int delayMs)
2276{
2277 sp<AudioCommand> command = new AudioCommand();
2278 command->mCommand = RELEASE_AUDIO_PATCH;
2279 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2280 data->mHandle = handle;
2281 command->mParam = data;
2282 command->mWaitStatus = true;
2283 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2284 return sendCommand(command, delayMs);
2285}
2286
Eric Laurentb52c1522014-05-20 11:27:36 -07002287void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2288{
2289 sp<AudioCommand> command = new AudioCommand();
2290 command->mCommand = UPDATE_AUDIOPORT_LIST;
2291 ALOGV("AudioCommandThread() adding update audio port list");
2292 sendCommand(command);
2293}
2294
Eric Laurented726cc2021-07-01 14:26:41 +02002295void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2296{
2297 sp<AudioCommand> command = new AudioCommand();
2298 command->mCommand = UPDATE_UID_STATES;
2299 ALOGV("AudioCommandThread() adding update UID states");
2300 sendCommand(command);
2301}
2302
Eric Laurentb52c1522014-05-20 11:27:36 -07002303void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2304{
2305 sp<AudioCommand>command = new AudioCommand();
2306 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2307 ALOGV("AudioCommandThread() adding update audio patch list");
2308 sendCommand(command);
2309}
2310
François Gaffiecfe17322018-11-07 13:41:29 +01002311void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2312 int flags)
2313{
2314 sp<AudioCommand>command = new AudioCommand();
2315 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2316 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2317 data->mGroup = group;
2318 data->mFlags = flags;
2319 command->mParam = data;
2320 ALOGV("AudioCommandThread() adding audio volume group changed");
2321 sendCommand(command);
2322}
2323
Eric Laurente1715a42014-05-20 11:30:42 -07002324status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2325 const struct audio_port_config *config, int delayMs)
2326{
2327 sp<AudioCommand> command = new AudioCommand();
2328 command->mCommand = SET_AUDIOPORT_CONFIG;
2329 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2330 data->mConfig = *config;
2331 command->mParam = data;
2332 command->mWaitStatus = true;
2333 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2334 return sendCommand(command, delayMs);
2335}
2336
Jean-Michel Trivide801052015-04-14 19:10:14 -07002337void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002338 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002339{
2340 sp<AudioCommand> command = new AudioCommand();
2341 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2342 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2343 data->mRegId = regId;
2344 data->mState = state;
2345 command->mParam = data;
2346 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002347 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002348 sendCommand(command);
2349}
2350
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002351void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002352 int event,
2353 const record_client_info_t *clientInfo,
2354 const audio_config_base_t *clientConfig,
2355 std::vector<effect_descriptor_t> clientEffects,
2356 const audio_config_base_t *deviceConfig,
2357 std::vector<effect_descriptor_t> effects,
2358 audio_patch_handle_t patchHandle,
2359 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002360{
2361 sp<AudioCommand>command = new AudioCommand();
2362 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2363 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2364 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002365 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002366 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002367 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002368 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002369 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002370 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002371 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002372 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002373 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2374 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002375 sendCommand(command);
2376}
2377
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002378void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2379{
2380 sp<AudioCommand> command = new AudioCommand();
2381 command->mCommand = AUDIO_MODULES_UPDATE;
2382 sendCommand(command);
2383}
2384
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002385void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2386{
2387 sp<AudioCommand>command = new AudioCommand();
2388 command->mCommand = ROUTING_UPDATED;
2389 ALOGV("AudioCommandThread() adding routing update");
2390 sendCommand(command);
2391}
2392
Eric Laurent81dd0f52021-07-05 11:54:40 +02002393void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2394{
2395 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002396 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002397 ALOGV("AudioCommandThread() adding check spatializer");
2398 sendCommand(command);
2399}
2400
Eric Laurent15903592022-02-24 20:44:36 +01002401void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2402{
2403 sp<AudioCommand>command = new AudioCommand();
2404 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2405 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2406 sendCommand(command);
2407}
2408
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002409void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2410{
2411 sp<AudioCommand>command = new AudioCommand();
2412 command->mCommand = VOL_RANGE_INIT_REQUEST;
2413 ALOGV("AudioCommandThread() adding volume range init request");
2414 sendCommand(command);
2415}
2416
Eric Laurent0ede8922014-05-09 18:04:42 -07002417status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2418{
2419 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002420 audio_utils::lock_guard _l(mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002421 insertCommand_l(command, delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002422 mWaitWorkCV.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002423 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002424 audio_utils::unique_lock ul(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002425 while (command->mWaitStatus) {
2426 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002427 if (command->mCond.wait_for(
Andy Hung02ea2a02024-01-25 17:02:30 -08002428 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002429 command->mStatus = TIMED_OUT;
2430 command->mWaitStatus = false;
2431 }
2432 }
2433 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002434}
2435
Andy Hung79eacdb2023-11-30 19:34:24 -08002436// insertCommand_l() must be called with mMutex held
Eric Laurent0ede8922014-05-09 18:04:42 -07002437void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002439 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002440 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 command->mTime = systemTime() + milliseconds(delayMs);
2442
2443 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002444 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002445 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 }
2447
2448 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002449 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002450 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2452 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002453
2454 // create audio patch or release audio patch commands are equivalent
2455 // with regard to filtering
2456 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2457 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2458 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2459 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2460 continue;
2461 }
2462 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463
2464 switch (command->mCommand) {
2465 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002466 ParametersData *data = (ParametersData *)command->mParam.get();
2467 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002469 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002470 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2472 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2473 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002474 String8 key;
2475 String8 value;
2476 param.getAt(j, key, value);
2477 for (size_t k = 0; k < param2.size(); k++) {
2478 String8 key2;
2479 String8 value2;
2480 param2.getAt(k, key2, value2);
2481 if (key2 == key) {
2482 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002483 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002484 break;
2485 }
2486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 }
2488 // if all keys have been filtered out, remove the command.
2489 // otherwise, update the key value pairs
2490 if (param2.size() == 0) {
2491 removedCommands.add(command2);
2492 } else {
2493 data2->mKeyValuePairs = param2.toString();
2494 }
Eric Laurent21e54562013-09-23 12:08:05 -07002495 command->mTime = command2->mTime;
2496 // force delayMs to non 0 so that code below does not request to wait for
2497 // command status as the command is now delayed
2498 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 } break;
2500
2501 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002502 VolumeData *data = (VolumeData *)command->mParam.get();
2503 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 if (data->mIO != data2->mIO) break;
2505 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002506 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002507 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002509 command->mTime = command2->mTime;
2510 // force delayMs to non 0 so that code below does not request to wait for
2511 // command status as the command is now delayed
2512 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002514
Andy Hung6b137d12024-08-27 22:35:17 +00002515 case SET_PORTS_VOLUME: {
2516 VolumePortsData *data = (VolumePortsData *)command->mParam.get();
2517 VolumePortsData *data2 = (VolumePortsData *)command2->mParam.get();
2518 if (data->mIO != data2->mIO) break;
2519 // Can remove command only if port ids list is the same, otherwise, remove from
2520 // command 2 all port whose volume will be replaced with command 1 volume.
2521 std::vector<audio_port_handle_t> portsOnlyInCommand2{};
2522 std::copy_if(data2->mPorts.begin(), data2->mPorts.end(),
2523 std::back_inserter(portsOnlyInCommand2), [&](const auto &portId) {
2524 return std::find(data->mPorts.begin(), data->mPorts.end(), portId) ==
2525 data->mPorts.end();
2526 });
2527 if (!portsOnlyInCommand2.empty()) {
2528 data2->mPorts = portsOnlyInCommand2;
2529 break;
2530 }
2531 ALOGV("Filtering out volume command on output %d for ports %s",
2532 data->mIO, data->dumpPorts().c_str());
2533 removedCommands.add(command2);
2534 command->mTime = command2->mTime;
2535 // force delayMs to non 0 so that code below does not request to wait for
2536 // command status as the command is now delayed
2537 delayMs = 1;
2538 } break;
2539
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002540 case SET_VOICE_VOLUME: {
2541 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2542 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2543 ALOGV("Filtering out voice volume command value %f replaced by %f",
2544 data2->mVolume, data->mVolume);
2545 removedCommands.add(command2);
2546 command->mTime = command2->mTime;
2547 // force delayMs to non 0 so that code below does not request to wait for
2548 // command status as the command is now delayed
2549 delayMs = 1;
2550 } break;
2551
Eric Laurente45b48a2014-09-04 16:40:57 -07002552 case CREATE_AUDIO_PATCH:
2553 case RELEASE_AUDIO_PATCH: {
2554 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002555 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002556 if (command->mCommand == CREATE_AUDIO_PATCH) {
2557 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002558 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002559 } else {
2560 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002561 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002562 }
2563 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002564 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002565 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2566 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002567 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002568 } else {
2569 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002570 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002571 }
2572 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002573 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2574 same output. */
2575 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2576 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2577 bool isOutputDiff = false;
2578 if (patch.num_sources == patch2.num_sources) {
2579 for (unsigned count = 0; count < patch.num_sources; count++) {
2580 if (patch.sources[count].id != patch2.sources[count].id) {
2581 isOutputDiff = true;
2582 break;
2583 }
2584 }
2585 if (isOutputDiff)
2586 break;
2587 }
2588 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002589 ALOGV("Filtering out %s audio patch command for handle %d",
2590 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2591 removedCommands.add(command2);
2592 command->mTime = command2->mTime;
2593 // force delayMs to non 0 so that code below does not request to wait for
2594 // command status as the command is now delayed
2595 delayMs = 1;
2596 } break;
2597
Jean-Michel Trivide801052015-04-14 19:10:14 -07002598 case DYN_POLICY_MIX_STATE_UPDATE: {
2599
2600 } break;
2601
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002602 case RECORDING_CONFIGURATION_UPDATE: {
2603
2604 } break;
2605
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002606 case ROUTING_UPDATED: {
2607
2608 } break;
2609
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002610 case VOL_RANGE_INIT_REQUEST: {
2611 // command may come from different requests, do not filter
2612 } break;
2613
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614 default:
2615 break;
2616 }
2617 }
2618
2619 // remove filtered commands
2620 for (size_t j = 0; j < removedCommands.size(); j++) {
2621 // removed commands always have time stamps greater than current command
2622 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002623 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002624 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 mAudioCommands.removeAt(k);
2626 break;
2627 }
2628 }
2629 }
2630 removedCommands.clear();
2631
Eric Laurentaa79bef2015-01-15 14:33:51 -08002632 // Disable wait for status if delay is not 0.
2633 // Except for create audio patch command because the returned patch handle
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02002634 // is needed by audio policy manager. Audio patch created after timeout
2635 // (see TIMED_OUT) will be released from threadLoop().
Eric Laurentaa79bef2015-01-15 14:33:51 -08002636 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002637 command->mWaitStatus = false;
2638 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002639
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002641 ALOGV("inserting command: %d at index %zd, num commands %zu",
2642 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002643 mAudioCommands.insertAt(command, i + 1);
2644}
2645
2646void AudioPolicyService::AudioCommandThread::exit()
2647{
Steve Block3856b092011-10-20 11:56:00 +01002648 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002650 audio_utils::lock_guard _l(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 requestExit();
Andy Hung79eacdb2023-11-30 19:34:24 -08002652 mWaitWorkCV.notify_one();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 }
Zach Janga754b4f2015-10-27 01:29:34 +00002654 // Note that we can call it from the thread loop if all other references have been released
2655 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 requestExitAndWait();
2657}
2658
2659void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2660{
2661 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2662 mCommand,
2663 (int)ns2s(mTime),
2664 (int)ns2ms(mTime)%1000,
2665 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002666 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667}
2668
Dima Zavinfce7a472011-04-19 22:30:36 -07002669/******* helpers for the service_ops callbacks defined below *********/
2670void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2671 const char *keyValuePairs,
2672 int delayMs)
2673{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002674 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002675 delayMs);
2676}
2677
2678int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2679 float volume,
2680 audio_io_handle_t output,
2681 int delayMs)
2682{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002683 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002684 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002685}
2686
Andy Hung6b137d12024-08-27 22:35:17 +00002687int AudioPolicyService::setPortsVolume(const std::vector<audio_port_handle_t> &ports, float volume,
2688 audio_io_handle_t output, int delayMs)
2689{
2690 return (int)mAudioCommandThread->volumePortsCommand(ports, volume, output, delayMs);
2691}
2692
Dima Zavinfce7a472011-04-19 22:30:36 -07002693int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2694{
2695 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2696}
2697
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002698void AudioPolicyService::setEffectSuspended(int effectId,
2699 audio_session_t sessionId,
2700 bool suspended)
2701{
2702 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2703}
2704
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002705Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002706{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002707 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002708 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002709}
2710
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002711
Dima Zavinfce7a472011-04-19 22:30:36 -07002712extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002713audio_module_handle_t aps_load_hw_module(void *service __unused,
2714 const char *name);
2715audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002716 audio_devices_t *pDevices,
2717 uint32_t *pSamplingRate,
2718 audio_format_t *pFormat,
2719 audio_channel_mask_t *pChannelMask,
2720 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002721 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002722
Eric Laurent2d388ec2014-03-07 13:25:54 -08002723audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002724 audio_module_handle_t module,
2725 audio_devices_t *pDevices,
2726 uint32_t *pSamplingRate,
2727 audio_format_t *pFormat,
2728 audio_channel_mask_t *pChannelMask,
2729 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002730 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002731 const audio_offload_info_t *offloadInfo);
2732audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002733 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002734 audio_io_handle_t output2);
2735int aps_close_output(void *service __unused, audio_io_handle_t output);
2736int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2737int aps_restore_output(void *service __unused, audio_io_handle_t output);
2738audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002739 audio_devices_t *pDevices,
2740 uint32_t *pSamplingRate,
2741 audio_format_t *pFormat,
2742 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002743 audio_in_acoustics_t acoustics __unused);
2744audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002745 audio_module_handle_t module,
2746 audio_devices_t *pDevices,
2747 uint32_t *pSamplingRate,
2748 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002749 audio_channel_mask_t *pChannelMask);
2750int aps_close_input(void *service __unused, audio_io_handle_t input);
2751int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002752int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002753 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002754 audio_io_handle_t dst_output);
2755char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2756 const char *keys);
2757void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2758 const char *kv_pairs, int delay_ms);
2759int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002760 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002761 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002762int aps_set_voice_volume(void *service, float volume, int delay_ms);
2763};
Dima Zavinfce7a472011-04-19 22:30:36 -07002764
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002765} // namespace android