blob: bc6498a0a722aaa32a4d9d9e29c7459f69136773 [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#undef __STRICT_ANSI__
22#define __STDINT_LIMITS
23#define __STDC_LIMIT_MACROS
24#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053026#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070027
28#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <binder/IServiceManager.h>
30#include <utils/Log.h>
31#include <cutils/properties.h>
32#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080033#include <binder/PermissionController.h>
34#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
Atneya Nair5b1ed642023-06-23 14:43:37 -070037#include "AudioRecordClient.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080040#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070041#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080042#include <media/AudioParameter.h>
Andy Hungc747c532022-03-07 21:41:14 -080043#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070044#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080045#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080046#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070049#include <system/audio_policy.h>
Mikhail Naganov68e3f642023-04-28 13:06:32 -070050#include <AudioPolicyConfig.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053051#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080054using binder::Status;
Shunkai Yao49bc61f2023-10-10 19:31:10 +000055using media::audio::common::Spatialization;
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten8dad0e32012-01-09 08:41:22 -080057static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
58static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053059static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070060
Mikhail Naganov959e2d02019-03-28 11:08:19 -070061static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Eric Laurent0ede8922014-05-09 18:04:42 -070063static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010064
Svet Ganovf4ddfef2018-01-16 07:37:58 -080065static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070066
Andy Hungc747c532022-03-07 21:41:14 -080067// Creates an association between Binder code to name for IAudioPolicyService.
68#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
69BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
70BINDER_METHOD_ENTRY(setDeviceConnectionState) \
71BINDER_METHOD_ENTRY(getDeviceConnectionState) \
72BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
73BINDER_METHOD_ENTRY(setPhoneState) \
74BINDER_METHOD_ENTRY(setForceUse) \
75BINDER_METHOD_ENTRY(getForceUse) \
76BINDER_METHOD_ENTRY(getOutput) \
77BINDER_METHOD_ENTRY(getOutputForAttr) \
78BINDER_METHOD_ENTRY(startOutput) \
79BINDER_METHOD_ENTRY(stopOutput) \
80BINDER_METHOD_ENTRY(releaseOutput) \
81BINDER_METHOD_ENTRY(getInputForAttr) \
82BINDER_METHOD_ENTRY(startInput) \
83BINDER_METHOD_ENTRY(stopInput) \
84BINDER_METHOD_ENTRY(releaseInput) \
85BINDER_METHOD_ENTRY(initStreamVolume) \
86BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
87BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
88BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
90BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
91BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
92BINDER_METHOD_ENTRY(getStrategyForStream) \
93BINDER_METHOD_ENTRY(getDevicesForAttributes) \
94BINDER_METHOD_ENTRY(getOutputForEffect) \
95BINDER_METHOD_ENTRY(registerEffect) \
96BINDER_METHOD_ENTRY(unregisterEffect) \
97BINDER_METHOD_ENTRY(setEffectEnabled) \
98BINDER_METHOD_ENTRY(moveEffectsToIo) \
99BINDER_METHOD_ENTRY(isStreamActive) \
100BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
101BINDER_METHOD_ENTRY(isSourceActive) \
102BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
103BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
104BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
105BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
106BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
107BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
108BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
109BINDER_METHOD_ENTRY(getOffloadSupport) \
110BINDER_METHOD_ENTRY(isDirectOutputSupported) \
111BINDER_METHOD_ENTRY(listAudioPorts) \
112BINDER_METHOD_ENTRY(getAudioPort) \
113BINDER_METHOD_ENTRY(createAudioPatch) \
114BINDER_METHOD_ENTRY(releaseAudioPatch) \
115BINDER_METHOD_ENTRY(listAudioPatches) \
116BINDER_METHOD_ENTRY(setAudioPortConfig) \
117BINDER_METHOD_ENTRY(registerClient) \
118BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
119BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
120BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
121BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
122BINDER_METHOD_ENTRY(getPhoneState) \
123BINDER_METHOD_ENTRY(registerPolicyMixes) \
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +0200124BINDER_METHOD_ENTRY(updatePolicyMixes) \
Andy Hungc747c532022-03-07 21:41:14 -0800125BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
126BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
127BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
128BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
129BINDER_METHOD_ENTRY(startAudioSource) \
130BINDER_METHOD_ENTRY(stopAudioSource) \
131BINDER_METHOD_ENTRY(setMasterMono) \
132BINDER_METHOD_ENTRY(getMasterMono) \
133BINDER_METHOD_ENTRY(getStreamVolumeDB) \
134BINDER_METHOD_ENTRY(getSurroundFormats) \
135BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
136BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
137BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
138BINDER_METHOD_ENTRY(setAssistantServicesUids) \
139BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
140BINDER_METHOD_ENTRY(setA11yServicesUids) \
141BINDER_METHOD_ENTRY(setCurrentImeUid) \
142BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
143BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800144BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800145BINDER_METHOD_ENTRY(listAudioProductStrategies) \
146BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
147BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
148BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
149BINDER_METHOD_ENTRY(setRttEnabled) \
150BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
151BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
152BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000153BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800154BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
155BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
156BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
157BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
158BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
159BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
160BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
161BINDER_METHOD_ENTRY(getSpatializer) \
162BINDER_METHOD_ENTRY(canBeSpatialized) \
163BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000164BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
165BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
166BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
167BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
168BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100169BINDER_METHOD_ENTRY(getRegisteredPolicyMixes) \
170 \
Andy Hungc747c532022-03-07 21:41:14 -0800171// singleton for Binder Method Statistics for IAudioPolicyService
172static auto& getIAudioPolicyServiceStatistics() {
173 using Code = int;
174
175#pragma push_macro("BINDER_METHOD_ENTRY")
176#undef BINDER_METHOD_ENTRY
177#define BINDER_METHOD_ENTRY(ENTRY) \
178 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
179
180 static mediautils::MethodStatistics<Code> methodStatistics{
181 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
182 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
183 };
184#pragma pop_macro("BINDER_METHOD_ENTRY")
185
186 return methodStatistics;
187}
188
Mathias Agopian65ab4712010-07-14 17:59:35 -0700189// ----------------------------------------------------------------------------
190
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530191static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
192{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700193 AudioPolicyManager *apm = nullptr;
194 media::AudioPolicyConfig apmConfig;
195 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
196 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
197 LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
198 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
199 "Only default engine is currently supported with the AIDL HAL");
200 apm = new AudioPolicyManager(config,
201 loadApmEngineLibraryAndCreateEngine(
202 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
203 clientInterface);
204 } else {
205 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
206 apm = new AudioPolicyManager(config,
207 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
208 clientInterface);
209 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530210 status_t status = apm->initialize();
211 if (status != NO_ERROR) {
212 delete apm;
213 apm = nullptr;
214 }
215 return apm;
216}
217
218static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
219{
220 delete interface;
221}
222// ----------------------------------------------------------------------------
223
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700225 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700226 mAudioPolicyManager(NULL),
227 mAudioPolicyClient(NULL),
228 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530229 mCaptureStateNotifier(false),
230 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100231 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
232 mUsecaseValidator(media::createUsecaseValidator()) {
Andy Hung225aef62022-12-06 16:33:20 -0800233 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530234}
235
236void AudioPolicyService::loadAudioPolicyManager()
237{
238 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
239 if (mLibraryHandle != nullptr) {
240 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
241 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
242 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
243 const char *lastError = dlerror();
244 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
245 __func__, lastError != nullptr ? lastError : "no error");
246
247 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
248 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
249 lastError = dlerror();
250 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
251 __func__, lastError != nullptr ? lastError : "no error");
252 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
253 unloadAudioPolicyManager();
254 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
255 }
256 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700257}
258
259void AudioPolicyService::onFirstRef()
260{
Andy Hungd47aca22022-03-15 11:50:51 -0700261 // Log an AudioPolicy "constructor" mediametrics event on first ref.
262 // This records the time it takes to load the audio modules and devices.
263 mediametrics::Defer defer([beginNs = systemTime()] {
264 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
265 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
266 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
267 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700268 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800269 audio_utils::lock_guard _l(mMutex);
Eric Laurent93575202011-01-18 18:39:02 -0800270
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700271 // start audio commands thread
272 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
273 // start output activity command thread
274 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700275
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700276 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530277
278 loadAudioPolicyManager();
279 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700280 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200281
bryant_liuba2b4392014-06-11 16:49:30 +0800282 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000283 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
Andy Hungd3595ed2023-12-19 15:34:46 -0800284 auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
285 auto uidPolicy = sp<UidPolicy>::make(this);
286 auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700287 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800288 audio_utils::lock_guard _l(mMutex);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700289 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000290 mUidPolicy = uidPolicy;
291 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700292 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000293 uidPolicy->registerSelf();
294 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200295
Eric Laurent81dd0f52021-07-05 11:54:40 +0200296 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200297 if (mAudioPolicyManager != nullptr) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800298 audio_utils::lock_guard _l(mMutex);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200299 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
300 AudioDeviceTypeAddrVector devices;
301 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
302 if (hasSpatializer) {
Andy Hung1040da52023-12-06 20:59:06 -0800303 // Unlock as Spatializer::create() will use the callback and acquire the
304 // AudioPolicyService_Mutex.
Andy Hung79eacdb2023-11-30 19:34:24 -0800305 mMutex.unlock();
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000306 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Andy Hung79eacdb2023-11-30 19:34:24 -0800307 mMutex.lock();
Eric Laurent52b0bd52021-09-27 15:25:40 +0200308 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700309 if (mSpatializer == nullptr) {
310 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
311 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
312 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
313 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200314 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200315 AudioSystem::audioPolicyReady();
François Gaffie163ce832023-06-28 11:36:35 +0200316 // AudioFlinger will handle effect creation and register these effects on audio_policy
317 // service. Hence, audio_policy service must be ready.
318 audioPolicyEffects->setDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319}
320
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530321void AudioPolicyService::unloadAudioPolicyManager()
322{
323 ALOGV("%s ", __func__);
324 if (mLibraryHandle != nullptr) {
325 dlclose(mLibraryHandle);
326 }
327 mLibraryHandle = nullptr;
328 mCreateAudioPolicyManager = nullptr;
329 mDestroyAudioPolicyManager = nullptr;
330}
331
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332AudioPolicyService::~AudioPolicyService()
333{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700334 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700335 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700336
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530337 mDestroyAudioPolicyManager(mAudioPolicyManager);
338 unloadAudioPolicyManager();
339
Eric Laurentdce54a12014-03-10 12:19:46 -0700340 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700341
342 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800343 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800344
345 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800346 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000347
348 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800349 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700350}
351
352// A notification client is always registered by AudioSystem when the client process
353// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800354Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700355{
Eric Laurent12590252015-08-21 18:40:20 -0700356 if (client == 0) {
357 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800358 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700359 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800360 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700361
362 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800363 pid_t pid = IPCThreadState::self()->getCallingPid();
364 int64_t token = ((int64_t)uid<<32) | pid;
365
366 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700367 sp<NotificationClient> notificationClient = new NotificationClient(this,
368 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800369 uid,
370 pid);
371 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700372
luochaojiang908c7d72018-06-21 14:58:04 +0800373 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700374
Marco Nelissenf8880202014-11-14 07:58:25 -0800375 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700376 binder->linkToDeath(notificationClient);
377 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800378 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700379}
380
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800381Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700382{
Andy Hung79eacdb2023-11-30 19:34:24 -0800383 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurente8726fe2015-06-26 09:39:24 -0700384
385 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800386 pid_t pid = IPCThreadState::self()->getCallingPid();
387 int64_t token = ((int64_t)uid<<32) | pid;
388
389 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800390 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700391 }
luochaojiang908c7d72018-06-21 14:58:04 +0800392 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800393 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700394}
395
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800396Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100397{
Andy Hung79eacdb2023-11-30 19:34:24 -0800398 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100399
400 uid_t uid = IPCThreadState::self()->getCallingUid();
401 pid_t pid = IPCThreadState::self()->getCallingPid();
402 int64_t token = ((int64_t)uid<<32) | pid;
403
404 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800405 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100406 }
407 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800408 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100409}
410
Eric Laurentb52c1522014-05-20 11:27:36 -0700411// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800412void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700413{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000414 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800415 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800416 audio_utils::lock_guard _l(mNotificationClientsMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800417 int64_t token = ((int64_t)uid<<32) | pid;
418 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800419 for (size_t i = 0; i < mNotificationClients.size(); i++) {
420 if (mNotificationClients.valueAt(i)->uid() == uid) {
421 hasSameUid = true;
422 break;
423 }
424 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000425 }
426 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800427 audio_utils::lock_guard _l(mMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800428 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700429 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700430 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700431 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800432 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700433}
434
435void AudioPolicyService::onAudioPortListUpdate()
436{
437 mOutputCommandThread->updateAudioPortListCommand();
438}
439
440void AudioPolicyService::doOnAudioPortListUpdate()
441{
Andy Hung79eacdb2023-11-30 19:34:24 -0800442 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700443 for (size_t i = 0; i < mNotificationClients.size(); i++) {
444 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
445 }
446}
447
448void AudioPolicyService::onAudioPatchListUpdate()
449{
450 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451}
452
Eric Laurentb52c1522014-05-20 11:27:36 -0700453void AudioPolicyService::doOnAudioPatchListUpdate()
454{
Andy Hung79eacdb2023-11-30 19:34:24 -0800455 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700456 for (size_t i = 0; i < mNotificationClients.size(); i++) {
457 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
458 }
459}
460
François Gaffiecfe17322018-11-07 13:41:29 +0100461void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
462{
463 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
464}
465
466void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
467{
Andy Hung79eacdb2023-11-30 19:34:24 -0800468 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100469 for (size_t i = 0; i < mNotificationClients.size(); i++) {
470 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
471 }
472}
473
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700474void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700475{
476 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000477 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700478 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
479}
480
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700481void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700482{
Andy Hung79eacdb2023-11-30 19:34:24 -0800483 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700484 for (size_t i = 0; i < mNotificationClients.size(); i++) {
485 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
486 }
487}
488
Eric Laurenta9f86652018-11-28 17:23:11 -0800489void AudioPolicyService::onRecordingConfigurationUpdate(
490 int event,
491 const record_client_info_t *clientInfo,
492 const audio_config_base_t *clientConfig,
493 std::vector<effect_descriptor_t> clientEffects,
494 const audio_config_base_t *deviceConfig,
495 std::vector<effect_descriptor_t> effects,
496 audio_patch_handle_t patchHandle,
497 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800498{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800499 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800500 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800501}
502
Eric Laurenta9f86652018-11-28 17:23:11 -0800503void AudioPolicyService::doOnRecordingConfigurationUpdate(
504 int event,
505 const record_client_info_t *clientInfo,
506 const audio_config_base_t *clientConfig,
507 std::vector<effect_descriptor_t> clientEffects,
508 const audio_config_base_t *deviceConfig,
509 std::vector<effect_descriptor_t> effects,
510 audio_patch_handle_t patchHandle,
511 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800512{
Andy Hung79eacdb2023-11-30 19:34:24 -0800513 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800514 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800515 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800516 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800517 }
518}
519
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700520void AudioPolicyService::onRoutingUpdated()
521{
522 mOutputCommandThread->routingChangedCommand();
523}
524
525void AudioPolicyService::doOnRoutingUpdated()
526{
Andy Hung79eacdb2023-11-30 19:34:24 -0800527 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700528 for (size_t i = 0; i < mNotificationClients.size(); i++) {
529 mNotificationClients.valueAt(i)->onRoutingUpdated();
530 }
531}
532
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000533void AudioPolicyService::onVolumeRangeInitRequest()
534{
535 mOutputCommandThread->volRangeInitReqCommand();
536}
537
538void AudioPolicyService::doOnVolumeRangeInitRequest()
539{
Andy Hung79eacdb2023-11-30 19:34:24 -0800540 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000541 for (size_t i = 0; i < mNotificationClients.size(); i++) {
542 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
543 }
544}
545
Eric Laurent81dd0f52021-07-05 11:54:40 +0200546void AudioPolicyService::onCheckSpatializer()
547{
Andy Hung79eacdb2023-11-30 19:34:24 -0800548 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200549 onCheckSpatializer_l();
550}
551
552void AudioPolicyService::onCheckSpatializer_l()
553{
554 if (mSpatializer != nullptr) {
555 mOutputCommandThread->checkSpatializerCommand();
556 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200557}
558
559void AudioPolicyService::doOnCheckSpatializer()
560{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200561 ALOGV("%s mSpatializer %p level %d",
562 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200563
Eric Laurent39095982021-08-24 18:29:27 +0200564 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200565 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000566 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200567 audio_io_handle_t currentOutput = mSpatializer->getOutput();
568 audio_io_handle_t newOutput;
569 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
570 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200571
Andy Hung79eacdb2023-11-30 19:34:24 -0800572 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200573 status_t status =
574 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100575 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
576 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200577 if (status == NO_ERROR && currentOutput == newOutput) {
578 return;
579 }
Eric Laurent15903592022-02-24 20:44:36 +0100580 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Andy Hung79eacdb2023-11-30 19:34:24 -0800581 mMutex.unlock();
Eric Laurent39095982021-08-24 18:29:27 +0200582 // It is OK to call detachOutput() is none is already attached.
583 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200584 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
585 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200586 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800587 mMutex.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200588 if (status != NO_ERROR) {
589 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
590 }
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000591 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
592 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200593 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200594
Eric Laurent39095982021-08-24 18:29:27 +0200595 if (output != AUDIO_IO_HANDLE_NONE) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800596 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200597 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200598 }
599 }
600 }
601}
602
Eric Laurent11094172022-04-05 18:27:42 +0200603size_t AudioPolicyService::countActiveClientsOnOutput_l(
604 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100605 size_t count = 0;
606 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
607 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200608 if (client->io == output && client->active
609 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100610 count++;
611 }
612 }
613 return count;
614}
615
616void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
617 if (mSpatializer == nullptr) {
618 return;
619 }
620 mOutputCommandThread->updateActiveSpatializerTracksCommand();
621}
622
623void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
624{
Eric Laurent21270b62022-07-04 15:11:29 +0200625 if (mSpatializer == nullptr) {
626 return;
627 }
628 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200629 size_t activeClients;
630 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800631 audio_utils::lock_guard _l(mMutex);
Eric Laurent21270b62022-07-04 15:11:29 +0200632 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100633 }
Eric Laurent21270b62022-07-04 15:11:29 +0200634 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100635}
636
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800637status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
638 audio_patch_handle_t *handle,
639 int delayMs)
640{
641 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
642}
643
644status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
645 int delayMs)
646{
647 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
648}
649
Eric Laurente1715a42014-05-20 11:30:42 -0700650status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
651 int delayMs)
652{
653 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
654}
655
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800656AudioPolicyService::NotificationClient::NotificationClient(
657 const sp<AudioPolicyService>& service,
658 const sp<media::IAudioPolicyServiceClient>& client,
659 uid_t uid,
660 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800661 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100662 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700663{
664}
665
666AudioPolicyService::NotificationClient::~NotificationClient()
667{
668}
669
670void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
671{
672 sp<NotificationClient> keep(this);
673 sp<AudioPolicyService> service = mService.promote();
674 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800675 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700676 }
677}
678
679void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
680{
Eric Laurente8726fe2015-06-26 09:39:24 -0700681 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700682 mAudioPolicyServiceClient->onAudioPortListUpdate();
683 }
684}
685
686void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
687{
Eric Laurente8726fe2015-06-26 09:39:24 -0700688 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700689 mAudioPolicyServiceClient->onAudioPatchListUpdate();
690 }
691}
Eric Laurent57dae992011-07-24 13:36:09 -0700692
Pattydd807582021-11-04 21:01:03 +0800693void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100694 int flags)
695{
696 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
697 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
698 }
699}
700
701
Jean-Michel Trivide801052015-04-14 19:10:14 -0700702void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700703 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700704{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700705 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800706 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
707 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800708 }
709}
710
711void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800712 int event,
713 const record_client_info_t *clientInfo,
714 const audio_config_base_t *clientConfig,
715 std::vector<effect_descriptor_t> clientEffects,
716 const audio_config_base_t *deviceConfig,
717 std::vector<effect_descriptor_t> effects,
718 audio_patch_handle_t patchHandle,
719 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800720{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700721 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800722 status_t status = [&]() -> status_t {
723 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
724 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
725 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700726 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700727 legacy2aidl_audio_config_base_t_AudioConfigBase(
728 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800729 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
730 convertContainer<std::vector<media::EffectDescriptor>>(
731 clientEffects,
732 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700733 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700734 legacy2aidl_audio_config_base_t_AudioConfigBase(
735 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800736 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
737 convertContainer<std::vector<media::EffectDescriptor>>(
738 effects,
739 legacy2aidl_effect_descriptor_t_EffectDescriptor));
740 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
741 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700742 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
743 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800744 return aidl_utils::statusTFromBinderStatus(
745 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
746 clientInfoAidl,
747 clientConfigAidl,
748 clientEffectsAidl,
749 deviceConfigAidl,
750 effectsAidl,
751 patchHandleAidl,
752 sourceAidl));
753 }();
754 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700755 }
756}
757
Eric Laurente8726fe2015-06-26 09:39:24 -0700758void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
759{
760 mAudioPortCallbacksEnabled = enabled;
761}
762
François Gaffiecfe17322018-11-07 13:41:29 +0100763void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
764{
765 mAudioVolumeGroupCallbacksEnabled = enabled;
766}
Eric Laurente8726fe2015-06-26 09:39:24 -0700767
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700768void AudioPolicyService::NotificationClient::onRoutingUpdated()
769{
770 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
771 mAudioPolicyServiceClient->onRoutingUpdated();
772 }
773}
774
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000775void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
776{
777 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
778 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
779 }
780}
781
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700783 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700784 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785}
786
Andy Hung79eacdb2023-11-30 19:34:24 -0800787static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
788 RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000789{
790 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791}
792
793status_t AudioPolicyService::dumpInternals(int fd)
794{
795 const size_t SIZE = 256;
796 char buffer[SIZE];
797 String8 result;
798
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000799 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800800 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000801 std::stringstream msg;
802 size_t i = 0;
803 for (auto usage : mSupportedSystemUsages) {
804 if (i++ != 0) msg << ", ";
805 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
806 msg << strUsage;
807 } else {
808 msg << usage << " (unknown)";
809 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800810 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000811 if (i == 0) {
812 msg << "None";
813 }
814 msg << std::endl;
815 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800816
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000817 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800818
819 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 return NO_ERROR;
821}
822
Eric Laurente8c8b432018-10-17 10:08:02 -0700823void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800824{
Andy Hung79eacdb2023-11-30 19:34:24 -0800825 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -0700826 updateUidStates_l();
827}
828
829void AudioPolicyService::updateUidStates_l()
830{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800831// Go over all active clients and allow capture (does not force silence) in the
832// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800833// The client is in the active assistant list
834// AND is TOP
835// AND an accessibility service is TOP
836// AND source is either VOICE_RECOGNITION OR HOTWORD
837// OR there is no active privacy sensitive capture or call
838// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
839// AND source is VOICE_RECOGNITION OR HOTWORD
840// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800841// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700842// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800843// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800844// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800845// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
846// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800847// OR The client is an accessibility service
848// AND Is on TOP
849// AND the source is VOICE_RECOGNITION or HOTWORD
850// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700851// AND there is no active privacy sensitive capture or call
852// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800853// AND is on TOP
854// AND the source is VOICE_RECOGNITION or HOTWORD
855// OR the client source is virtual (remote submix, call audio TX or RX...)
856// OR the client source is HOTWORD
857// AND is on TOP
858// OR all active clients are using HOTWORD source
859// AND no call is active
860// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
861// OR the client is the current InputMethodService
862// AND a RTT call is active AND the source is VOICE_RECOGNITION
863// OR Any client
864// AND The assistant is not on TOP
865// AND is on TOP or latest started
866// AND there is no active privacy sensitive capture or call
867// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800868
Eric Laurent4e947da2019-10-17 15:24:06 -0700869
Eric Laurent4eb58f12018-12-07 16:41:02 -0800870 sp<AudioRecordClient> topActive;
871 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800872 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700873 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800874 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700875
Eric Laurenta46bedb2018-12-07 18:01:26 -0800876 nsecs_t topStartNs = 0;
877 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800878 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800879 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800880 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800881 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
882 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800883 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800884 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700885 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800886 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
887 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700888 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700889 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700890 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800891
Michael Groovercfd28302018-12-11 19:16:46 -0800892 // if Sensor Privacy is enabled then all recordings should be silenced.
893 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
894 silenceAllRecordings_l();
895 return;
896 }
897
Eric Laurente8c8b432018-10-17 10:08:02 -0700898 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
899 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000900 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
901 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800902 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700903 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800904 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700905
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700906 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700907 // clients which app is in IDLE state are not eligible for top active or
908 // latest active
909 if (appState == APP_STATE_IDLE) {
910 continue;
911 }
912
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700913 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700914 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800915 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700916 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700917 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800918 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800919 bool isPrivacySensitive =
920 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700921
Eric Laurentc21d5692020-02-25 10:24:36 -0800922 if (appState == APP_STATE_TOP) {
923 if (isPrivacySensitive) {
924 if (current->startTimeNs > topSensitiveStartNs) {
925 topSensitiveActive = current;
926 topSensitiveStartNs = current->startTimeNs;
927 }
928 } else {
929 if (current->startTimeNs > topStartNs) {
930 topActive = current;
931 topStartNs = current->startTimeNs;
932 }
933 }
934 if (isAssistant) {
935 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800936 if (isActiveAssistant) {
937 useActiveAssistantList = true;
938 } else if (!useActiveAssistantList) {
939 if (current->startTimeNs > latestAssistantStartNs) {
940 latestActiveAssistant = current;
941 latestAssistantStartNs = current->startTimeNs;
942 }
943 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800944 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800945 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800946 // Clients capturing for HOTWORD are not considered
947 // for latest active to avoid masking regular clients started before
948 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
949 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
950 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700951 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
952 // is marked latest sensitive active even if another app qualifies.
953 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700954 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700955 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700956 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000957 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700958 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700959 latestSensitiveActiveOrComm = current;
960 latestSensitiveStartNs = current->startTimeNs;
961 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800962 }
963 isSensitiveActive = true;
964 } else {
965 if (current->startTimeNs > latestStartNs) {
966 latestActive = current;
967 latestStartNs = current->startTimeNs;
968 }
969 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800970 }
971 }
François Gaffiedb1a4412023-10-10 17:32:33 +0000972 if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
973 !isVirtualSource(current->attributes.source)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700974 onlyHotwordActive = false;
975 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100976 if (currentUid == mPhoneStateOwnerUid &&
977 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700978 isPhoneStateOwnerActive = true;
979 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800980 }
981
Eric Laurent1ff16a72019-03-14 18:35:04 -0700982 // if no active client with UI on Top, consider latest active as top
983 if (topActive == nullptr) {
984 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800985 topStartNs = latestStartNs;
986 }
987 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700988 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800989 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700990 } else if (latestSensitiveActiveOrComm != nullptr) {
991 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
992 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700993 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000994 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700995 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700996 topSensitiveActive = latestSensitiveActiveOrComm;
997 topSensitiveStartNs = latestSensitiveStartNs;
998 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800999 }
1000
1001 // If both privacy sensitive and regular capture are active:
1002 // if the regular capture is privileged
1003 // allow concurrency
1004 // else
1005 // favor the privacy sensitive case
1006 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001007 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001008 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001009 }
1010
1011 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1012 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001013 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001014 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001015 if (!current->active) {
1016 continue;
1017 }
1018
Eric Laurent4eb58f12018-12-07 16:41:02 -08001019 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001020 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001021 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001022 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001023 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001024 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1025 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001026
Andy Hung79eacdb2023-11-30 19:34:24 -08001027 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mMutex) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001028 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001029 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001030 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001031 bool canCaptureCommunication = recordClient->canCaptureOutput
1032 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001033 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001034 return !(isInCall && !canCaptureCall)
1035 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001036 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001037
1038 // By default allow capture if:
1039 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001040 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001041 // AND there is no active privacy sensitive capture or call
1042 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001043 bool allowSensitiveCapture =
1044 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001045 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001046 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001047 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001048 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001049
Eric Laurented726cc2021-07-01 14:26:41 +02001050 if (!current->hasOp()) {
1051 // Never allow capture if app op is denied
1052 allowCapture = false;
1053 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001054 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1055 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001056 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001057 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001058 // Active assistant list is not being used
1059 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001060 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001061 // OR there is no active privacy sensitive capture or call
1062 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1063 // AND is latest TOP assistant AND
1064 // uses VOICE_RECOGNITION OR uses HOTWORD
1065 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001066 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001067 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001068 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001069 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001070 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001071 && canCaptureIfInCallOrCommunication(current)) {
1072 if (isTopOrLatestAssistant
1073 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1074 || source == AUDIO_SOURCE_HOTWORD)) {
1075 allowCapture = true;
1076 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1077 allowCapture = true;
1078 }
1079 }
1080 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1081 // For assistant on active list and on top allow capture if:
1082 // An accessibility service is on TOP
1083 // AND the source is VOICE_RECOGNITION or HOTWORD
1084 // OR there is no active privacy sensitive capture or call
1085 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1086 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1087 if (isA11yOnTop) {
1088 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1089 allowCapture = true;
1090 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001091 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001092 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001093 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1094 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001095 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001096 }
1097 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001098 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001099 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001100 // The assistant is not on TOP
1101 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001102 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001103 // OR
1104 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1105 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001106 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001107 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001108 allowCapture = true;
1109 }
Eric Laurent589171c2019-07-25 18:04:29 -07001110 if (isA11yOnTop) {
1111 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1112 allowCapture = true;
1113 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001114 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001115 } else if (source == AUDIO_SOURCE_HOTWORD) {
1116 // For HOTWORD source allow capture when not on TOP if:
1117 // All active clients are using HOTWORD source
1118 // AND no call is active
1119 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001120 if (onlyHotwordActive
1121 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001122 allowCapture = true;
1123 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001124 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001125 // For current InputMethodService allow capture if:
1126 // A RTT call is active AND the source is VOICE_RECOGNITION
1127 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1128 allowCapture = true;
1129 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001130 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001131 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001132 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001133 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001134 }
1135}
1136
Michael Groovercfd28302018-12-11 19:16:46 -08001137void AudioPolicyService::silenceAllRecordings_l() {
1138 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1139 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001140 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001141 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001142 }
Michael Groovercfd28302018-12-11 19:16:46 -08001143 }
1144}
1145
Eric Laurente8c8b432018-10-17 10:08:02 -07001146/* static */
1147app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001148
1149 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001150 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001151 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1152 // include persistent services
1153 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001154 }
1155 return APP_STATE_FOREGROUND;
1156}
1157
Eric Laurent4eb58f12018-12-07 16:41:02 -08001158/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001159bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001160{
1161 switch (source) {
1162 case AUDIO_SOURCE_VOICE_UPLINK:
1163 case AUDIO_SOURCE_VOICE_DOWNLINK:
1164 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001165 case AUDIO_SOURCE_REMOTE_SUBMIX:
1166 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001167 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001168 return true;
1169 default:
1170 break;
1171 }
1172 return false;
1173}
1174
Eric Laurent8c7ef892021-06-10 13:32:16 +02001175void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001176{
1177 AutoCallerClear acc;
1178
1179 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001180 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001181 }
1182 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1183 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001184 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001185 if (client->silenced != silenced) {
1186 if (client->active) {
1187 if (silenced) {
1188 finishRecording(client->attributionSource, client->attributes.source);
1189 } else {
1190 std::stringstream msg;
1191 msg << "Audio recording un-silenced on session " << client->session;
1192 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1193 client->attributes.source)) {
1194 silenced = true;
1195 }
1196 }
1197 }
1198 af->setRecordSilenced(client->portId, silenced);
1199 client->silenced = silenced;
1200 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001201 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001202}
1203
Glenn Kasten0f11b512014-01-31 16:18:54 -08001204status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Andy Hung79eacdb2023-11-30 19:34:24 -08001205NO_THREAD_SAFETY_ANALYSIS // update for trylock.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206{
Glenn Kasten44deb052012-02-05 18:09:08 -08001207 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 dumpPermissionDenial(fd);
1209 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001210 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 if (!locked) {
1212 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001213 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 }
1215
1216 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001217
1218 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001219 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001220 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 mAudioCommandThread->dump(fd);
1222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001224 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001225 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001226 if (mOutputCommandThread != 0) {
1227 mOutputCommandThread->dump(fd);
1228 }
1229
Eric Laurentdce54a12014-03-10 12:19:46 -07001230 if (mAudioPolicyManager) {
1231 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001232 } else {
1233 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001234 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236
Kevin Rocard8be94972019-02-22 13:26:25 -08001237 mPackageManager.dump(fd);
1238
Andy Hung79eacdb2023-11-30 19:34:24 -08001239 dumpReleaseLock(mMutex, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001240
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001241 if (mSpatializer != nullptr) {
1242 std::string dumpString = mSpatializer->toString(1 /* level */);
1243 write(fd, dumpString.c_str(), dumpString.size());
1244 } else {
1245 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1246 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1247 }
1248
Andy Hungc747c532022-03-07 21:41:14 -08001249 {
1250 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1251 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1252 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 }
1255 return NO_ERROR;
1256}
1257
1258status_t AudioPolicyService::dumpPermissionDenial(int fd)
1259{
1260 const size_t SIZE = 256;
1261 char buffer[SIZE];
1262 String8 result;
1263 snprintf(buffer, SIZE, "Permission Denial: "
1264 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1265 IPCThreadState::self()->getCallingPid(),
1266 IPCThreadState::self()->getCallingUid());
1267 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001268 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 return NO_ERROR;
1270}
1271
1272status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001273 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001274 // make sure transactions reserved to AudioFlinger do not come from other processes
1275 switch (code) {
1276 case TRANSACTION_startOutput:
1277 case TRANSACTION_stopOutput:
1278 case TRANSACTION_releaseOutput:
1279 case TRANSACTION_getInputForAttr:
1280 case TRANSACTION_startInput:
1281 case TRANSACTION_stopInput:
1282 case TRANSACTION_releaseInput:
1283 case TRANSACTION_getOutputForEffect:
1284 case TRANSACTION_registerEffect:
1285 case TRANSACTION_unregisterEffect:
1286 case TRANSACTION_setEffectEnabled:
1287 case TRANSACTION_getStrategyForStream:
1288 case TRANSACTION_getOutputForAttr:
1289 case TRANSACTION_moveEffectsToIo:
1290 ALOGW("%s: transaction %d received from PID %d",
1291 __func__, code, IPCThreadState::self()->getCallingPid());
1292 return INVALID_OPERATION;
1293 default:
1294 break;
1295 }
1296
1297 // make sure the following transactions come from system components
1298 switch (code) {
1299 case TRANSACTION_setDeviceConnectionState:
1300 case TRANSACTION_handleDeviceConfigChange:
1301 case TRANSACTION_setPhoneState:
1302//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1303// case TRANSACTION_setForceUse:
1304 case TRANSACTION_initStreamVolume:
1305 case TRANSACTION_setStreamVolumeIndex:
1306 case TRANSACTION_setVolumeIndexForAttributes:
1307 case TRANSACTION_getStreamVolumeIndex:
1308 case TRANSACTION_getVolumeIndexForAttributes:
1309 case TRANSACTION_getMinVolumeIndexForAttributes:
1310 case TRANSACTION_getMaxVolumeIndexForAttributes:
1311 case TRANSACTION_isStreamActive:
1312 case TRANSACTION_isStreamActiveRemotely:
1313 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001314 case TRANSACTION_registerPolicyMixes:
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02001315 case TRANSACTION_updatePolicyMixes:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001316 case TRANSACTION_setMasterMono:
1317 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001318 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001319 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001320 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001321 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001322 case TRANSACTION_setA11yServicesUids:
1323 case TRANSACTION_setUidDeviceAffinities:
1324 case TRANSACTION_removeUidDeviceAffinities:
1325 case TRANSACTION_setUserIdDeviceAffinities:
1326 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001327 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001328 case TRANSACTION_listAudioVolumeGroups:
1329 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1330 case TRANSACTION_acquireSoundTriggerSession:
1331 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001332 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001333 case TRANSACTION_setRttEnabled:
1334 case TRANSACTION_isCallScreenModeSupported:
1335 case TRANSACTION_setDevicesRoleForStrategy:
1336 case TRANSACTION_setSupportedSystemUsages:
1337 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001338 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001339 case TRANSACTION_getDevicesForRoleAndStrategy:
1340 case TRANSACTION_getDevicesForAttributes:
1341 case TRANSACTION_setAllowedCapturePolicy:
1342 case TRANSACTION_onNewAudioModulesAvailable:
1343 case TRANSACTION_setCurrentImeUid:
1344 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1345 case TRANSACTION_setDevicesRoleForCapturePreset:
1346 case TRANSACTION_addDevicesRoleForCapturePreset:
1347 case TRANSACTION_removeDevicesRoleForCapturePreset:
1348 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001349 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001350 case TRANSACTION_getSpatializer:
1351 case TRANSACTION_setPreferredMixerAttributes:
Marvin Raminbdefaf02023-11-01 09:10:32 +01001352 case TRANSACTION_clearPreferredMixerAttributes:
1353 case TRANSACTION_getRegisteredPolicyMixes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001354 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1355 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1356 __func__, code, IPCThreadState::self()->getCallingPid(),
1357 IPCThreadState::self()->getCallingUid());
1358 return INVALID_OPERATION;
1359 }
1360 } break;
1361 default:
1362 break;
1363 }
1364
Andy Hungc747c532022-03-07 21:41:14 -08001365 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1366 mediautils::TimeCheck check(
1367 std::string("IAudioPolicyService::").append(methodName),
1368 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1369 if (timeout) {
1370 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1371 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1372 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1373 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1374 .record();
1375 } else {
1376 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1377 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001378 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1379 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1380 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001381
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001382 switch (code) {
1383 case SHELL_COMMAND_TRANSACTION: {
1384 int in = data.readFileDescriptor();
1385 int out = data.readFileDescriptor();
1386 int err = data.readFileDescriptor();
1387 int argc = data.readInt32();
1388 Vector<String16> args;
1389 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1390 args.add(data.readString16());
1391 }
1392 sp<IBinder> unusedCallback;
1393 sp<IResultReceiver> resultReceiver;
1394 status_t status;
1395 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1396 return status;
1397 }
1398 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1399 return status;
1400 }
1401 status = shellCommand(in, out, err, args);
1402 if (resultReceiver != nullptr) {
1403 resultReceiver->send(status);
1404 }
1405 return NO_ERROR;
1406 }
1407 }
1408
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1410}
1411
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001412// ------------------- Shell command implementation -------------------
1413
1414// NOTE: This is a remote API - make sure all args are validated
1415status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1416 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1417 return PERMISSION_DENIED;
1418 }
1419 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1420 return BAD_VALUE;
1421 }
jovanakbe066e12019-09-02 11:54:39 -07001422 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001423 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001424 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001425 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001426 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001427 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001428 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1429 purgePermissionCache();
1430 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001431 } else if (args.size() == 1 && args[0] == String16("help")) {
1432 printHelp(out);
1433 return NO_ERROR;
1434 }
1435 printHelp(err);
1436 return BAD_VALUE;
1437}
1438
jovanakbe066e12019-09-02 11:54:39 -07001439static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1440 if (userId < 0) {
1441 ALOGE("Invalid user: %d", userId);
1442 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001443 return BAD_VALUE;
1444 }
jovanakbe066e12019-09-02 11:54:39 -07001445
1446 PermissionController pc;
1447 uid = pc.getPackageUid(packageName, 0);
1448 if (uid <= 0) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001449 ALOGE("Unknown package: '%s'", String8(packageName).c_str());
1450 dprintf(err, "Unknown package: '%s'\n", String8(packageName).c_str());
jovanakbe066e12019-09-02 11:54:39 -07001451 return BAD_VALUE;
1452 }
1453
1454 uid = multiuser_get_uid(userId, uid);
1455 return NO_ERROR;
1456}
1457
1458status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1459 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1460 if (!(args.size() == 3 || args.size() == 5)) {
1461 printHelp(err);
1462 return BAD_VALUE;
1463 }
1464
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001465 bool active = false;
1466 if (args[2] == String16("active")) {
1467 active = true;
1468 } else if ((args[2] != String16("idle"))) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001469 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).c_str());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001470 return BAD_VALUE;
1471 }
jovanakbe066e12019-09-02 11:54:39 -07001472
1473 int userId = 0;
1474 if (args.size() >= 5 && args[3] == String16("--user")) {
1475 userId = atoi(String8(args[4]));
1476 }
1477
1478 uid_t uid;
1479 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1480 return BAD_VALUE;
1481 }
1482
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001483 sp<UidPolicy> uidPolicy;
1484 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001485 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001486 uidPolicy = mUidPolicy;
1487 }
1488 if (uidPolicy) {
1489 uidPolicy->addOverrideUid(uid, active);
1490 return NO_ERROR;
1491 }
1492 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001493}
1494
1495status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001496 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1497 if (!(args.size() == 2 || args.size() == 4)) {
1498 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001499 return BAD_VALUE;
1500 }
jovanakbe066e12019-09-02 11:54:39 -07001501
1502 int userId = 0;
1503 if (args.size() >= 4 && args[2] == String16("--user")) {
1504 userId = atoi(String8(args[3]));
1505 }
1506
1507 uid_t uid;
1508 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1509 return BAD_VALUE;
1510 }
1511
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001512 sp<UidPolicy> uidPolicy;
1513 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001514 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001515 uidPolicy = mUidPolicy;
1516 }
1517 if (uidPolicy) {
1518 uidPolicy->removeOverrideUid(uid);
1519 return NO_ERROR;
1520 }
1521 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001522}
1523
1524status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001525 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1526 if (!(args.size() == 2 || args.size() == 4)) {
1527 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001528 return BAD_VALUE;
1529 }
jovanakbe066e12019-09-02 11:54:39 -07001530
1531 int userId = 0;
1532 if (args.size() >= 4 && args[2] == String16("--user")) {
1533 userId = atoi(String8(args[3]));
1534 }
1535
1536 uid_t uid;
1537 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1538 return BAD_VALUE;
1539 }
1540
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001541 sp<UidPolicy> uidPolicy;
1542 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001543 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001544 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001545 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001546 if (uidPolicy) {
1547 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1548 }
1549 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001550}
1551
1552status_t AudioPolicyService::printHelp(int out) {
1553 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001554 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1555 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1556 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001557 " help print this message\n");
1558}
1559
Eric Laurent0d13fea2022-11-04 17:12:08 +01001560status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1561 const audio_config_base_t& config,
1562 const audio_output_flags_t flags) {
1563 return mUsecaseValidator->registerStream(output, config, flags);
1564}
1565
1566status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1567 return mUsecaseValidator->unregisterStream(output);
1568}
1569
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001570// ----------- AudioPolicyService::UidPolicy implementation ----------
1571
1572void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001573 status_t res = mAm.linkToDeath(this);
1574 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001575 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001576 | ActivityManager::UID_OBSERVER_ACTIVE
1577 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001578 ActivityManager::PROCESS_STATE_UNKNOWN,
1579 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001580 if (!res) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001581 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001582 mObserverRegistered = true;
1583 } else {
1584 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001585
Steven Moreland2f348142019-07-02 15:59:07 -07001586 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001587 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001588}
1589
1590void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001591 mAm.unlinkToDeath(this);
1592 mAm.unregisterUidObserver(this);
Andy Hung79eacdb2023-11-30 19:34:24 -08001593 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001594 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001595}
1596
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001597void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001598 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001599 mCachedUids.clear();
1600 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001601}
1602
Eric Laurente8c8b432018-10-17 10:08:02 -07001603void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001604 bool needToReregister = false;
1605 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001606 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001607 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001608 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001609 if (needToReregister) {
1610 // Looks like ActivityManager has died previously, attempt to re-register.
1611 registerSelf();
1612 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001613}
1614
1615bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1616 if (isServiceUid(uid)) return true;
1617 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001618 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001619 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001620 auto overrideIter = mOverrideUids.find(uid);
1621 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001622 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001623 }
1624 // In an absense of the ActivityManager, assume everything to be active.
1625 if (!mObserverRegistered) return true;
1626 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001627 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001628 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001629 }
1630 }
1631 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001632 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001633 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001634 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001635 mCachedUids.insert(std::pair<uid_t,
1636 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1637 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001638 }
1639 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001640}
1641
Eric Laurente8c8b432018-10-17 10:08:02 -07001642int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1643 if (isServiceUid(uid)) {
1644 return ActivityManager::PROCESS_STATE_TOP;
1645 }
1646 checkRegistered();
1647 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001648 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001649 auto overrideIter = mOverrideUids.find(uid);
1650 if (overrideIter != mOverrideUids.end()) {
1651 if (overrideIter->second.first) {
1652 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1653 return overrideIter->second.second;
1654 } else {
1655 auto cacheIter = mCachedUids.find(uid);
1656 if (cacheIter != mCachedUids.end()) {
1657 return cacheIter->second.second;
1658 }
1659 }
1660 }
1661 return ActivityManager::PROCESS_STATE_UNKNOWN;
1662 }
1663 // In an absense of the ActivityManager, assume everything to be active.
1664 if (!mObserverRegistered) {
1665 return ActivityManager::PROCESS_STATE_TOP;
1666 }
1667 auto cacheIter = mCachedUids.find(uid);
1668 if (cacheIter != mCachedUids.end()) {
1669 if (cacheIter->second.first) {
1670 return cacheIter->second.second;
1671 } else {
1672 return ActivityManager::PROCESS_STATE_UNKNOWN;
1673 }
1674 }
1675 }
1676 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001677 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001678 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1679 if (active) {
1680 state = am.getUidProcessState(uid, String16("audioserver"));
1681 }
1682 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001683 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001684 mCachedUids.insert(std::pair<uid_t,
1685 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1686 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001687
Eric Laurente8c8b432018-10-17 10:08:02 -07001688 return state;
1689}
1690
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001691void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001692 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001693}
1694
1695void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001696 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001697}
1698
1699void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001700 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001701}
1702
Eric Laurente8c8b432018-10-17 10:08:02 -07001703void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1704 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001705 int64_t procStateSeq __unused,
1706 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001707 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1708 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001709 }
1710}
1711
Austin Borgerdddb7552023-03-30 17:53:01 -07001712void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001713}
1714
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001715void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001716 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1717}
1718
1719void AudioPolicyService::UidPolicy::notifyService() {
1720 sp<AudioPolicyService> service = mService.promote();
1721 if (service != nullptr) {
1722 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001723 }
1724}
1725
Eric Laurente8c8b432018-10-17 10:08:02 -07001726void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1727 std::pair<bool, int>> *uids,
1728 uid_t uid,
1729 bool active,
1730 int state,
1731 bool insert) {
1732 if (isServiceUid(uid)) {
1733 return;
1734 }
1735 bool wasActive = isUidActive(uid);
1736 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001737 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001738 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001739 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001740 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001741 if (wasActive != isUidActive(uid) || state != previousState) {
1742 notifyService();
1743 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001744}
1745
Eric Laurente8c8b432018-10-17 10:08:02 -07001746void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1747 std::pair<bool, int>> *uids,
1748 uid_t uid,
1749 bool active,
1750 int state,
1751 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001752 auto it = uids->find(uid);
1753 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001754 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001755 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1756 it->second.first = active;
1757 }
1758 if (it->second.first) {
1759 it->second.second = state;
1760 } else {
1761 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1762 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001763 } else {
1764 uids->erase(it);
1765 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001766 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1767 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1768 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001769 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001770}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771
Eric Laurent4eb58f12018-12-07 16:41:02 -08001772bool AudioPolicyService::UidPolicy::isA11yOnTop() {
Andy Hung79eacdb2023-11-30 19:34:24 -08001773 audio_utils::lock_guard _l(mMutex);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001774 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001775 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001776 continue;
1777 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001778 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1779 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001780 return true;
1781 }
1782 }
1783 return false;
1784}
1785
Eric Laurentb78763e2018-10-17 10:08:02 -07001786bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1787{
1788 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1789 return it != mA11yUids.end();
1790}
1791
Oscar Azucena829d90d2022-01-28 17:17:56 -08001792void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1793 mAssistantUids.clear();
1794 mAssistantUids = uids;
1795}
1796
1797bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1798{
1799 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1800 return it != mAssistantUids.end();
1801}
1802
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001803void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1804 mActiveAssistantUids = activeUids;
1805}
1806
1807bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1808{
1809 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1810 mActiveAssistantUids.end(), uid);
1811 return it != mActiveAssistantUids.end();
1812}
1813
Oscar Azucena829d90d2022-01-28 17:17:56 -08001814void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1815 const size_t SIZE = 256;
1816 char buffer[SIZE];
1817 String8 result;
1818 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1819 snprintf(buffer, SIZE, "\t%s: \n", title);
1820 result.append(buffer);
1821 int counter = 0;
1822 if (uids.empty()) {
1823 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1824 result.append(buffer);
1825 return;
1826 }
1827 for (const auto &uid : uids) {
1828 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1829 result.append(buffer);
1830 }
1831 };
1832
1833 snprintf(buffer, SIZE, "UID Policy:\n");
1834 result.append(buffer);
1835 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1836 result.append(buffer);
1837
1838 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001839 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001840
1841 appendUidsToResult("Accessibility UIDs", mA11yUids);
1842
1843 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1844 result.append(buffer);
1845
1846 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1847 result.append(buffer);
1848
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001849 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001850}
1851
Michael Groovercfd28302018-12-11 19:16:46 -08001852// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1853void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1854 SensorPrivacyManager spm;
1855 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1856 spm.addSensorPrivacyListener(this);
1857}
1858
1859void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1860 SensorPrivacyManager spm;
1861 spm.removeSensorPrivacyListener(this);
1862}
1863
1864bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1865 return mSensorPrivacyEnabled;
1866}
1867
Evan Seversond8dc6832022-01-27 10:47:03 -08001868binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1869 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001870 mSensorPrivacyEnabled = enabled;
1871 sp<AudioPolicyService> service = mService.promote();
1872 if (service != nullptr) {
1873 service->updateUidStates();
1874 }
1875 return binder::Status::ok();
1876}
1877
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1879
Eric Laurentbfb1b832013-01-07 09:53:42 -08001880AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1881 const wp<AudioPolicyService>& service)
1882 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884}
1885
1886
1887AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1888{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001889 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001890 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 }
1892 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893}
1894
1895void AudioPolicyService::AudioCommandThread::onFirstRef()
1896{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001897 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898}
1899
1900bool AudioPolicyService::AudioCommandThread::threadLoop()
1901{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001902 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903
Andy Hung79eacdb2023-11-30 19:34:24 -08001904 audio_utils::unique_lock ul(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 while (!exitPending())
1906 {
Eric Laurent59a89232014-06-08 14:14:17 -07001907 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001908 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001909 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910 nsecs_t curTime = systemTime();
1911 // commands are sorted by increasing time stamp: execute them from index 0 and up
1912 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001913 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001915 if (mAudioCommands.isEmpty()) {
1916 ++numTimesBecameEmpty;
1917 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001918 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919
1920 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001922 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001923 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001924 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001925 ul.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001926 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1927 data->mVolume,
1928 data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001929 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 }break;
1931 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001932 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001933 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001934 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001935 ul.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001936 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hung79eacdb2023-11-30 19:34:24 -08001937 ul.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001938 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001940 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001941 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001942 data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001943 ul.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001945 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001948 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001949 ALOGV("AudioCommandThread() processing stop output portId %d",
1950 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001951 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 if (svc == 0) {
1953 break;
1954 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001955 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001956 svc->doStopOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001957 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 }break;
1959 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001960 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001961 ALOGV("AudioCommandThread() processing release output portId %d",
1962 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001963 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001964 if (svc == 0) {
1965 break;
1966 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001967 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001968 svc->doReleaseOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001969 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001971 case CREATE_AUDIO_PATCH: {
1972 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1973 ALOGV("AudioCommandThread() processing create audio patch");
1974 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1975 if (af == 0) {
1976 command->mStatus = PERMISSION_DENIED;
1977 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001978 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001979 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001980 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001981 }
1982 } break;
1983 case RELEASE_AUDIO_PATCH: {
1984 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1985 ALOGV("AudioCommandThread() processing release audio patch");
1986 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1987 if (af == 0) {
1988 command->mStatus = PERMISSION_DENIED;
1989 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001990 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001991 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001992 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001993 }
1994 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001995 case UPDATE_AUDIOPORT_LIST: {
1996 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001997 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001998 if (svc == 0) {
1999 break;
2000 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002001 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002002 svc->doOnAudioPortListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08002003 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002004 }break;
2005 case UPDATE_AUDIOPATCH_LIST: {
2006 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07002007 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002008 if (svc == 0) {
2009 break;
2010 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002011 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002012 svc->doOnAudioPatchListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08002013 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002014 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01002015 case CHANGED_AUDIOVOLUMEGROUP: {
2016 AudioVolumeGroupData *data =
2017 static_cast<AudioVolumeGroupData *>(command->mParam.get());
2018 ALOGV("AudioCommandThread() processing update audio volume group");
2019 svc = mService.promote();
2020 if (svc == 0) {
2021 break;
2022 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002023 ul.unlock();
François Gaffiecfe17322018-11-07 13:41:29 +01002024 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
Andy Hung79eacdb2023-11-30 19:34:24 -08002025 ul.lock();
François Gaffiecfe17322018-11-07 13:41:29 +01002026 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07002027 case SET_AUDIOPORT_CONFIG: {
2028 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
2029 ALOGV("AudioCommandThread() processing set port config");
2030 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2031 if (af == 0) {
2032 command->mStatus = PERMISSION_DENIED;
2033 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002034 ul.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07002035 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hung79eacdb2023-11-30 19:34:24 -08002036 ul.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07002037 }
2038 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07002039 case DYN_POLICY_MIX_STATE_UPDATE: {
2040 DynPolicyMixStateUpdateData *data =
2041 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002042 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002043 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002044 svc = mService.promote();
2045 if (svc == 0) {
2046 break;
2047 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002048 ul.unlock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002049 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
Andy Hung79eacdb2023-11-30 19:34:24 -08002050 ul.lock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002051 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002052 case RECORDING_CONFIGURATION_UPDATE: {
2053 RecordingConfigurationUpdateData *data =
2054 (RecordingConfigurationUpdateData *)command->mParam.get();
2055 ALOGV("AudioCommandThread() processing recording configuration update");
2056 svc = mService.promote();
2057 if (svc == 0) {
2058 break;
2059 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002060 ul.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002061 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08002062 &data->mClientConfig, data->mClientEffects,
2063 &data->mDeviceConfig, data->mEffects,
2064 data->mPatchHandle, data->mSource);
Andy Hung79eacdb2023-11-30 19:34:24 -08002065 ul.lock();
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002066 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002067 case SET_EFFECT_SUSPENDED: {
2068 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
2069 ALOGV("AudioCommandThread() processing set effect suspended");
2070 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2071 if (af != 0) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002072 ul.unlock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002073 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
Andy Hung79eacdb2023-11-30 19:34:24 -08002074 ul.lock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002075 }
2076 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002077 case AUDIO_MODULES_UPDATE: {
2078 ALOGV("AudioCommandThread() processing audio modules update");
2079 svc = mService.promote();
2080 if (svc == 0) {
2081 break;
2082 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002083 ul.unlock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002084 svc->doOnNewAudioModulesAvailable();
Andy Hung79eacdb2023-11-30 19:34:24 -08002085 ul.lock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002086 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002087 case ROUTING_UPDATED: {
2088 ALOGV("AudioCommandThread() processing routing update");
2089 svc = mService.promote();
2090 if (svc == 0) {
2091 break;
2092 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002093 ul.unlock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002094 svc->doOnRoutingUpdated();
Andy Hung79eacdb2023-11-30 19:34:24 -08002095 ul.lock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002096 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002097
Eric Laurented726cc2021-07-01 14:26:41 +02002098 case UPDATE_UID_STATES: {
2099 ALOGV("AudioCommandThread() processing updateUID states");
2100 svc = mService.promote();
2101 if (svc == 0) {
2102 break;
2103 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002104 ul.unlock();
Eric Laurented726cc2021-07-01 14:26:41 +02002105 svc->updateUidStates();
Andy Hung79eacdb2023-11-30 19:34:24 -08002106 ul.lock();
Eric Laurented726cc2021-07-01 14:26:41 +02002107 } break;
2108
Eric Laurent15903592022-02-24 20:44:36 +01002109 case CHECK_SPATIALIZER_OUTPUT: {
2110 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002111 svc = mService.promote();
2112 if (svc == 0) {
2113 break;
2114 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002115 ul.unlock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002116 svc->doOnCheckSpatializer();
Andy Hung79eacdb2023-11-30 19:34:24 -08002117 ul.lock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002118 } break;
2119
Eric Laurent15903592022-02-24 20:44:36 +01002120 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2121 ALOGV("AudioCommandThread() processing update spatializer tracks");
2122 svc = mService.promote();
2123 if (svc == 0) {
2124 break;
2125 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002126 ul.unlock();
Eric Laurent15903592022-02-24 20:44:36 +01002127 svc->doOnUpdateActiveSpatializerTracks();
Andy Hung79eacdb2023-11-30 19:34:24 -08002128 ul.lock();
Eric Laurent15903592022-02-24 20:44:36 +01002129 } break;
2130
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002131 case VOL_RANGE_INIT_REQUEST: {
2132 ALOGV("AudioCommandThread() processing volume range init request");
2133 svc = mService.promote();
2134 if (svc == 0) {
2135 break;
2136 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002137 ul.unlock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002138 svc->doOnVolumeRangeInitRequest();
Andy Hung79eacdb2023-11-30 19:34:24 -08002139 ul.lock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002140 } break;
2141
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002143 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002145 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002146 audio_utils::lock_guard _l(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002147 if (command->mWaitStatus) {
2148 command->mWaitStatus = false;
Andy Hung79eacdb2023-11-30 19:34:24 -08002149 command->mCond.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002150 }
2151 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002152 waitTime = -1;
Andy Hung79eacdb2023-11-30 19:34:24 -08002153 // release ul before releasing strong reference on the service as
Zach Janga754b4f2015-10-27 01:29:34 +00002154 // AudioPolicyService destructor calls AudioCommandThread::exit() which
Andy Hung79eacdb2023-11-30 19:34:24 -08002155 // acquires ul.
2156 ul.unlock();
Zach Janga754b4f2015-10-27 01:29:34 +00002157 svc.clear();
Andy Hung79eacdb2023-11-30 19:34:24 -08002158 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 } else {
2160 waitTime = mAudioCommands[0]->mTime - curTime;
2161 break;
2162 }
2163 }
Zach Janga754b4f2015-10-27 01:29:34 +00002164
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002165 // release delayed commands wake lock as many times as we made the queue is
2166 // empty during popping.
2167 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002168 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002169 }
2170
2171 // At this stage we have either an empty command queue or the first command in the queue
2172 // has a finite delay. So unless we are exiting it is safe to wait.
2173 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002174 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002175 if (waitTime == -1) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002176 mWaitWorkCV.wait(ul);
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002177 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002178 // discard return value.
2179 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002180 }
Eric Laurent59a89232014-06-08 14:14:17 -07002181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002183 // release delayed commands wake lock before quitting
2184 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002185 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 return false;
2188}
2189
2190status_t AudioPolicyService::AudioCommandThread::dump(int fd)
Andy Hung79eacdb2023-11-30 19:34:24 -08002191NO_THREAD_SAFETY_ANALYSIS // trylock
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192{
2193 const size_t SIZE = 256;
2194 char buffer[SIZE];
2195 String8 result;
2196
Andy Hung79eacdb2023-11-30 19:34:24 -08002197 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198 if (!locked) {
2199 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002200 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 }
2202
2203 snprintf(buffer, SIZE, "- Commands:\n");
2204 result = String8(buffer);
2205 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002206 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 mAudioCommands[i]->dump(buffer, SIZE);
2208 result.append(buffer);
2209 }
2210 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002211 if (mLastCommand != 0) {
2212 mLastCommand->dump(buffer, SIZE);
2213 result.append(buffer);
2214 } else {
2215 result.append(" none\n");
2216 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002218 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219
Andy Hung79eacdb2023-11-30 19:34:24 -08002220 dumpReleaseLock(mMutex, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221
2222 return NO_ERROR;
2223}
2224
Glenn Kastenfff6d712012-01-12 16:38:12 -08002225status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002226 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002227 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002228 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229{
Eric Laurent0ede8922014-05-09 18:04:42 -07002230 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002232 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 data->mStream = stream;
2234 data->mVolume = volume;
2235 data->mIO = output;
2236 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002237 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002238 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002239 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002240 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241}
2242
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002243status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002244 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002245 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246{
Eric Laurent0ede8922014-05-09 18:04:42 -07002247 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002249 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002251 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002253 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002254 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002255 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002256 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257}
2258
2259status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2260{
Eric Laurent0ede8922014-05-09 18:04:42 -07002261 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002263 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 data->mVolume = volume;
2265 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002266 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002267 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002268 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269}
2270
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002271void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2272 audio_session_t sessionId,
2273 bool suspended)
2274{
2275 sp<AudioCommand> command = new AudioCommand();
2276 command->mCommand = SET_EFFECT_SUSPENDED;
2277 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2278 data->mEffectId = effectId;
2279 data->mSessionId = sessionId;
2280 data->mSuspended = suspended;
2281 command->mParam = data;
2282 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2283 effectId, sessionId, suspended);
2284 sendCommand(command);
2285}
2286
2287
Eric Laurentd7fe0862018-07-14 16:48:01 -07002288void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002289{
Eric Laurent0ede8922014-05-09 18:04:42 -07002290 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002291 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002292 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002293 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002294 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002295 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002296 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297}
2298
Eric Laurentd7fe0862018-07-14 16:48:01 -07002299void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002300{
Eric Laurent0ede8922014-05-09 18:04:42 -07002301 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002302 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002303 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002304 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002305 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002306 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002307 sendCommand(command);
2308}
2309
Eric Laurent951f4552014-05-20 10:48:17 -07002310status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2311 const struct audio_patch *patch,
2312 audio_patch_handle_t *handle,
2313 int delayMs)
2314{
2315 status_t status = NO_ERROR;
2316
2317 sp<AudioCommand> command = new AudioCommand();
2318 command->mCommand = CREATE_AUDIO_PATCH;
2319 CreateAudioPatchData *data = new CreateAudioPatchData();
2320 data->mPatch = *patch;
2321 data->mHandle = *handle;
2322 command->mParam = data;
2323 command->mWaitStatus = true;
2324 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2325 status = sendCommand(command, delayMs);
2326 if (status == NO_ERROR) {
2327 *handle = data->mHandle;
2328 }
2329 return status;
2330}
2331
2332status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2333 int delayMs)
2334{
2335 sp<AudioCommand> command = new AudioCommand();
2336 command->mCommand = RELEASE_AUDIO_PATCH;
2337 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2338 data->mHandle = handle;
2339 command->mParam = data;
2340 command->mWaitStatus = true;
2341 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2342 return sendCommand(command, delayMs);
2343}
2344
Eric Laurentb52c1522014-05-20 11:27:36 -07002345void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2346{
2347 sp<AudioCommand> command = new AudioCommand();
2348 command->mCommand = UPDATE_AUDIOPORT_LIST;
2349 ALOGV("AudioCommandThread() adding update audio port list");
2350 sendCommand(command);
2351}
2352
Eric Laurented726cc2021-07-01 14:26:41 +02002353void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2354{
2355 sp<AudioCommand> command = new AudioCommand();
2356 command->mCommand = UPDATE_UID_STATES;
2357 ALOGV("AudioCommandThread() adding update UID states");
2358 sendCommand(command);
2359}
2360
Eric Laurentb52c1522014-05-20 11:27:36 -07002361void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2362{
2363 sp<AudioCommand>command = new AudioCommand();
2364 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2365 ALOGV("AudioCommandThread() adding update audio patch list");
2366 sendCommand(command);
2367}
2368
François Gaffiecfe17322018-11-07 13:41:29 +01002369void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2370 int flags)
2371{
2372 sp<AudioCommand>command = new AudioCommand();
2373 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2374 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2375 data->mGroup = group;
2376 data->mFlags = flags;
2377 command->mParam = data;
2378 ALOGV("AudioCommandThread() adding audio volume group changed");
2379 sendCommand(command);
2380}
2381
Eric Laurente1715a42014-05-20 11:30:42 -07002382status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2383 const struct audio_port_config *config, int delayMs)
2384{
2385 sp<AudioCommand> command = new AudioCommand();
2386 command->mCommand = SET_AUDIOPORT_CONFIG;
2387 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2388 data->mConfig = *config;
2389 command->mParam = data;
2390 command->mWaitStatus = true;
2391 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2392 return sendCommand(command, delayMs);
2393}
2394
Jean-Michel Trivide801052015-04-14 19:10:14 -07002395void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002396 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002397{
2398 sp<AudioCommand> command = new AudioCommand();
2399 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2400 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2401 data->mRegId = regId;
2402 data->mState = state;
2403 command->mParam = data;
2404 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002405 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002406 sendCommand(command);
2407}
2408
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002409void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002410 int event,
2411 const record_client_info_t *clientInfo,
2412 const audio_config_base_t *clientConfig,
2413 std::vector<effect_descriptor_t> clientEffects,
2414 const audio_config_base_t *deviceConfig,
2415 std::vector<effect_descriptor_t> effects,
2416 audio_patch_handle_t patchHandle,
2417 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002418{
2419 sp<AudioCommand>command = new AudioCommand();
2420 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2421 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2422 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002423 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002424 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002425 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002426 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002427 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002428 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002429 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002430 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002431 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2432 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002433 sendCommand(command);
2434}
2435
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002436void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2437{
2438 sp<AudioCommand> command = new AudioCommand();
2439 command->mCommand = AUDIO_MODULES_UPDATE;
2440 sendCommand(command);
2441}
2442
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002443void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2444{
2445 sp<AudioCommand>command = new AudioCommand();
2446 command->mCommand = ROUTING_UPDATED;
2447 ALOGV("AudioCommandThread() adding routing update");
2448 sendCommand(command);
2449}
2450
Eric Laurent81dd0f52021-07-05 11:54:40 +02002451void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2452{
2453 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002454 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002455 ALOGV("AudioCommandThread() adding check spatializer");
2456 sendCommand(command);
2457}
2458
Eric Laurent15903592022-02-24 20:44:36 +01002459void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2460{
2461 sp<AudioCommand>command = new AudioCommand();
2462 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2463 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2464 sendCommand(command);
2465}
2466
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002467void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2468{
2469 sp<AudioCommand>command = new AudioCommand();
2470 command->mCommand = VOL_RANGE_INIT_REQUEST;
2471 ALOGV("AudioCommandThread() adding volume range init request");
2472 sendCommand(command);
2473}
2474
Eric Laurent0ede8922014-05-09 18:04:42 -07002475status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2476{
2477 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002478 audio_utils::lock_guard _l(mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002479 insertCommand_l(command, delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002480 mWaitWorkCV.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002481 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002482 audio_utils::unique_lock ul(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002483 while (command->mWaitStatus) {
2484 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002485 if (command->mCond.wait_for(
Andy Hung02ea2a02024-01-25 17:02:30 -08002486 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002487 command->mStatus = TIMED_OUT;
2488 command->mWaitStatus = false;
2489 }
2490 }
2491 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492}
2493
Andy Hung79eacdb2023-11-30 19:34:24 -08002494// insertCommand_l() must be called with mMutex held
Eric Laurent0ede8922014-05-09 18:04:42 -07002495void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002497 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002498 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 command->mTime = systemTime() + milliseconds(delayMs);
2500
2501 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002502 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002503 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 }
2505
2506 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002507 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002508 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2510 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002511
2512 // create audio patch or release audio patch commands are equivalent
2513 // with regard to filtering
2514 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2515 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2516 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2517 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2518 continue;
2519 }
2520 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521
2522 switch (command->mCommand) {
2523 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002524 ParametersData *data = (ParametersData *)command->mParam.get();
2525 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002527 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002528 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2530 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2531 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002532 String8 key;
2533 String8 value;
2534 param.getAt(j, key, value);
2535 for (size_t k = 0; k < param2.size(); k++) {
2536 String8 key2;
2537 String8 value2;
2538 param2.getAt(k, key2, value2);
2539 if (key2 == key) {
2540 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002541 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002542 break;
2543 }
2544 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 }
2546 // if all keys have been filtered out, remove the command.
2547 // otherwise, update the key value pairs
2548 if (param2.size() == 0) {
2549 removedCommands.add(command2);
2550 } else {
2551 data2->mKeyValuePairs = param2.toString();
2552 }
Eric Laurent21e54562013-09-23 12:08:05 -07002553 command->mTime = command2->mTime;
2554 // force delayMs to non 0 so that code below does not request to wait for
2555 // command status as the command is now delayed
2556 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 } break;
2558
2559 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002560 VolumeData *data = (VolumeData *)command->mParam.get();
2561 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 if (data->mIO != data2->mIO) break;
2563 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002564 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002565 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002567 command->mTime = command2->mTime;
2568 // force delayMs to non 0 so that code below does not request to wait for
2569 // command status as the command is now delayed
2570 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002572
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002573 case SET_VOICE_VOLUME: {
2574 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2575 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2576 ALOGV("Filtering out voice volume command value %f replaced by %f",
2577 data2->mVolume, data->mVolume);
2578 removedCommands.add(command2);
2579 command->mTime = command2->mTime;
2580 // force delayMs to non 0 so that code below does not request to wait for
2581 // command status as the command is now delayed
2582 delayMs = 1;
2583 } break;
2584
Eric Laurente45b48a2014-09-04 16:40:57 -07002585 case CREATE_AUDIO_PATCH:
2586 case RELEASE_AUDIO_PATCH: {
2587 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002588 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002589 if (command->mCommand == CREATE_AUDIO_PATCH) {
2590 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002591 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002592 } else {
2593 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002594 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002595 }
2596 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002597 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002598 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2599 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002600 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002601 } else {
2602 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002603 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002604 }
2605 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002606 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2607 same output. */
2608 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2609 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2610 bool isOutputDiff = false;
2611 if (patch.num_sources == patch2.num_sources) {
2612 for (unsigned count = 0; count < patch.num_sources; count++) {
2613 if (patch.sources[count].id != patch2.sources[count].id) {
2614 isOutputDiff = true;
2615 break;
2616 }
2617 }
2618 if (isOutputDiff)
2619 break;
2620 }
2621 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002622 ALOGV("Filtering out %s audio patch command for handle %d",
2623 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2624 removedCommands.add(command2);
2625 command->mTime = command2->mTime;
2626 // force delayMs to non 0 so that code below does not request to wait for
2627 // command status as the command is now delayed
2628 delayMs = 1;
2629 } break;
2630
Jean-Michel Trivide801052015-04-14 19:10:14 -07002631 case DYN_POLICY_MIX_STATE_UPDATE: {
2632
2633 } break;
2634
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002635 case RECORDING_CONFIGURATION_UPDATE: {
2636
2637 } break;
2638
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002639 case ROUTING_UPDATED: {
2640
2641 } break;
2642
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002643 case VOL_RANGE_INIT_REQUEST: {
2644 // command may come from different requests, do not filter
2645 } break;
2646
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 default:
2648 break;
2649 }
2650 }
2651
2652 // remove filtered commands
2653 for (size_t j = 0; j < removedCommands.size(); j++) {
2654 // removed commands always have time stamps greater than current command
2655 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002656 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002657 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658 mAudioCommands.removeAt(k);
2659 break;
2660 }
2661 }
2662 }
2663 removedCommands.clear();
2664
Eric Laurentaa79bef2015-01-15 14:33:51 -08002665 // Disable wait for status if delay is not 0.
2666 // Except for create audio patch command because the returned patch handle
2667 // is needed by audio policy manager
2668 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002669 command->mWaitStatus = false;
2670 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002671
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002673 ALOGV("inserting command: %d at index %zd, num commands %zu",
2674 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 mAudioCommands.insertAt(command, i + 1);
2676}
2677
2678void AudioPolicyService::AudioCommandThread::exit()
2679{
Steve Block3856b092011-10-20 11:56:00 +01002680 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002682 audio_utils::lock_guard _l(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 requestExit();
Andy Hung79eacdb2023-11-30 19:34:24 -08002684 mWaitWorkCV.notify_one();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 }
Zach Janga754b4f2015-10-27 01:29:34 +00002686 // Note that we can call it from the thread loop if all other references have been released
2687 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 requestExitAndWait();
2689}
2690
2691void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2692{
2693 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2694 mCommand,
2695 (int)ns2s(mTime),
2696 (int)ns2ms(mTime)%1000,
2697 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002698 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699}
2700
Dima Zavinfce7a472011-04-19 22:30:36 -07002701/******* helpers for the service_ops callbacks defined below *********/
2702void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2703 const char *keyValuePairs,
2704 int delayMs)
2705{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002706 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002707 delayMs);
2708}
2709
2710int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2711 float volume,
2712 audio_io_handle_t output,
2713 int delayMs)
2714{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002715 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002716 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002717}
2718
Dima Zavinfce7a472011-04-19 22:30:36 -07002719int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2720{
2721 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2722}
2723
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002724void AudioPolicyService::setEffectSuspended(int effectId,
2725 audio_session_t sessionId,
2726 bool suspended)
2727{
2728 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2729}
2730
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002731Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002732{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002733 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002734 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002735}
2736
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002737
Dima Zavinfce7a472011-04-19 22:30:36 -07002738extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002739audio_module_handle_t aps_load_hw_module(void *service __unused,
2740 const char *name);
2741audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002742 audio_devices_t *pDevices,
2743 uint32_t *pSamplingRate,
2744 audio_format_t *pFormat,
2745 audio_channel_mask_t *pChannelMask,
2746 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002747 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002748
Eric Laurent2d388ec2014-03-07 13:25:54 -08002749audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002750 audio_module_handle_t module,
2751 audio_devices_t *pDevices,
2752 uint32_t *pSamplingRate,
2753 audio_format_t *pFormat,
2754 audio_channel_mask_t *pChannelMask,
2755 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002756 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002757 const audio_offload_info_t *offloadInfo);
2758audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002759 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002760 audio_io_handle_t output2);
2761int aps_close_output(void *service __unused, audio_io_handle_t output);
2762int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2763int aps_restore_output(void *service __unused, audio_io_handle_t output);
2764audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002765 audio_devices_t *pDevices,
2766 uint32_t *pSamplingRate,
2767 audio_format_t *pFormat,
2768 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002769 audio_in_acoustics_t acoustics __unused);
2770audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002771 audio_module_handle_t module,
2772 audio_devices_t *pDevices,
2773 uint32_t *pSamplingRate,
2774 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002775 audio_channel_mask_t *pChannelMask);
2776int aps_close_input(void *service __unused, audio_io_handle_t input);
2777int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002778int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002779 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002780 audio_io_handle_t dst_output);
2781char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2782 const char *keys);
2783void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2784 const char *kv_pairs, int delay_ms);
2785int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002786 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002787 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002788int aps_set_voice_volume(void *service, float volume, int delay_ms);
2789};
Dima Zavinfce7a472011-04-19 22:30:36 -07002790
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002791} // namespace android