blob: 717640faeb4c62048f7b0733d2154a5ba2be4e2c [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
Andy Hungc747c532022-03-07 21:41:14 -080064// Creates an association between Binder code to name for IAudioPolicyService.
65#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
66BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
67BINDER_METHOD_ENTRY(setDeviceConnectionState) \
68BINDER_METHOD_ENTRY(getDeviceConnectionState) \
69BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
70BINDER_METHOD_ENTRY(setPhoneState) \
71BINDER_METHOD_ENTRY(setForceUse) \
72BINDER_METHOD_ENTRY(getForceUse) \
73BINDER_METHOD_ENTRY(getOutput) \
74BINDER_METHOD_ENTRY(getOutputForAttr) \
75BINDER_METHOD_ENTRY(startOutput) \
76BINDER_METHOD_ENTRY(stopOutput) \
77BINDER_METHOD_ENTRY(releaseOutput) \
78BINDER_METHOD_ENTRY(getInputForAttr) \
79BINDER_METHOD_ENTRY(startInput) \
80BINDER_METHOD_ENTRY(stopInput) \
81BINDER_METHOD_ENTRY(releaseInput) \
82BINDER_METHOD_ENTRY(initStreamVolume) \
83BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
84BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
85BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
86BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
87BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
88BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getStrategyForStream) \
90BINDER_METHOD_ENTRY(getDevicesForAttributes) \
91BINDER_METHOD_ENTRY(getOutputForEffect) \
92BINDER_METHOD_ENTRY(registerEffect) \
93BINDER_METHOD_ENTRY(unregisterEffect) \
94BINDER_METHOD_ENTRY(setEffectEnabled) \
95BINDER_METHOD_ENTRY(moveEffectsToIo) \
96BINDER_METHOD_ENTRY(isStreamActive) \
97BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
98BINDER_METHOD_ENTRY(isSourceActive) \
99BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
100BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
101BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
102BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
103BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
104BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
105BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
106BINDER_METHOD_ENTRY(getOffloadSupport) \
107BINDER_METHOD_ENTRY(isDirectOutputSupported) \
108BINDER_METHOD_ENTRY(listAudioPorts) \
109BINDER_METHOD_ENTRY(getAudioPort) \
110BINDER_METHOD_ENTRY(createAudioPatch) \
111BINDER_METHOD_ENTRY(releaseAudioPatch) \
112BINDER_METHOD_ENTRY(listAudioPatches) \
113BINDER_METHOD_ENTRY(setAudioPortConfig) \
114BINDER_METHOD_ENTRY(registerClient) \
115BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
116BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
117BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
118BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
119BINDER_METHOD_ENTRY(getPhoneState) \
120BINDER_METHOD_ENTRY(registerPolicyMixes) \
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +0200121BINDER_METHOD_ENTRY(updatePolicyMixes) \
Andy Hungc747c532022-03-07 21:41:14 -0800122BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
123BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
124BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
125BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
126BINDER_METHOD_ENTRY(startAudioSource) \
127BINDER_METHOD_ENTRY(stopAudioSource) \
128BINDER_METHOD_ENTRY(setMasterMono) \
129BINDER_METHOD_ENTRY(getMasterMono) \
130BINDER_METHOD_ENTRY(getStreamVolumeDB) \
131BINDER_METHOD_ENTRY(getSurroundFormats) \
132BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
133BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
134BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
135BINDER_METHOD_ENTRY(setAssistantServicesUids) \
136BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
137BINDER_METHOD_ENTRY(setA11yServicesUids) \
138BINDER_METHOD_ENTRY(setCurrentImeUid) \
139BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
140BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800141BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800142BINDER_METHOD_ENTRY(listAudioProductStrategies) \
143BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
144BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
145BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
146BINDER_METHOD_ENTRY(setRttEnabled) \
147BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
148BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
149BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000150BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800151BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
152BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
153BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
154BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
155BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
156BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
157BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
158BINDER_METHOD_ENTRY(getSpatializer) \
159BINDER_METHOD_ENTRY(canBeSpatialized) \
160BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000161BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
162BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
163BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
164BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
165BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Andy Hungc747c532022-03-07 21:41:14 -0800166
167// singleton for Binder Method Statistics for IAudioPolicyService
168static auto& getIAudioPolicyServiceStatistics() {
169 using Code = int;
170
171#pragma push_macro("BINDER_METHOD_ENTRY")
172#undef BINDER_METHOD_ENTRY
173#define BINDER_METHOD_ENTRY(ENTRY) \
174 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
175
176 static mediautils::MethodStatistics<Code> methodStatistics{
177 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
178 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
179 };
180#pragma pop_macro("BINDER_METHOD_ENTRY")
181
182 return methodStatistics;
183}
184
Mathias Agopian65ab4712010-07-14 17:59:35 -0700185// ----------------------------------------------------------------------------
186
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530187static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
188{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700189 AudioPolicyManager *apm = nullptr;
190 media::AudioPolicyConfig apmConfig;
191 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
192 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
193 LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
194 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
195 "Only default engine is currently supported with the AIDL HAL");
196 apm = new AudioPolicyManager(config,
197 loadApmEngineLibraryAndCreateEngine(
198 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
199 clientInterface);
200 } else {
201 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
202 apm = new AudioPolicyManager(config,
203 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
204 clientInterface);
205 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530206 status_t status = apm->initialize();
207 if (status != NO_ERROR) {
208 delete apm;
209 apm = nullptr;
210 }
211 return apm;
212}
213
214static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
215{
216 delete interface;
217}
218// ----------------------------------------------------------------------------
219
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700221 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700222 mAudioPolicyManager(NULL),
223 mAudioPolicyClient(NULL),
224 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530225 mCaptureStateNotifier(false),
226 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100227 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
228 mUsecaseValidator(media::createUsecaseValidator()) {
Andy Hung225aef62022-12-06 16:33:20 -0800229 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530230}
231
232void AudioPolicyService::loadAudioPolicyManager()
233{
234 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
235 if (mLibraryHandle != nullptr) {
236 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
237 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
238 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
239 const char *lastError = dlerror();
240 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
241 __func__, lastError != nullptr ? lastError : "no error");
242
243 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
244 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
245 lastError = dlerror();
246 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
247 __func__, lastError != nullptr ? lastError : "no error");
248 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
249 unloadAudioPolicyManager();
250 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
251 }
252 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700253}
254
255void AudioPolicyService::onFirstRef()
256{
Andy Hungd47aca22022-03-15 11:50:51 -0700257 // Log an AudioPolicy "constructor" mediametrics event on first ref.
258 // This records the time it takes to load the audio modules and devices.
259 mediametrics::Defer defer([beginNs = systemTime()] {
260 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
261 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
262 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
263 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700264 {
Andy Hung6a0fbd92023-11-30 19:34:24 -0800265 audio_utils::lock_guard _l(mMutex);
Eric Laurent93575202011-01-18 18:39:02 -0800266
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700267 // start audio commands thread
268 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
269 // start output activity command thread
270 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700271
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700272 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530273
274 loadAudioPolicyManager();
275 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700276 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200277
bryant_liuba2b4392014-06-11 16:49:30 +0800278 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000279 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
Andy Hungbec2f3a2023-12-19 15:34:46 -0800280 auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
281 auto uidPolicy = sp<UidPolicy>::make(this);
282 auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700283 {
Andy Hung6a0fbd92023-11-30 19:34:24 -0800284 audio_utils::lock_guard _l(mMutex);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700285 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000286 mUidPolicy = uidPolicy;
287 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700288 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000289 uidPolicy->registerSelf();
290 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200291
Eric Laurent81dd0f52021-07-05 11:54:40 +0200292 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200293 if (mAudioPolicyManager != nullptr) {
Andy Hung6a0fbd92023-11-30 19:34:24 -0800294 audio_utils::lock_guard _l(mMutex);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200295 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
296 AudioDeviceTypeAddrVector devices;
297 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
298 if (hasSpatializer) {
Andy Hung1040da52023-12-06 20:59:06 -0800299 // Unlock as Spatializer::create() will use the callback and acquire the
300 // AudioPolicyService_Mutex.
Andy Hung6a0fbd92023-11-30 19:34:24 -0800301 mMutex.unlock();
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000302 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Andy Hung6a0fbd92023-11-30 19:34:24 -0800303 mMutex.lock();
Eric Laurent52b0bd52021-09-27 15:25:40 +0200304 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700305 if (mSpatializer == nullptr) {
306 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
307 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
308 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
309 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200310 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200311 AudioSystem::audioPolicyReady();
Andy Hunge63196d2024-01-09 19:05:23 -0800312}
313
314void AudioPolicyService::onAudioSystemReady() {
315 sp<AudioPolicyEffects> audioPolicyEffects;
316 {
317 audio_utils::lock_guard _l(mMutex);
318
319 audioPolicyEffects = mAudioPolicyEffects;
320 }
321 audioPolicyEffects->initDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700322}
323
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530324void AudioPolicyService::unloadAudioPolicyManager()
325{
326 ALOGV("%s ", __func__);
327 if (mLibraryHandle != nullptr) {
328 dlclose(mLibraryHandle);
329 }
330 mLibraryHandle = nullptr;
331 mCreateAudioPolicyManager = nullptr;
332 mDestroyAudioPolicyManager = nullptr;
333}
334
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335AudioPolicyService::~AudioPolicyService()
336{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700338 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700339
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530340 mDestroyAudioPolicyManager(mAudioPolicyManager);
341 unloadAudioPolicyManager();
342
Eric Laurentdce54a12014-03-10 12:19:46 -0700343 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700344
345 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800346 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800347
348 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800349 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000350
351 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800352 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700353}
354
355// A notification client is always registered by AudioSystem when the client process
356// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800357Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700358{
Eric Laurent12590252015-08-21 18:40:20 -0700359 if (client == 0) {
360 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800361 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700362 }
Andy Hung6a0fbd92023-11-30 19:34:24 -0800363 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700364
365 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800366 pid_t pid = IPCThreadState::self()->getCallingPid();
367 int64_t token = ((int64_t)uid<<32) | pid;
368
369 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700370 sp<NotificationClient> notificationClient = new NotificationClient(this,
371 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800372 uid,
373 pid);
374 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700375
luochaojiang908c7d72018-06-21 14:58:04 +0800376 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700377
Marco Nelissenf8880202014-11-14 07:58:25 -0800378 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700379 binder->linkToDeath(notificationClient);
380 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800381 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700382}
383
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800384Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700385{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800386 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurente8726fe2015-06-26 09:39:24 -0700387
388 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800389 pid_t pid = IPCThreadState::self()->getCallingPid();
390 int64_t token = ((int64_t)uid<<32) | pid;
391
392 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800393 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700394 }
luochaojiang908c7d72018-06-21 14:58:04 +0800395 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800396 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700397}
398
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800399Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100400{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800401 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100402
403 uid_t uid = IPCThreadState::self()->getCallingUid();
404 pid_t pid = IPCThreadState::self()->getCallingPid();
405 int64_t token = ((int64_t)uid<<32) | pid;
406
407 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800408 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100409 }
410 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800411 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100412}
413
Eric Laurentb52c1522014-05-20 11:27:36 -0700414// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800415void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700416{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000417 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800418 {
Andy Hung6a0fbd92023-11-30 19:34:24 -0800419 audio_utils::lock_guard _l(mNotificationClientsMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800420 int64_t token = ((int64_t)uid<<32) | pid;
421 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800422 for (size_t i = 0; i < mNotificationClients.size(); i++) {
423 if (mNotificationClients.valueAt(i)->uid() == uid) {
424 hasSameUid = true;
425 break;
426 }
427 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000428 }
429 {
Andy Hung6a0fbd92023-11-30 19:34:24 -0800430 audio_utils::lock_guard _l(mMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800431 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700432 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700433 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700434 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800435 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700436}
437
438void AudioPolicyService::onAudioPortListUpdate()
439{
440 mOutputCommandThread->updateAudioPortListCommand();
441}
442
443void AudioPolicyService::doOnAudioPortListUpdate()
444{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800445 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700446 for (size_t i = 0; i < mNotificationClients.size(); i++) {
447 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
448 }
449}
450
451void AudioPolicyService::onAudioPatchListUpdate()
452{
453 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454}
455
Eric Laurentb52c1522014-05-20 11:27:36 -0700456void AudioPolicyService::doOnAudioPatchListUpdate()
457{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800458 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700459 for (size_t i = 0; i < mNotificationClients.size(); i++) {
460 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
461 }
462}
463
François Gaffiecfe17322018-11-07 13:41:29 +0100464void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
465{
466 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
467}
468
469void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
470{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800471 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100472 for (size_t i = 0; i < mNotificationClients.size(); i++) {
473 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
474 }
475}
476
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700477void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700478{
479 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000480 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700481 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
482}
483
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700484void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700485{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800486 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700487 for (size_t i = 0; i < mNotificationClients.size(); i++) {
488 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
489 }
490}
491
Eric Laurenta9f86652018-11-28 17:23:11 -0800492void AudioPolicyService::onRecordingConfigurationUpdate(
493 int event,
494 const record_client_info_t *clientInfo,
495 const audio_config_base_t *clientConfig,
496 std::vector<effect_descriptor_t> clientEffects,
497 const audio_config_base_t *deviceConfig,
498 std::vector<effect_descriptor_t> effects,
499 audio_patch_handle_t patchHandle,
500 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800501{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800502 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800503 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800504}
505
Eric Laurenta9f86652018-11-28 17:23:11 -0800506void AudioPolicyService::doOnRecordingConfigurationUpdate(
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{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800516 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800517 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800518 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800519 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800520 }
521}
522
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700523void AudioPolicyService::onRoutingUpdated()
524{
525 mOutputCommandThread->routingChangedCommand();
526}
527
528void AudioPolicyService::doOnRoutingUpdated()
529{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800530 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700531 for (size_t i = 0; i < mNotificationClients.size(); i++) {
532 mNotificationClients.valueAt(i)->onRoutingUpdated();
533 }
534}
535
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000536void AudioPolicyService::onVolumeRangeInitRequest()
537{
538 mOutputCommandThread->volRangeInitReqCommand();
539}
540
541void AudioPolicyService::doOnVolumeRangeInitRequest()
542{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800543 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000544 for (size_t i = 0; i < mNotificationClients.size(); i++) {
545 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
546 }
547}
548
Eric Laurent81dd0f52021-07-05 11:54:40 +0200549void AudioPolicyService::onCheckSpatializer()
550{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800551 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200552 onCheckSpatializer_l();
553}
554
555void AudioPolicyService::onCheckSpatializer_l()
556{
557 if (mSpatializer != nullptr) {
558 mOutputCommandThread->checkSpatializerCommand();
559 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200560}
561
562void AudioPolicyService::doOnCheckSpatializer()
563{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200564 ALOGV("%s mSpatializer %p level %d",
565 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200566
Eric Laurent39095982021-08-24 18:29:27 +0200567 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200568 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000569 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200570 audio_io_handle_t currentOutput = mSpatializer->getOutput();
571 audio_io_handle_t newOutput;
572 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
573 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200574
Andy Hung6a0fbd92023-11-30 19:34:24 -0800575 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200576 status_t status =
577 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100578 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
579 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200580 if (status == NO_ERROR && currentOutput == newOutput) {
581 return;
582 }
Eric Laurent15903592022-02-24 20:44:36 +0100583 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Andy Hung6a0fbd92023-11-30 19:34:24 -0800584 mMutex.unlock();
Eric Laurent39095982021-08-24 18:29:27 +0200585 // It is OK to call detachOutput() is none is already attached.
586 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200587 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
588 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200589 }
Andy Hung6a0fbd92023-11-30 19:34:24 -0800590 mMutex.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200591 if (status != NO_ERROR) {
592 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
593 }
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000594 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
595 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200596 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200597
Eric Laurent39095982021-08-24 18:29:27 +0200598 if (output != AUDIO_IO_HANDLE_NONE) {
Andy Hung6a0fbd92023-11-30 19:34:24 -0800599 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200600 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200601 }
602 }
603 }
604}
605
Eric Laurent11094172022-04-05 18:27:42 +0200606size_t AudioPolicyService::countActiveClientsOnOutput_l(
607 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100608 size_t count = 0;
609 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
610 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200611 if (client->io == output && client->active
612 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100613 count++;
614 }
615 }
616 return count;
617}
618
619void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
620 if (mSpatializer == nullptr) {
621 return;
622 }
623 mOutputCommandThread->updateActiveSpatializerTracksCommand();
624}
625
626void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
627{
Eric Laurent21270b62022-07-04 15:11:29 +0200628 if (mSpatializer == nullptr) {
629 return;
630 }
631 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200632 size_t activeClients;
633 {
Andy Hung6a0fbd92023-11-30 19:34:24 -0800634 audio_utils::lock_guard _l(mMutex);
Eric Laurent21270b62022-07-04 15:11:29 +0200635 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100636 }
Eric Laurent21270b62022-07-04 15:11:29 +0200637 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100638}
639
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800640status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
641 audio_patch_handle_t *handle,
642 int delayMs)
643{
644 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
645}
646
647status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
648 int delayMs)
649{
650 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
651}
652
Eric Laurente1715a42014-05-20 11:30:42 -0700653status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
654 int delayMs)
655{
656 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
657}
658
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800659AudioPolicyService::NotificationClient::NotificationClient(
660 const sp<AudioPolicyService>& service,
661 const sp<media::IAudioPolicyServiceClient>& client,
662 uid_t uid,
663 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800664 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100665 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700666{
667}
668
669AudioPolicyService::NotificationClient::~NotificationClient()
670{
671}
672
673void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
674{
675 sp<NotificationClient> keep(this);
676 sp<AudioPolicyService> service = mService.promote();
677 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800678 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700679 }
680}
681
682void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
683{
Eric Laurente8726fe2015-06-26 09:39:24 -0700684 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700685 mAudioPolicyServiceClient->onAudioPortListUpdate();
686 }
687}
688
689void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
690{
Eric Laurente8726fe2015-06-26 09:39:24 -0700691 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700692 mAudioPolicyServiceClient->onAudioPatchListUpdate();
693 }
694}
Eric Laurent57dae992011-07-24 13:36:09 -0700695
Pattydd807582021-11-04 21:01:03 +0800696void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100697 int flags)
698{
699 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
700 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
701 }
702}
703
704
Jean-Michel Trivide801052015-04-14 19:10:14 -0700705void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700706 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700707{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700708 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800709 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
710 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800711 }
712}
713
714void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800715 int event,
716 const record_client_info_t *clientInfo,
717 const audio_config_base_t *clientConfig,
718 std::vector<effect_descriptor_t> clientEffects,
719 const audio_config_base_t *deviceConfig,
720 std::vector<effect_descriptor_t> effects,
721 audio_patch_handle_t patchHandle,
722 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800723{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700724 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800725 status_t status = [&]() -> status_t {
726 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
727 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
728 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700729 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700730 legacy2aidl_audio_config_base_t_AudioConfigBase(
731 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800732 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
733 convertContainer<std::vector<media::EffectDescriptor>>(
734 clientEffects,
735 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700736 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700737 legacy2aidl_audio_config_base_t_AudioConfigBase(
738 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800739 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
740 convertContainer<std::vector<media::EffectDescriptor>>(
741 effects,
742 legacy2aidl_effect_descriptor_t_EffectDescriptor));
743 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
744 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700745 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
746 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800747 return aidl_utils::statusTFromBinderStatus(
748 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
749 clientInfoAidl,
750 clientConfigAidl,
751 clientEffectsAidl,
752 deviceConfigAidl,
753 effectsAidl,
754 patchHandleAidl,
755 sourceAidl));
756 }();
757 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700758 }
759}
760
Eric Laurente8726fe2015-06-26 09:39:24 -0700761void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
762{
763 mAudioPortCallbacksEnabled = enabled;
764}
765
François Gaffiecfe17322018-11-07 13:41:29 +0100766void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
767{
768 mAudioVolumeGroupCallbacksEnabled = enabled;
769}
Eric Laurente8726fe2015-06-26 09:39:24 -0700770
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700771void AudioPolicyService::NotificationClient::onRoutingUpdated()
772{
773 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
774 mAudioPolicyServiceClient->onRoutingUpdated();
775 }
776}
777
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000778void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
779{
780 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
781 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
782 }
783}
784
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700786 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700787 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788}
789
Andy Hung6a0fbd92023-11-30 19:34:24 -0800790static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
791 RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000792{
793 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794}
795
796status_t AudioPolicyService::dumpInternals(int fd)
797{
798 const size_t SIZE = 256;
799 char buffer[SIZE];
800 String8 result;
801
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000802 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800803 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000804 std::stringstream msg;
805 size_t i = 0;
806 for (auto usage : mSupportedSystemUsages) {
807 if (i++ != 0) msg << ", ";
808 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
809 msg << strUsage;
810 } else {
811 msg << usage << " (unknown)";
812 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800813 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000814 if (i == 0) {
815 msg << "None";
816 }
817 msg << std::endl;
818 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800819
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000820 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800821
822 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 return NO_ERROR;
824}
825
Eric Laurente8c8b432018-10-17 10:08:02 -0700826void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800827{
Andy Hung6a0fbd92023-11-30 19:34:24 -0800828 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -0700829 updateUidStates_l();
830}
831
832void AudioPolicyService::updateUidStates_l()
833{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800834// Go over all active clients and allow capture (does not force silence) in the
835// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800836// The client is in the active assistant list
837// AND is TOP
838// AND an accessibility service is TOP
839// AND source is either VOICE_RECOGNITION OR HOTWORD
840// OR there is no active privacy sensitive capture or call
841// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
842// AND source is VOICE_RECOGNITION OR HOTWORD
843// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800844// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700845// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800846// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800847// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800848// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
849// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800850// OR The client is an accessibility service
851// AND Is on TOP
852// AND the source is VOICE_RECOGNITION or HOTWORD
853// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700854// AND there is no active privacy sensitive capture or call
855// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800856// AND is on TOP
857// AND the source is VOICE_RECOGNITION or HOTWORD
858// OR the client source is virtual (remote submix, call audio TX or RX...)
859// OR the client source is HOTWORD
860// AND is on TOP
861// OR all active clients are using HOTWORD source
862// AND no call is active
863// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
864// OR the client is the current InputMethodService
865// AND a RTT call is active AND the source is VOICE_RECOGNITION
866// OR Any client
867// AND The assistant is not on TOP
868// AND is on TOP or latest started
869// AND there is no active privacy sensitive capture or call
870// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800871
Eric Laurent4e947da2019-10-17 15:24:06 -0700872
Eric Laurent4eb58f12018-12-07 16:41:02 -0800873 sp<AudioRecordClient> topActive;
874 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800875 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700876 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800877 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700878
Eric Laurenta46bedb2018-12-07 18:01:26 -0800879 nsecs_t topStartNs = 0;
880 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800881 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800882 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800883 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800884 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
885 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800886 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800887 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700888 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800889 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
890 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700891 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700892 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700893 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800894
Michael Groovercfd28302018-12-11 19:16:46 -0800895 // if Sensor Privacy is enabled then all recordings should be silenced.
896 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
897 silenceAllRecordings_l();
898 return;
899 }
900
Eric Laurente8c8b432018-10-17 10:08:02 -0700901 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
902 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000903 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
904 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800905 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700906 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800907 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700908
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700909 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700910 // clients which app is in IDLE state are not eligible for top active or
911 // latest active
912 if (appState == APP_STATE_IDLE) {
913 continue;
914 }
915
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700916 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700917 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800918 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700919 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700920 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800921 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800922 bool isPrivacySensitive =
923 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700924
Eric Laurentc21d5692020-02-25 10:24:36 -0800925 if (appState == APP_STATE_TOP) {
926 if (isPrivacySensitive) {
927 if (current->startTimeNs > topSensitiveStartNs) {
928 topSensitiveActive = current;
929 topSensitiveStartNs = current->startTimeNs;
930 }
931 } else {
932 if (current->startTimeNs > topStartNs) {
933 topActive = current;
934 topStartNs = current->startTimeNs;
935 }
936 }
937 if (isAssistant) {
938 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800939 if (isActiveAssistant) {
940 useActiveAssistantList = true;
941 } else if (!useActiveAssistantList) {
942 if (current->startTimeNs > latestAssistantStartNs) {
943 latestActiveAssistant = current;
944 latestAssistantStartNs = current->startTimeNs;
945 }
946 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800947 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800948 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800949 // Clients capturing for HOTWORD are not considered
950 // for latest active to avoid masking regular clients started before
951 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
952 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
953 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700954 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
955 // is marked latest sensitive active even if another app qualifies.
956 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700957 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700958 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700959 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000960 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700961 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700962 latestSensitiveActiveOrComm = current;
963 latestSensitiveStartNs = current->startTimeNs;
964 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800965 }
966 isSensitiveActive = true;
967 } else {
968 if (current->startTimeNs > latestStartNs) {
969 latestActive = current;
970 latestStartNs = current->startTimeNs;
971 }
972 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800973 }
974 }
François Gaffiedb1a4412023-10-10 17:32:33 +0000975 if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
976 !isVirtualSource(current->attributes.source)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700977 onlyHotwordActive = false;
978 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100979 if (currentUid == mPhoneStateOwnerUid &&
980 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700981 isPhoneStateOwnerActive = true;
982 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800983 }
984
Eric Laurent1ff16a72019-03-14 18:35:04 -0700985 // if no active client with UI on Top, consider latest active as top
986 if (topActive == nullptr) {
987 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800988 topStartNs = latestStartNs;
989 }
990 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700991 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800992 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700993 } else if (latestSensitiveActiveOrComm != nullptr) {
994 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
995 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700996 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000997 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700998 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700999 topSensitiveActive = latestSensitiveActiveOrComm;
1000 topSensitiveStartNs = latestSensitiveStartNs;
1001 }
Eric Laurentc21d5692020-02-25 10:24:36 -08001002 }
1003
1004 // If both privacy sensitive and regular capture are active:
1005 // if the regular capture is privileged
1006 // allow concurrency
1007 // else
1008 // favor the privacy sensitive case
1009 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001010 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001011 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001012 }
1013
1014 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1015 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001016 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001017 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001018 if (!current->active) {
1019 continue;
1020 }
1021
Eric Laurent4eb58f12018-12-07 16:41:02 -08001022 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001023 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001024 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001025 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001026 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001027 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1028 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001029
Andy Hung6a0fbd92023-11-30 19:34:24 -08001030 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mMutex) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001031 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001032 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001033 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001034 bool canCaptureCommunication = recordClient->canCaptureOutput
1035 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001036 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001037 return !(isInCall && !canCaptureCall)
1038 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001039 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001040
1041 // By default allow capture if:
1042 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001043 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001044 // AND there is no active privacy sensitive capture or call
1045 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001046 bool allowSensitiveCapture =
1047 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001048 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001049 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001050 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001051 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001052
Eric Laurented726cc2021-07-01 14:26:41 +02001053 if (!current->hasOp()) {
1054 // Never allow capture if app op is denied
1055 allowCapture = false;
1056 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001057 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1058 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001059 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001060 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001061 // Active assistant list is not being used
1062 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001063 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001064 // OR there is no active privacy sensitive capture or call
1065 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1066 // AND is latest TOP assistant AND
1067 // uses VOICE_RECOGNITION OR uses HOTWORD
1068 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001069 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001070 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001071 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001072 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001073 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001074 && canCaptureIfInCallOrCommunication(current)) {
1075 if (isTopOrLatestAssistant
1076 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1077 || source == AUDIO_SOURCE_HOTWORD)) {
1078 allowCapture = true;
1079 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1080 allowCapture = true;
1081 }
1082 }
1083 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1084 // For assistant on active list and on top allow capture if:
1085 // An accessibility service is on TOP
1086 // AND the source is VOICE_RECOGNITION or HOTWORD
1087 // OR there is no active privacy sensitive capture or call
1088 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1089 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1090 if (isA11yOnTop) {
1091 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1092 allowCapture = true;
1093 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001094 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001095 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001096 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1097 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001098 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001099 }
1100 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001101 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001102 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001103 // The assistant is not on TOP
1104 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001105 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001106 // OR
1107 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1108 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001109 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001110 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001111 allowCapture = true;
1112 }
Eric Laurent589171c2019-07-25 18:04:29 -07001113 if (isA11yOnTop) {
1114 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1115 allowCapture = true;
1116 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001117 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001118 } else if (source == AUDIO_SOURCE_HOTWORD) {
1119 // For HOTWORD source allow capture when not on TOP if:
1120 // All active clients are using HOTWORD source
1121 // AND no call is active
1122 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001123 if (onlyHotwordActive
1124 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001125 allowCapture = true;
1126 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001127 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001128 // For current InputMethodService allow capture if:
1129 // A RTT call is active AND the source is VOICE_RECOGNITION
1130 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1131 allowCapture = true;
1132 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001133 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001134 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001135 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001136 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001137 }
1138}
1139
Michael Groovercfd28302018-12-11 19:16:46 -08001140void AudioPolicyService::silenceAllRecordings_l() {
1141 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1142 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001143 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001144 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001145 }
Michael Groovercfd28302018-12-11 19:16:46 -08001146 }
1147}
1148
Eric Laurente8c8b432018-10-17 10:08:02 -07001149/* static */
1150app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001151
1152 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001153 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001154 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1155 // include persistent services
1156 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001157 }
1158 return APP_STATE_FOREGROUND;
1159}
1160
Eric Laurent4eb58f12018-12-07 16:41:02 -08001161/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001162bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001163{
1164 switch (source) {
1165 case AUDIO_SOURCE_VOICE_UPLINK:
1166 case AUDIO_SOURCE_VOICE_DOWNLINK:
1167 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001168 case AUDIO_SOURCE_REMOTE_SUBMIX:
1169 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001170 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001171 return true;
1172 default:
1173 break;
1174 }
1175 return false;
1176}
1177
Eric Laurent8c7ef892021-06-10 13:32:16 +02001178void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001179{
1180 AutoCallerClear acc;
1181
1182 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001183 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001184 }
1185 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1186 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001187 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001188 if (client->silenced != silenced) {
1189 if (client->active) {
1190 if (silenced) {
1191 finishRecording(client->attributionSource, client->attributes.source);
1192 } else {
1193 std::stringstream msg;
1194 msg << "Audio recording un-silenced on session " << client->session;
1195 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1196 client->attributes.source)) {
1197 silenced = true;
1198 }
1199 }
1200 }
1201 af->setRecordSilenced(client->portId, silenced);
1202 client->silenced = silenced;
1203 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001204 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001205}
1206
Glenn Kasten0f11b512014-01-31 16:18:54 -08001207status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Andy Hung6a0fbd92023-11-30 19:34:24 -08001208NO_THREAD_SAFETY_ANALYSIS // update for trylock.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209{
Glenn Kasten44deb052012-02-05 18:09:08 -08001210 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 dumpPermissionDenial(fd);
1212 } else {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001213 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 if (!locked) {
1215 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001216 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 }
1218
1219 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001220
1221 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001222 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001223 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 mAudioCommandThread->dump(fd);
1225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001227 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001228 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001229 if (mOutputCommandThread != 0) {
1230 mOutputCommandThread->dump(fd);
1231 }
1232
Eric Laurentdce54a12014-03-10 12:19:46 -07001233 if (mAudioPolicyManager) {
1234 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001235 } else {
1236 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001237 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239
Kevin Rocard8be94972019-02-22 13:26:25 -08001240 mPackageManager.dump(fd);
1241
Andy Hung6a0fbd92023-11-30 19:34:24 -08001242 dumpReleaseLock(mMutex, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001243
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001244 if (mSpatializer != nullptr) {
1245 std::string dumpString = mSpatializer->toString(1 /* level */);
1246 write(fd, dumpString.c_str(), dumpString.size());
1247 } else {
1248 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1249 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1250 }
1251
Andy Hungc747c532022-03-07 21:41:14 -08001252 {
1253 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1254 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1255 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1256 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257 }
1258 return NO_ERROR;
1259}
1260
1261status_t AudioPolicyService::dumpPermissionDenial(int fd)
1262{
1263 const size_t SIZE = 256;
1264 char buffer[SIZE];
1265 String8 result;
1266 snprintf(buffer, SIZE, "Permission Denial: "
1267 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1268 IPCThreadState::self()->getCallingPid(),
1269 IPCThreadState::self()->getCallingUid());
1270 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001271 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 return NO_ERROR;
1273}
1274
1275status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001276 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001277 // make sure transactions reserved to AudioFlinger do not come from other processes
1278 switch (code) {
1279 case TRANSACTION_startOutput:
1280 case TRANSACTION_stopOutput:
1281 case TRANSACTION_releaseOutput:
1282 case TRANSACTION_getInputForAttr:
1283 case TRANSACTION_startInput:
1284 case TRANSACTION_stopInput:
1285 case TRANSACTION_releaseInput:
1286 case TRANSACTION_getOutputForEffect:
1287 case TRANSACTION_registerEffect:
1288 case TRANSACTION_unregisterEffect:
1289 case TRANSACTION_setEffectEnabled:
1290 case TRANSACTION_getStrategyForStream:
1291 case TRANSACTION_getOutputForAttr:
1292 case TRANSACTION_moveEffectsToIo:
1293 ALOGW("%s: transaction %d received from PID %d",
1294 __func__, code, IPCThreadState::self()->getCallingPid());
1295 return INVALID_OPERATION;
1296 default:
1297 break;
1298 }
1299
1300 // make sure the following transactions come from system components
1301 switch (code) {
1302 case TRANSACTION_setDeviceConnectionState:
1303 case TRANSACTION_handleDeviceConfigChange:
1304 case TRANSACTION_setPhoneState:
1305//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1306// case TRANSACTION_setForceUse:
1307 case TRANSACTION_initStreamVolume:
1308 case TRANSACTION_setStreamVolumeIndex:
1309 case TRANSACTION_setVolumeIndexForAttributes:
1310 case TRANSACTION_getStreamVolumeIndex:
1311 case TRANSACTION_getVolumeIndexForAttributes:
1312 case TRANSACTION_getMinVolumeIndexForAttributes:
1313 case TRANSACTION_getMaxVolumeIndexForAttributes:
1314 case TRANSACTION_isStreamActive:
1315 case TRANSACTION_isStreamActiveRemotely:
1316 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001317 case TRANSACTION_registerPolicyMixes:
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02001318 case TRANSACTION_updatePolicyMixes:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001319 case TRANSACTION_setMasterMono:
1320 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001321 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001322 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001323 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001324 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001325 case TRANSACTION_setA11yServicesUids:
1326 case TRANSACTION_setUidDeviceAffinities:
1327 case TRANSACTION_removeUidDeviceAffinities:
1328 case TRANSACTION_setUserIdDeviceAffinities:
1329 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001330 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001331 case TRANSACTION_listAudioVolumeGroups:
1332 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1333 case TRANSACTION_acquireSoundTriggerSession:
1334 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001335 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001336 case TRANSACTION_setRttEnabled:
1337 case TRANSACTION_isCallScreenModeSupported:
1338 case TRANSACTION_setDevicesRoleForStrategy:
1339 case TRANSACTION_setSupportedSystemUsages:
1340 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001341 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001342 case TRANSACTION_getDevicesForRoleAndStrategy:
1343 case TRANSACTION_getDevicesForAttributes:
1344 case TRANSACTION_setAllowedCapturePolicy:
1345 case TRANSACTION_onNewAudioModulesAvailable:
1346 case TRANSACTION_setCurrentImeUid:
1347 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1348 case TRANSACTION_setDevicesRoleForCapturePreset:
1349 case TRANSACTION_addDevicesRoleForCapturePreset:
1350 case TRANSACTION_removeDevicesRoleForCapturePreset:
1351 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001352 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001353 case TRANSACTION_getSpatializer:
1354 case TRANSACTION_setPreferredMixerAttributes:
1355 case TRANSACTION_clearPreferredMixerAttributes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001356 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1357 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1358 __func__, code, IPCThreadState::self()->getCallingPid(),
1359 IPCThreadState::self()->getCallingUid());
1360 return INVALID_OPERATION;
1361 }
1362 } break;
1363 default:
1364 break;
1365 }
1366
Andy Hungc747c532022-03-07 21:41:14 -08001367 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1368 mediautils::TimeCheck check(
1369 std::string("IAudioPolicyService::").append(methodName),
1370 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1371 if (timeout) {
1372 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1373 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1374 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1375 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1376 .record();
1377 } else {
1378 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1379 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001380 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1381 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1382 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001383
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001384 switch (code) {
1385 case SHELL_COMMAND_TRANSACTION: {
1386 int in = data.readFileDescriptor();
1387 int out = data.readFileDescriptor();
1388 int err = data.readFileDescriptor();
1389 int argc = data.readInt32();
1390 Vector<String16> args;
1391 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1392 args.add(data.readString16());
1393 }
1394 sp<IBinder> unusedCallback;
1395 sp<IResultReceiver> resultReceiver;
1396 status_t status;
1397 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1398 return status;
1399 }
1400 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1401 return status;
1402 }
1403 status = shellCommand(in, out, err, args);
1404 if (resultReceiver != nullptr) {
1405 resultReceiver->send(status);
1406 }
1407 return NO_ERROR;
1408 }
1409 }
1410
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1412}
1413
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001414// ------------------- Shell command implementation -------------------
1415
1416// NOTE: This is a remote API - make sure all args are validated
1417status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1418 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1419 return PERMISSION_DENIED;
1420 }
1421 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1422 return BAD_VALUE;
1423 }
jovanakbe066e12019-09-02 11:54:39 -07001424 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001425 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001426 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001427 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001428 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001429 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001430 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1431 purgePermissionCache();
1432 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001433 } else if (args.size() == 1 && args[0] == String16("help")) {
1434 printHelp(out);
1435 return NO_ERROR;
1436 }
1437 printHelp(err);
1438 return BAD_VALUE;
1439}
1440
jovanakbe066e12019-09-02 11:54:39 -07001441static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1442 if (userId < 0) {
1443 ALOGE("Invalid user: %d", userId);
1444 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001445 return BAD_VALUE;
1446 }
jovanakbe066e12019-09-02 11:54:39 -07001447
1448 PermissionController pc;
1449 uid = pc.getPackageUid(packageName, 0);
1450 if (uid <= 0) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001451 ALOGE("Unknown package: '%s'", String8(packageName).c_str());
1452 dprintf(err, "Unknown package: '%s'\n", String8(packageName).c_str());
jovanakbe066e12019-09-02 11:54:39 -07001453 return BAD_VALUE;
1454 }
1455
1456 uid = multiuser_get_uid(userId, uid);
1457 return NO_ERROR;
1458}
1459
1460status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1461 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1462 if (!(args.size() == 3 || args.size() == 5)) {
1463 printHelp(err);
1464 return BAD_VALUE;
1465 }
1466
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001467 bool active = false;
1468 if (args[2] == String16("active")) {
1469 active = true;
1470 } else if ((args[2] != String16("idle"))) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001471 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).c_str());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001472 return BAD_VALUE;
1473 }
jovanakbe066e12019-09-02 11:54:39 -07001474
1475 int userId = 0;
1476 if (args.size() >= 5 && args[3] == String16("--user")) {
1477 userId = atoi(String8(args[4]));
1478 }
1479
1480 uid_t uid;
1481 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1482 return BAD_VALUE;
1483 }
1484
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001485 sp<UidPolicy> uidPolicy;
1486 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001487 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001488 uidPolicy = mUidPolicy;
1489 }
1490 if (uidPolicy) {
1491 uidPolicy->addOverrideUid(uid, active);
1492 return NO_ERROR;
1493 }
1494 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001495}
1496
1497status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001498 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1499 if (!(args.size() == 2 || args.size() == 4)) {
1500 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001501 return BAD_VALUE;
1502 }
jovanakbe066e12019-09-02 11:54:39 -07001503
1504 int userId = 0;
1505 if (args.size() >= 4 && args[2] == String16("--user")) {
1506 userId = atoi(String8(args[3]));
1507 }
1508
1509 uid_t uid;
1510 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1511 return BAD_VALUE;
1512 }
1513
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001514 sp<UidPolicy> uidPolicy;
1515 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001516 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001517 uidPolicy = mUidPolicy;
1518 }
1519 if (uidPolicy) {
1520 uidPolicy->removeOverrideUid(uid);
1521 return NO_ERROR;
1522 }
1523 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001524}
1525
1526status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001527 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1528 if (!(args.size() == 2 || args.size() == 4)) {
1529 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001530 return BAD_VALUE;
1531 }
jovanakbe066e12019-09-02 11:54:39 -07001532
1533 int userId = 0;
1534 if (args.size() >= 4 && args[2] == String16("--user")) {
1535 userId = atoi(String8(args[3]));
1536 }
1537
1538 uid_t uid;
1539 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1540 return BAD_VALUE;
1541 }
1542
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001543 sp<UidPolicy> uidPolicy;
1544 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001545 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001546 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001547 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001548 if (uidPolicy) {
1549 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1550 }
1551 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001552}
1553
1554status_t AudioPolicyService::printHelp(int out) {
1555 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001556 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1557 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1558 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001559 " help print this message\n");
1560}
1561
Eric Laurent0d13fea2022-11-04 17:12:08 +01001562status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1563 const audio_config_base_t& config,
1564 const audio_output_flags_t flags) {
1565 return mUsecaseValidator->registerStream(output, config, flags);
1566}
1567
1568status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1569 return mUsecaseValidator->unregisterStream(output);
1570}
1571
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001572// ----------- AudioPolicyService::UidPolicy implementation ----------
1573
1574void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001575 status_t res = mAm.linkToDeath(this);
1576 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001577 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001578 | ActivityManager::UID_OBSERVER_ACTIVE
1579 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001580 ActivityManager::PROCESS_STATE_UNKNOWN,
1581 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001582 if (!res) {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001583 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001584 mObserverRegistered = true;
1585 } else {
1586 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001587
Steven Moreland2f348142019-07-02 15:59:07 -07001588 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001589 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001590}
1591
1592void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001593 mAm.unlinkToDeath(this);
1594 mAm.unregisterUidObserver(this);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001595 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001596 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001597}
1598
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001599void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001600 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001601 mCachedUids.clear();
1602 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001603}
1604
Eric Laurente8c8b432018-10-17 10:08:02 -07001605void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001606 bool needToReregister = false;
1607 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001608 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001609 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001610 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001611 if (needToReregister) {
1612 // Looks like ActivityManager has died previously, attempt to re-register.
1613 registerSelf();
1614 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001615}
1616
1617bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1618 if (isServiceUid(uid)) return true;
1619 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001620 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001621 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001622 auto overrideIter = mOverrideUids.find(uid);
1623 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001624 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001625 }
1626 // In an absense of the ActivityManager, assume everything to be active.
1627 if (!mObserverRegistered) return true;
1628 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001629 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001630 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001631 }
1632 }
1633 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001634 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001635 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001636 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001637 mCachedUids.insert(std::pair<uid_t,
1638 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1639 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001640 }
1641 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001642}
1643
Eric Laurente8c8b432018-10-17 10:08:02 -07001644int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1645 if (isServiceUid(uid)) {
1646 return ActivityManager::PROCESS_STATE_TOP;
1647 }
1648 checkRegistered();
1649 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001650 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001651 auto overrideIter = mOverrideUids.find(uid);
1652 if (overrideIter != mOverrideUids.end()) {
1653 if (overrideIter->second.first) {
1654 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1655 return overrideIter->second.second;
1656 } else {
1657 auto cacheIter = mCachedUids.find(uid);
1658 if (cacheIter != mCachedUids.end()) {
1659 return cacheIter->second.second;
1660 }
1661 }
1662 }
1663 return ActivityManager::PROCESS_STATE_UNKNOWN;
1664 }
1665 // In an absense of the ActivityManager, assume everything to be active.
1666 if (!mObserverRegistered) {
1667 return ActivityManager::PROCESS_STATE_TOP;
1668 }
1669 auto cacheIter = mCachedUids.find(uid);
1670 if (cacheIter != mCachedUids.end()) {
1671 if (cacheIter->second.first) {
1672 return cacheIter->second.second;
1673 } else {
1674 return ActivityManager::PROCESS_STATE_UNKNOWN;
1675 }
1676 }
1677 }
1678 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001679 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001680 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1681 if (active) {
1682 state = am.getUidProcessState(uid, String16("audioserver"));
1683 }
1684 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001685 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001686 mCachedUids.insert(std::pair<uid_t,
1687 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1688 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001689
Eric Laurente8c8b432018-10-17 10:08:02 -07001690 return state;
1691}
1692
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001693void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001694 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001695}
1696
1697void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001698 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001699}
1700
1701void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001702 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001703}
1704
Eric Laurente8c8b432018-10-17 10:08:02 -07001705void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1706 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001707 int64_t procStateSeq __unused,
1708 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001709 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1710 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001711 }
1712}
1713
Austin Borgerdddb7552023-03-30 17:53:01 -07001714void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001715}
1716
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001717void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001718 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1719}
1720
1721void AudioPolicyService::UidPolicy::notifyService() {
1722 sp<AudioPolicyService> service = mService.promote();
1723 if (service != nullptr) {
1724 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001725 }
1726}
1727
Eric Laurente8c8b432018-10-17 10:08:02 -07001728void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1729 std::pair<bool, int>> *uids,
1730 uid_t uid,
1731 bool active,
1732 int state,
1733 bool insert) {
1734 if (isServiceUid(uid)) {
1735 return;
1736 }
1737 bool wasActive = isUidActive(uid);
1738 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001739 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001740 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001741 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001742 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001743 if (wasActive != isUidActive(uid) || state != previousState) {
1744 notifyService();
1745 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001746}
1747
Eric Laurente8c8b432018-10-17 10:08:02 -07001748void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1749 std::pair<bool, int>> *uids,
1750 uid_t uid,
1751 bool active,
1752 int state,
1753 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001754 auto it = uids->find(uid);
1755 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001756 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001757 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1758 it->second.first = active;
1759 }
1760 if (it->second.first) {
1761 it->second.second = state;
1762 } else {
1763 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1764 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001765 } else {
1766 uids->erase(it);
1767 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001768 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1769 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1770 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001771 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001772}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773
Eric Laurent4eb58f12018-12-07 16:41:02 -08001774bool AudioPolicyService::UidPolicy::isA11yOnTop() {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001775 audio_utils::lock_guard _l(mMutex);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001776 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001777 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001778 continue;
1779 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001780 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1781 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001782 return true;
1783 }
1784 }
1785 return false;
1786}
1787
Eric Laurentb78763e2018-10-17 10:08:02 -07001788bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1789{
1790 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1791 return it != mA11yUids.end();
1792}
1793
Oscar Azucena829d90d2022-01-28 17:17:56 -08001794void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1795 mAssistantUids.clear();
1796 mAssistantUids = uids;
1797}
1798
1799bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1800{
1801 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1802 return it != mAssistantUids.end();
1803}
1804
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001805void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1806 mActiveAssistantUids = activeUids;
1807}
1808
1809bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1810{
1811 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1812 mActiveAssistantUids.end(), uid);
1813 return it != mActiveAssistantUids.end();
1814}
1815
Oscar Azucena829d90d2022-01-28 17:17:56 -08001816void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1817 const size_t SIZE = 256;
1818 char buffer[SIZE];
1819 String8 result;
1820 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1821 snprintf(buffer, SIZE, "\t%s: \n", title);
1822 result.append(buffer);
1823 int counter = 0;
1824 if (uids.empty()) {
1825 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1826 result.append(buffer);
1827 return;
1828 }
1829 for (const auto &uid : uids) {
1830 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1831 result.append(buffer);
1832 }
1833 };
1834
1835 snprintf(buffer, SIZE, "UID Policy:\n");
1836 result.append(buffer);
1837 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1838 result.append(buffer);
1839
1840 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001841 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001842
1843 appendUidsToResult("Accessibility UIDs", mA11yUids);
1844
1845 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1846 result.append(buffer);
1847
1848 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1849 result.append(buffer);
1850
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001851 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001852}
1853
Michael Groovercfd28302018-12-11 19:16:46 -08001854// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1855void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1856 SensorPrivacyManager spm;
1857 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1858 spm.addSensorPrivacyListener(this);
1859}
1860
1861void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1862 SensorPrivacyManager spm;
1863 spm.removeSensorPrivacyListener(this);
1864}
1865
1866bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1867 return mSensorPrivacyEnabled;
1868}
1869
Evan Seversond8dc6832022-01-27 10:47:03 -08001870binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1871 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001872 mSensorPrivacyEnabled = enabled;
1873 sp<AudioPolicyService> service = mService.promote();
1874 if (service != nullptr) {
1875 service->updateUidStates();
1876 }
1877 return binder::Status::ok();
1878}
1879
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1881
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1883 const wp<AudioPolicyService>& service)
1884 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886}
1887
1888
1889AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1890{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001891 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001892 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895}
1896
1897void AudioPolicyService::AudioCommandThread::onFirstRef()
1898{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001899 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900}
1901
1902bool AudioPolicyService::AudioCommandThread::threadLoop()
1903{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001904 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905
Andy Hung6a0fbd92023-11-30 19:34:24 -08001906 audio_utils::unique_lock ul(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 while (!exitPending())
1908 {
Eric Laurent59a89232014-06-08 14:14:17 -07001909 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001910 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001911 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912 nsecs_t curTime = systemTime();
1913 // commands are sorted by increasing time stamp: execute them from index 0 and up
1914 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001915 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001917 if (mAudioCommands.isEmpty()) {
1918 ++numTimesBecameEmpty;
1919 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001920 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921
1922 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001924 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001925 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001926 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001927 ul.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001928 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1929 data->mVolume,
1930 data->mIO);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001931 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 }break;
1933 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001934 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001935 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001936 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001937 ul.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001938 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001939 ul.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001940 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001942 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001943 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001944 data->mVolume);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001945 ul.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001947 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001949 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001950 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001951 ALOGV("AudioCommandThread() processing stop output portId %d",
1952 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001953 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954 if (svc == 0) {
1955 break;
1956 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08001957 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001958 svc->doStopOutput(data->mPortId);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001959 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960 }break;
1961 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001962 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001963 ALOGV("AudioCommandThread() processing release output portId %d",
1964 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001965 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001966 if (svc == 0) {
1967 break;
1968 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08001969 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001970 svc->doReleaseOutput(data->mPortId);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001971 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001972 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001973 case CREATE_AUDIO_PATCH: {
1974 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1975 ALOGV("AudioCommandThread() processing create audio patch");
1976 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1977 if (af == 0) {
1978 command->mStatus = PERMISSION_DENIED;
1979 } else {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001980 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001981 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001982 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001983 }
1984 } break;
1985 case RELEASE_AUDIO_PATCH: {
1986 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1987 ALOGV("AudioCommandThread() processing release audio patch");
1988 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1989 if (af == 0) {
1990 command->mStatus = PERMISSION_DENIED;
1991 } else {
Andy Hung6a0fbd92023-11-30 19:34:24 -08001992 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001993 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hung6a0fbd92023-11-30 19:34:24 -08001994 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001995 }
1996 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001997 case UPDATE_AUDIOPORT_LIST: {
1998 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001999 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002000 if (svc == 0) {
2001 break;
2002 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002003 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002004 svc->doOnAudioPortListUpdate();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002005 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002006 }break;
2007 case UPDATE_AUDIOPATCH_LIST: {
2008 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07002009 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002010 if (svc == 0) {
2011 break;
2012 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002013 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002014 svc->doOnAudioPatchListUpdate();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002015 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002016 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01002017 case CHANGED_AUDIOVOLUMEGROUP: {
2018 AudioVolumeGroupData *data =
2019 static_cast<AudioVolumeGroupData *>(command->mParam.get());
2020 ALOGV("AudioCommandThread() processing update audio volume group");
2021 svc = mService.promote();
2022 if (svc == 0) {
2023 break;
2024 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002025 ul.unlock();
François Gaffiecfe17322018-11-07 13:41:29 +01002026 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
Andy Hung6a0fbd92023-11-30 19:34:24 -08002027 ul.lock();
François Gaffiecfe17322018-11-07 13:41:29 +01002028 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07002029 case SET_AUDIOPORT_CONFIG: {
2030 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
2031 ALOGV("AudioCommandThread() processing set port config");
2032 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2033 if (af == 0) {
2034 command->mStatus = PERMISSION_DENIED;
2035 } else {
Andy Hung6a0fbd92023-11-30 19:34:24 -08002036 ul.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07002037 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hung6a0fbd92023-11-30 19:34:24 -08002038 ul.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07002039 }
2040 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07002041 case DYN_POLICY_MIX_STATE_UPDATE: {
2042 DynPolicyMixStateUpdateData *data =
2043 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002044 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002045 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002046 svc = mService.promote();
2047 if (svc == 0) {
2048 break;
2049 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002050 ul.unlock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002051 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
Andy Hung6a0fbd92023-11-30 19:34:24 -08002052 ul.lock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002053 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002054 case RECORDING_CONFIGURATION_UPDATE: {
2055 RecordingConfigurationUpdateData *data =
2056 (RecordingConfigurationUpdateData *)command->mParam.get();
2057 ALOGV("AudioCommandThread() processing recording configuration update");
2058 svc = mService.promote();
2059 if (svc == 0) {
2060 break;
2061 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002062 ul.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002063 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08002064 &data->mClientConfig, data->mClientEffects,
2065 &data->mDeviceConfig, data->mEffects,
2066 data->mPatchHandle, data->mSource);
Andy Hung6a0fbd92023-11-30 19:34:24 -08002067 ul.lock();
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002068 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002069 case SET_EFFECT_SUSPENDED: {
2070 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
2071 ALOGV("AudioCommandThread() processing set effect suspended");
2072 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2073 if (af != 0) {
Andy Hung6a0fbd92023-11-30 19:34:24 -08002074 ul.unlock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002075 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
Andy Hung6a0fbd92023-11-30 19:34:24 -08002076 ul.lock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002077 }
2078 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002079 case AUDIO_MODULES_UPDATE: {
2080 ALOGV("AudioCommandThread() processing audio modules update");
2081 svc = mService.promote();
2082 if (svc == 0) {
2083 break;
2084 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002085 ul.unlock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002086 svc->doOnNewAudioModulesAvailable();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002087 ul.lock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002088 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002089 case ROUTING_UPDATED: {
2090 ALOGV("AudioCommandThread() processing routing update");
2091 svc = mService.promote();
2092 if (svc == 0) {
2093 break;
2094 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002095 ul.unlock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002096 svc->doOnRoutingUpdated();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002097 ul.lock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002098 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002099
Eric Laurented726cc2021-07-01 14:26:41 +02002100 case UPDATE_UID_STATES: {
2101 ALOGV("AudioCommandThread() processing updateUID states");
2102 svc = mService.promote();
2103 if (svc == 0) {
2104 break;
2105 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002106 ul.unlock();
Eric Laurented726cc2021-07-01 14:26:41 +02002107 svc->updateUidStates();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002108 ul.lock();
Eric Laurented726cc2021-07-01 14:26:41 +02002109 } break;
2110
Eric Laurent15903592022-02-24 20:44:36 +01002111 case CHECK_SPATIALIZER_OUTPUT: {
2112 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002113 svc = mService.promote();
2114 if (svc == 0) {
2115 break;
2116 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002117 ul.unlock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002118 svc->doOnCheckSpatializer();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002119 ul.lock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002120 } break;
2121
Eric Laurent15903592022-02-24 20:44:36 +01002122 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2123 ALOGV("AudioCommandThread() processing update spatializer tracks");
2124 svc = mService.promote();
2125 if (svc == 0) {
2126 break;
2127 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002128 ul.unlock();
Eric Laurent15903592022-02-24 20:44:36 +01002129 svc->doOnUpdateActiveSpatializerTracks();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002130 ul.lock();
Eric Laurent15903592022-02-24 20:44:36 +01002131 } break;
2132
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002133 case VOL_RANGE_INIT_REQUEST: {
2134 ALOGV("AudioCommandThread() processing volume range init request");
2135 svc = mService.promote();
2136 if (svc == 0) {
2137 break;
2138 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002139 ul.unlock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002140 svc->doOnVolumeRangeInitRequest();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002141 ul.lock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002142 } break;
2143
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002145 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002147 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08002148 audio_utils::lock_guard _l(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002149 if (command->mWaitStatus) {
2150 command->mWaitStatus = false;
Andy Hung6a0fbd92023-11-30 19:34:24 -08002151 command->mCond.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002152 }
2153 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002154 waitTime = -1;
Andy Hung6a0fbd92023-11-30 19:34:24 -08002155 // release ul before releasing strong reference on the service as
Zach Janga754b4f2015-10-27 01:29:34 +00002156 // AudioPolicyService destructor calls AudioCommandThread::exit() which
Andy Hung6a0fbd92023-11-30 19:34:24 -08002157 // acquires ul.
2158 ul.unlock();
Zach Janga754b4f2015-10-27 01:29:34 +00002159 svc.clear();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002160 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 } else {
2162 waitTime = mAudioCommands[0]->mTime - curTime;
2163 break;
2164 }
2165 }
Zach Janga754b4f2015-10-27 01:29:34 +00002166
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002167 // release delayed commands wake lock as many times as we made the queue is
2168 // empty during popping.
2169 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002170 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002171 }
2172
2173 // At this stage we have either an empty command queue or the first command in the queue
2174 // has a finite delay. So unless we are exiting it is safe to wait.
2175 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002176 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002177 if (waitTime == -1) {
Andy Hung6a0fbd92023-11-30 19:34:24 -08002178 mWaitWorkCV.wait(ul);
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002179 } else {
Andy Hung6a0fbd92023-11-30 19:34:24 -08002180 // discard return value.
2181 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002182 }
Eric Laurent59a89232014-06-08 14:14:17 -07002183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002185 // release delayed commands wake lock before quitting
2186 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002187 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 return false;
2190}
2191
2192status_t AudioPolicyService::AudioCommandThread::dump(int fd)
Andy Hung6a0fbd92023-11-30 19:34:24 -08002193NO_THREAD_SAFETY_ANALYSIS // trylock
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194{
2195 const size_t SIZE = 256;
2196 char buffer[SIZE];
2197 String8 result;
2198
Andy Hung6a0fbd92023-11-30 19:34:24 -08002199 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 if (!locked) {
2201 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002202 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
2204
2205 snprintf(buffer, SIZE, "- Commands:\n");
2206 result = String8(buffer);
2207 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002208 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209 mAudioCommands[i]->dump(buffer, SIZE);
2210 result.append(buffer);
2211 }
2212 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002213 if (mLastCommand != 0) {
2214 mLastCommand->dump(buffer, SIZE);
2215 result.append(buffer);
2216 } else {
2217 result.append(" none\n");
2218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002220 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221
Andy Hung6a0fbd92023-11-30 19:34:24 -08002222 dumpReleaseLock(mMutex, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223
2224 return NO_ERROR;
2225}
2226
Glenn Kastenfff6d712012-01-12 16:38:12 -08002227status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002228 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002229 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002230 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231{
Eric Laurent0ede8922014-05-09 18:04:42 -07002232 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002234 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 data->mStream = stream;
2236 data->mVolume = volume;
2237 data->mIO = output;
2238 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002239 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002240 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002241 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002242 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243}
2244
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002245status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002246 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002247 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248{
Eric Laurent0ede8922014-05-09 18:04:42 -07002249 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002251 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002253 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002255 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002256 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002257 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002258 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259}
2260
2261status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2262{
Eric Laurent0ede8922014-05-09 18:04:42 -07002263 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002265 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 data->mVolume = volume;
2267 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002268 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002269 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002270 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271}
2272
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002273void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2274 audio_session_t sessionId,
2275 bool suspended)
2276{
2277 sp<AudioCommand> command = new AudioCommand();
2278 command->mCommand = SET_EFFECT_SUSPENDED;
2279 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2280 data->mEffectId = effectId;
2281 data->mSessionId = sessionId;
2282 data->mSuspended = suspended;
2283 command->mParam = data;
2284 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2285 effectId, sessionId, suspended);
2286 sendCommand(command);
2287}
2288
2289
Eric Laurentd7fe0862018-07-14 16:48:01 -07002290void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002291{
Eric Laurent0ede8922014-05-09 18:04:42 -07002292 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002293 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002294 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002295 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002296 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002297 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002298 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299}
2300
Eric Laurentd7fe0862018-07-14 16:48:01 -07002301void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002302{
Eric Laurent0ede8922014-05-09 18:04:42 -07002303 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002304 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002305 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002306 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002307 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002308 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002309 sendCommand(command);
2310}
2311
Eric Laurent951f4552014-05-20 10:48:17 -07002312status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2313 const struct audio_patch *patch,
2314 audio_patch_handle_t *handle,
2315 int delayMs)
2316{
2317 status_t status = NO_ERROR;
2318
2319 sp<AudioCommand> command = new AudioCommand();
2320 command->mCommand = CREATE_AUDIO_PATCH;
2321 CreateAudioPatchData *data = new CreateAudioPatchData();
2322 data->mPatch = *patch;
2323 data->mHandle = *handle;
2324 command->mParam = data;
2325 command->mWaitStatus = true;
2326 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2327 status = sendCommand(command, delayMs);
2328 if (status == NO_ERROR) {
2329 *handle = data->mHandle;
2330 }
2331 return status;
2332}
2333
2334status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2335 int delayMs)
2336{
2337 sp<AudioCommand> command = new AudioCommand();
2338 command->mCommand = RELEASE_AUDIO_PATCH;
2339 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2340 data->mHandle = handle;
2341 command->mParam = data;
2342 command->mWaitStatus = true;
2343 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2344 return sendCommand(command, delayMs);
2345}
2346
Eric Laurentb52c1522014-05-20 11:27:36 -07002347void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2348{
2349 sp<AudioCommand> command = new AudioCommand();
2350 command->mCommand = UPDATE_AUDIOPORT_LIST;
2351 ALOGV("AudioCommandThread() adding update audio port list");
2352 sendCommand(command);
2353}
2354
Eric Laurented726cc2021-07-01 14:26:41 +02002355void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2356{
2357 sp<AudioCommand> command = new AudioCommand();
2358 command->mCommand = UPDATE_UID_STATES;
2359 ALOGV("AudioCommandThread() adding update UID states");
2360 sendCommand(command);
2361}
2362
Eric Laurentb52c1522014-05-20 11:27:36 -07002363void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2364{
2365 sp<AudioCommand>command = new AudioCommand();
2366 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2367 ALOGV("AudioCommandThread() adding update audio patch list");
2368 sendCommand(command);
2369}
2370
François Gaffiecfe17322018-11-07 13:41:29 +01002371void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2372 int flags)
2373{
2374 sp<AudioCommand>command = new AudioCommand();
2375 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2376 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2377 data->mGroup = group;
2378 data->mFlags = flags;
2379 command->mParam = data;
2380 ALOGV("AudioCommandThread() adding audio volume group changed");
2381 sendCommand(command);
2382}
2383
Eric Laurente1715a42014-05-20 11:30:42 -07002384status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2385 const struct audio_port_config *config, int delayMs)
2386{
2387 sp<AudioCommand> command = new AudioCommand();
2388 command->mCommand = SET_AUDIOPORT_CONFIG;
2389 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2390 data->mConfig = *config;
2391 command->mParam = data;
2392 command->mWaitStatus = true;
2393 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2394 return sendCommand(command, delayMs);
2395}
2396
Jean-Michel Trivide801052015-04-14 19:10:14 -07002397void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002398 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002399{
2400 sp<AudioCommand> command = new AudioCommand();
2401 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2402 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2403 data->mRegId = regId;
2404 data->mState = state;
2405 command->mParam = data;
2406 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002407 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002408 sendCommand(command);
2409}
2410
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002411void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002412 int event,
2413 const record_client_info_t *clientInfo,
2414 const audio_config_base_t *clientConfig,
2415 std::vector<effect_descriptor_t> clientEffects,
2416 const audio_config_base_t *deviceConfig,
2417 std::vector<effect_descriptor_t> effects,
2418 audio_patch_handle_t patchHandle,
2419 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002420{
2421 sp<AudioCommand>command = new AudioCommand();
2422 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2423 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2424 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002425 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002426 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002427 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002428 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002429 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002430 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002431 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002432 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002433 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2434 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002435 sendCommand(command);
2436}
2437
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002438void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2439{
2440 sp<AudioCommand> command = new AudioCommand();
2441 command->mCommand = AUDIO_MODULES_UPDATE;
2442 sendCommand(command);
2443}
2444
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002445void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2446{
2447 sp<AudioCommand>command = new AudioCommand();
2448 command->mCommand = ROUTING_UPDATED;
2449 ALOGV("AudioCommandThread() adding routing update");
2450 sendCommand(command);
2451}
2452
Eric Laurent81dd0f52021-07-05 11:54:40 +02002453void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2454{
2455 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002456 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002457 ALOGV("AudioCommandThread() adding check spatializer");
2458 sendCommand(command);
2459}
2460
Eric Laurent15903592022-02-24 20:44:36 +01002461void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2462{
2463 sp<AudioCommand>command = new AudioCommand();
2464 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2465 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2466 sendCommand(command);
2467}
2468
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002469void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2470{
2471 sp<AudioCommand>command = new AudioCommand();
2472 command->mCommand = VOL_RANGE_INIT_REQUEST;
2473 ALOGV("AudioCommandThread() adding volume range init request");
2474 sendCommand(command);
2475}
2476
Eric Laurent0ede8922014-05-09 18:04:42 -07002477status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2478{
2479 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08002480 audio_utils::lock_guard _l(mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002481 insertCommand_l(command, delayMs);
Andy Hung6a0fbd92023-11-30 19:34:24 -08002482 mWaitWorkCV.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002483 }
Andy Hung6a0fbd92023-11-30 19:34:24 -08002484 audio_utils::unique_lock ul(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002485 while (command->mWaitStatus) {
2486 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
Andy Hung6a0fbd92023-11-30 19:34:24 -08002487 if (command->mCond.wait_for(
Andy Hung5529c132024-01-25 17:02:30 -08002488 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002489 command->mStatus = TIMED_OUT;
2490 command->mWaitStatus = false;
2491 }
2492 }
2493 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002494}
2495
Andy Hung6a0fbd92023-11-30 19:34:24 -08002496// insertCommand_l() must be called with mMutex held
Eric Laurent0ede8922014-05-09 18:04:42 -07002497void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002499 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002500 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 command->mTime = systemTime() + milliseconds(delayMs);
2502
2503 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002504 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002505 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 }
2507
2508 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002509 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002510 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2512 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002513
2514 // create audio patch or release audio patch commands are equivalent
2515 // with regard to filtering
2516 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2517 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2518 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2519 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2520 continue;
2521 }
2522 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523
2524 switch (command->mCommand) {
2525 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002526 ParametersData *data = (ParametersData *)command->mParam.get();
2527 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002529 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002530 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2532 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2533 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002534 String8 key;
2535 String8 value;
2536 param.getAt(j, key, value);
2537 for (size_t k = 0; k < param2.size(); k++) {
2538 String8 key2;
2539 String8 value2;
2540 param2.getAt(k, key2, value2);
2541 if (key2 == key) {
2542 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002543 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002544 break;
2545 }
2546 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 }
2548 // if all keys have been filtered out, remove the command.
2549 // otherwise, update the key value pairs
2550 if (param2.size() == 0) {
2551 removedCommands.add(command2);
2552 } else {
2553 data2->mKeyValuePairs = param2.toString();
2554 }
Eric Laurent21e54562013-09-23 12:08:05 -07002555 command->mTime = command2->mTime;
2556 // force delayMs to non 0 so that code below does not request to wait for
2557 // command status as the command is now delayed
2558 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 } break;
2560
2561 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002562 VolumeData *data = (VolumeData *)command->mParam.get();
2563 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 if (data->mIO != data2->mIO) break;
2565 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002566 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002567 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002569 command->mTime = command2->mTime;
2570 // force delayMs to non 0 so that code below does not request to wait for
2571 // command status as the command is now delayed
2572 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002574
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002575 case SET_VOICE_VOLUME: {
2576 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2577 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2578 ALOGV("Filtering out voice volume command value %f replaced by %f",
2579 data2->mVolume, data->mVolume);
2580 removedCommands.add(command2);
2581 command->mTime = command2->mTime;
2582 // force delayMs to non 0 so that code below does not request to wait for
2583 // command status as the command is now delayed
2584 delayMs = 1;
2585 } break;
2586
Eric Laurente45b48a2014-09-04 16:40:57 -07002587 case CREATE_AUDIO_PATCH:
2588 case RELEASE_AUDIO_PATCH: {
2589 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002590 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002591 if (command->mCommand == CREATE_AUDIO_PATCH) {
2592 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002593 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002594 } else {
2595 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002596 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002597 }
2598 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002599 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002600 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2601 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002602 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002603 } else {
2604 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002605 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002606 }
2607 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002608 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2609 same output. */
2610 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2611 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2612 bool isOutputDiff = false;
2613 if (patch.num_sources == patch2.num_sources) {
2614 for (unsigned count = 0; count < patch.num_sources; count++) {
2615 if (patch.sources[count].id != patch2.sources[count].id) {
2616 isOutputDiff = true;
2617 break;
2618 }
2619 }
2620 if (isOutputDiff)
2621 break;
2622 }
2623 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002624 ALOGV("Filtering out %s audio patch command for handle %d",
2625 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2626 removedCommands.add(command2);
2627 command->mTime = command2->mTime;
2628 // force delayMs to non 0 so that code below does not request to wait for
2629 // command status as the command is now delayed
2630 delayMs = 1;
2631 } break;
2632
Jean-Michel Trivide801052015-04-14 19:10:14 -07002633 case DYN_POLICY_MIX_STATE_UPDATE: {
2634
2635 } break;
2636
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002637 case RECORDING_CONFIGURATION_UPDATE: {
2638
2639 } break;
2640
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002641 case ROUTING_UPDATED: {
2642
2643 } break;
2644
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002645 case VOL_RANGE_INIT_REQUEST: {
2646 // command may come from different requests, do not filter
2647 } break;
2648
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 default:
2650 break;
2651 }
2652 }
2653
2654 // remove filtered commands
2655 for (size_t j = 0; j < removedCommands.size(); j++) {
2656 // removed commands always have time stamps greater than current command
2657 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002658 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002659 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 mAudioCommands.removeAt(k);
2661 break;
2662 }
2663 }
2664 }
2665 removedCommands.clear();
2666
Eric Laurentaa79bef2015-01-15 14:33:51 -08002667 // Disable wait for status if delay is not 0.
2668 // Except for create audio patch command because the returned patch handle
2669 // is needed by audio policy manager
2670 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002671 command->mWaitStatus = false;
2672 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002673
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002675 ALOGV("inserting command: %d at index %zd, num commands %zu",
2676 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 mAudioCommands.insertAt(command, i + 1);
2678}
2679
2680void AudioPolicyService::AudioCommandThread::exit()
2681{
Steve Block3856b092011-10-20 11:56:00 +01002682 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 {
Andy Hung6a0fbd92023-11-30 19:34:24 -08002684 audio_utils::lock_guard _l(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 requestExit();
Andy Hung6a0fbd92023-11-30 19:34:24 -08002686 mWaitWorkCV.notify_one();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 }
Zach Janga754b4f2015-10-27 01:29:34 +00002688 // Note that we can call it from the thread loop if all other references have been released
2689 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 requestExitAndWait();
2691}
2692
2693void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2694{
2695 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2696 mCommand,
2697 (int)ns2s(mTime),
2698 (int)ns2ms(mTime)%1000,
2699 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002700 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701}
2702
Dima Zavinfce7a472011-04-19 22:30:36 -07002703/******* helpers for the service_ops callbacks defined below *********/
2704void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2705 const char *keyValuePairs,
2706 int delayMs)
2707{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002708 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002709 delayMs);
2710}
2711
2712int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2713 float volume,
2714 audio_io_handle_t output,
2715 int delayMs)
2716{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002717 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002718 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002719}
2720
Dima Zavinfce7a472011-04-19 22:30:36 -07002721int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2722{
2723 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2724}
2725
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002726void AudioPolicyService::setEffectSuspended(int effectId,
2727 audio_session_t sessionId,
2728 bool suspended)
2729{
2730 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2731}
2732
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002733Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002734{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002735 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002736 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002737}
2738
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002739
Dima Zavinfce7a472011-04-19 22:30:36 -07002740extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002741audio_module_handle_t aps_load_hw_module(void *service __unused,
2742 const char *name);
2743audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002744 audio_devices_t *pDevices,
2745 uint32_t *pSamplingRate,
2746 audio_format_t *pFormat,
2747 audio_channel_mask_t *pChannelMask,
2748 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002749 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002750
Eric Laurent2d388ec2014-03-07 13:25:54 -08002751audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002752 audio_module_handle_t module,
2753 audio_devices_t *pDevices,
2754 uint32_t *pSamplingRate,
2755 audio_format_t *pFormat,
2756 audio_channel_mask_t *pChannelMask,
2757 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002758 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002759 const audio_offload_info_t *offloadInfo);
2760audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002761 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002762 audio_io_handle_t output2);
2763int aps_close_output(void *service __unused, audio_io_handle_t output);
2764int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2765int aps_restore_output(void *service __unused, audio_io_handle_t output);
2766audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002767 audio_devices_t *pDevices,
2768 uint32_t *pSamplingRate,
2769 audio_format_t *pFormat,
2770 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002771 audio_in_acoustics_t acoustics __unused);
2772audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002773 audio_module_handle_t module,
2774 audio_devices_t *pDevices,
2775 uint32_t *pSamplingRate,
2776 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002777 audio_channel_mask_t *pChannelMask);
2778int aps_close_input(void *service __unused, audio_io_handle_t input);
2779int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002780int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002781 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002782 audio_io_handle_t dst_output);
2783char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2784 const char *keys);
2785void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2786 const char *kv_pairs, int delay_ms);
2787int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002788 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002789 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002790int aps_set_voice_volume(void *service, float volume, int delay_ms);
2791};
Dima Zavinfce7a472011-04-19 22:30:36 -07002792
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002793} // namespace android