blob: 1a25ff9052163d8ddfe765dbb2eb5e3fe2a6ef97 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioPolicyService"
18//#define LOG_NDEBUG 0
19
Glenn Kasten153b9fe2013-07-15 11:23:36 -070020#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070021#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070022#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053023#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070024
25#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070026#include <binder/IServiceManager.h>
27#include <utils/Log.h>
28#include <cutils/properties.h>
29#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080030#include <binder/PermissionController.h>
31#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Atneya Nair5b1ed642023-06-23 14:43:37 -070034#include "AudioRecordClient.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080037#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070038#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080039#include <media/AudioParameter.h>
Andy Hungc747c532022-03-07 21:41:14 -080040#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070041#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080042#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080043#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
Dima Zavin64760242011-05-11 14:15:23 -070045#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070046#include <system/audio_policy.h>
Mikhail Naganov68e3f642023-04-28 13:06:32 -070047#include <AudioPolicyConfig.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053048#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080051using binder::Status;
Shunkai Yao49bc61f2023-10-10 19:31:10 +000052using media::audio::common::Spatialization;
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Glenn Kasten8dad0e32012-01-09 08:41:22 -080054static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
55static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053056static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mikhail Naganov959e2d02019-03-28 11:08:19 -070058static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Eric Laurent0ede8922014-05-09 18:04:42 -070060static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010061
Svet Ganovf4ddfef2018-01-16 07:37:58 -080062static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070063
Andy Hungc747c532022-03-07 21:41:14 -080064// Creates an association between Binder code to name for IAudioPolicyService.
65#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
66BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
67BINDER_METHOD_ENTRY(setDeviceConnectionState) \
68BINDER_METHOD_ENTRY(getDeviceConnectionState) \
69BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
70BINDER_METHOD_ENTRY(setPhoneState) \
71BINDER_METHOD_ENTRY(setForceUse) \
72BINDER_METHOD_ENTRY(getForceUse) \
73BINDER_METHOD_ENTRY(getOutput) \
74BINDER_METHOD_ENTRY(getOutputForAttr) \
75BINDER_METHOD_ENTRY(startOutput) \
76BINDER_METHOD_ENTRY(stopOutput) \
77BINDER_METHOD_ENTRY(releaseOutput) \
78BINDER_METHOD_ENTRY(getInputForAttr) \
79BINDER_METHOD_ENTRY(startInput) \
80BINDER_METHOD_ENTRY(stopInput) \
81BINDER_METHOD_ENTRY(releaseInput) \
82BINDER_METHOD_ENTRY(initStreamVolume) \
83BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
84BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
85BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
86BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
87BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
88BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getStrategyForStream) \
90BINDER_METHOD_ENTRY(getDevicesForAttributes) \
91BINDER_METHOD_ENTRY(getOutputForEffect) \
92BINDER_METHOD_ENTRY(registerEffect) \
93BINDER_METHOD_ENTRY(unregisterEffect) \
94BINDER_METHOD_ENTRY(setEffectEnabled) \
95BINDER_METHOD_ENTRY(moveEffectsToIo) \
96BINDER_METHOD_ENTRY(isStreamActive) \
97BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
98BINDER_METHOD_ENTRY(isSourceActive) \
99BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
100BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
101BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
102BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
103BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
104BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
105BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
106BINDER_METHOD_ENTRY(getOffloadSupport) \
107BINDER_METHOD_ENTRY(isDirectOutputSupported) \
108BINDER_METHOD_ENTRY(listAudioPorts) \
109BINDER_METHOD_ENTRY(getAudioPort) \
110BINDER_METHOD_ENTRY(createAudioPatch) \
111BINDER_METHOD_ENTRY(releaseAudioPatch) \
112BINDER_METHOD_ENTRY(listAudioPatches) \
113BINDER_METHOD_ENTRY(setAudioPortConfig) \
114BINDER_METHOD_ENTRY(registerClient) \
115BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
116BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
117BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
118BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
119BINDER_METHOD_ENTRY(getPhoneState) \
120BINDER_METHOD_ENTRY(registerPolicyMixes) \
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +0200121BINDER_METHOD_ENTRY(updatePolicyMixes) \
Andy Hungc747c532022-03-07 21:41:14 -0800122BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
123BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
124BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
125BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
126BINDER_METHOD_ENTRY(startAudioSource) \
127BINDER_METHOD_ENTRY(stopAudioSource) \
128BINDER_METHOD_ENTRY(setMasterMono) \
129BINDER_METHOD_ENTRY(getMasterMono) \
130BINDER_METHOD_ENTRY(getStreamVolumeDB) \
131BINDER_METHOD_ENTRY(getSurroundFormats) \
132BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
133BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
134BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
135BINDER_METHOD_ENTRY(setAssistantServicesUids) \
136BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
137BINDER_METHOD_ENTRY(setA11yServicesUids) \
138BINDER_METHOD_ENTRY(setCurrentImeUid) \
139BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
140BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800141BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800142BINDER_METHOD_ENTRY(listAudioProductStrategies) \
143BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
144BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
145BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
146BINDER_METHOD_ENTRY(setRttEnabled) \
147BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
148BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
149BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000150BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800151BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
152BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
153BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
154BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
155BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
156BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
157BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
158BINDER_METHOD_ENTRY(getSpatializer) \
159BINDER_METHOD_ENTRY(canBeSpatialized) \
160BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000161BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
162BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
163BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
164BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
165BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100166BINDER_METHOD_ENTRY(getRegisteredPolicyMixes) \
167 \
Andy Hungc747c532022-03-07 21:41:14 -0800168// singleton for Binder Method Statistics for IAudioPolicyService
169static auto& getIAudioPolicyServiceStatistics() {
170 using Code = int;
171
172#pragma push_macro("BINDER_METHOD_ENTRY")
173#undef BINDER_METHOD_ENTRY
174#define BINDER_METHOD_ENTRY(ENTRY) \
175 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
176
177 static mediautils::MethodStatistics<Code> methodStatistics{
178 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
179 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
180 };
181#pragma pop_macro("BINDER_METHOD_ENTRY")
182
183 return methodStatistics;
184}
185
Mathias Agopian65ab4712010-07-14 17:59:35 -0700186// ----------------------------------------------------------------------------
187
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530188static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
189{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700190 AudioPolicyManager *apm = nullptr;
191 media::AudioPolicyConfig apmConfig;
192 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
193 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
194 LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
195 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
196 "Only default engine is currently supported with the AIDL HAL");
197 apm = new AudioPolicyManager(config,
198 loadApmEngineLibraryAndCreateEngine(
199 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
200 clientInterface);
201 } else {
202 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
203 apm = new AudioPolicyManager(config,
204 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
205 clientInterface);
206 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530207 status_t status = apm->initialize();
208 if (status != NO_ERROR) {
209 delete apm;
210 apm = nullptr;
211 }
212 return apm;
213}
214
215static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
216{
217 delete interface;
218}
219// ----------------------------------------------------------------------------
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700222 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700223 mAudioPolicyManager(NULL),
224 mAudioPolicyClient(NULL),
225 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530226 mCaptureStateNotifier(false),
227 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100228 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
229 mUsecaseValidator(media::createUsecaseValidator()) {
Andy Hung225aef62022-12-06 16:33:20 -0800230 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Andy Hung58b01b12024-03-26 18:04:29 -0700231 setInheritRt(true);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530232}
233
234void AudioPolicyService::loadAudioPolicyManager()
235{
236 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
237 if (mLibraryHandle != nullptr) {
238 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
239 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
240 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
241 const char *lastError = dlerror();
242 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
243 __func__, lastError != nullptr ? lastError : "no error");
244
245 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
246 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
247 lastError = dlerror();
248 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
249 __func__, lastError != nullptr ? lastError : "no error");
250 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
251 unloadAudioPolicyManager();
252 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
253 }
254 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700255}
256
257void AudioPolicyService::onFirstRef()
258{
Andy Hungd47aca22022-03-15 11:50:51 -0700259 // Log an AudioPolicy "constructor" mediametrics event on first ref.
260 // This records the time it takes to load the audio modules and devices.
261 mediametrics::Defer defer([beginNs = systemTime()] {
262 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
263 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
264 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
265 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700266 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800267 audio_utils::lock_guard _l(mMutex);
Eric Laurent93575202011-01-18 18:39:02 -0800268
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700269 // start audio commands thread
270 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
271 // start output activity command thread
272 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700273
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700274 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530275
276 loadAudioPolicyManager();
277 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700278 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200279
bryant_liuba2b4392014-06-11 16:49:30 +0800280 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000281 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
Andy Hungd3595ed2023-12-19 15:34:46 -0800282 auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
283 auto uidPolicy = sp<UidPolicy>::make(this);
284 auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700285 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800286 audio_utils::lock_guard _l(mMutex);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700287 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000288 mUidPolicy = uidPolicy;
289 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700290 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000291 uidPolicy->registerSelf();
292 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200293
Eric Laurent81dd0f52021-07-05 11:54:40 +0200294 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200295 if (mAudioPolicyManager != nullptr) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800296 audio_utils::lock_guard _l(mMutex);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200297 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
298 AudioDeviceTypeAddrVector devices;
299 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
300 if (hasSpatializer) {
Andy Hung1040da52023-12-06 20:59:06 -0800301 // Unlock as Spatializer::create() will use the callback and acquire the
302 // AudioPolicyService_Mutex.
Andy Hung79eacdb2023-11-30 19:34:24 -0800303 mMutex.unlock();
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000304 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Andy Hung79eacdb2023-11-30 19:34:24 -0800305 mMutex.lock();
Eric Laurent52b0bd52021-09-27 15:25:40 +0200306 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700307 if (mSpatializer == nullptr) {
308 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
309 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
310 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
311 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200312 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200313 AudioSystem::audioPolicyReady();
Andy Hungb08b3752024-01-09 19:05:23 -0800314}
315
316void AudioPolicyService::onAudioSystemReady() {
317 sp<AudioPolicyEffects> audioPolicyEffects;
318 {
319 audio_utils::lock_guard _l(mMutex);
320
321 audioPolicyEffects = mAudioPolicyEffects;
322 }
323 audioPolicyEffects->initDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324}
325
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530326void AudioPolicyService::unloadAudioPolicyManager()
327{
328 ALOGV("%s ", __func__);
329 if (mLibraryHandle != nullptr) {
330 dlclose(mLibraryHandle);
331 }
332 mLibraryHandle = nullptr;
333 mCreateAudioPolicyManager = nullptr;
334 mDestroyAudioPolicyManager = nullptr;
335}
336
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337AudioPolicyService::~AudioPolicyService()
338{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700340 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700341
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530342 mDestroyAudioPolicyManager(mAudioPolicyManager);
343 unloadAudioPolicyManager();
344
Eric Laurentdce54a12014-03-10 12:19:46 -0700345 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700346
347 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800348 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800349
350 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800351 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000352
353 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800354 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700355}
356
357// A notification client is always registered by AudioSystem when the client process
358// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800359Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700360{
Eric Laurent12590252015-08-21 18:40:20 -0700361 if (client == 0) {
362 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800363 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700364 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800365 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700366
367 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800368 pid_t pid = IPCThreadState::self()->getCallingPid();
369 int64_t token = ((int64_t)uid<<32) | pid;
370
371 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700372 sp<NotificationClient> notificationClient = new NotificationClient(this,
373 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800374 uid,
375 pid);
376 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700377
luochaojiang908c7d72018-06-21 14:58:04 +0800378 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700379
Marco Nelissenf8880202014-11-14 07:58:25 -0800380 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700381 binder->linkToDeath(notificationClient);
382 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800383 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700384}
385
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800386Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700387{
Andy Hung79eacdb2023-11-30 19:34:24 -0800388 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurente8726fe2015-06-26 09:39:24 -0700389
390 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800391 pid_t pid = IPCThreadState::self()->getCallingPid();
392 int64_t token = ((int64_t)uid<<32) | pid;
393
394 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800395 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700396 }
luochaojiang908c7d72018-06-21 14:58:04 +0800397 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800398 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700399}
400
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800401Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100402{
Andy Hung79eacdb2023-11-30 19:34:24 -0800403 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100404
405 uid_t uid = IPCThreadState::self()->getCallingUid();
406 pid_t pid = IPCThreadState::self()->getCallingPid();
407 int64_t token = ((int64_t)uid<<32) | pid;
408
409 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800410 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100411 }
412 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800413 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100414}
415
Eric Laurentb52c1522014-05-20 11:27:36 -0700416// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800417void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700418{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000419 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800420 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800421 audio_utils::lock_guard _l(mNotificationClientsMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800422 int64_t token = ((int64_t)uid<<32) | pid;
423 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800424 for (size_t i = 0; i < mNotificationClients.size(); i++) {
425 if (mNotificationClients.valueAt(i)->uid() == uid) {
426 hasSameUid = true;
427 break;
428 }
429 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000430 }
431 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800432 audio_utils::lock_guard _l(mMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800433 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700434 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700435 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700436 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800437 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700438}
439
440void AudioPolicyService::onAudioPortListUpdate()
441{
442 mOutputCommandThread->updateAudioPortListCommand();
443}
444
445void AudioPolicyService::doOnAudioPortListUpdate()
446{
Andy Hung79eacdb2023-11-30 19:34:24 -0800447 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700448 for (size_t i = 0; i < mNotificationClients.size(); i++) {
449 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
450 }
451}
452
453void AudioPolicyService::onAudioPatchListUpdate()
454{
455 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700456}
457
Eric Laurentb52c1522014-05-20 11:27:36 -0700458void AudioPolicyService::doOnAudioPatchListUpdate()
459{
Andy Hung79eacdb2023-11-30 19:34:24 -0800460 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700461 for (size_t i = 0; i < mNotificationClients.size(); i++) {
462 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
463 }
464}
465
François Gaffiecfe17322018-11-07 13:41:29 +0100466void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
467{
468 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
469}
470
471void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
472{
Andy Hung79eacdb2023-11-30 19:34:24 -0800473 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100474 for (size_t i = 0; i < mNotificationClients.size(); i++) {
475 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
476 }
477}
478
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700479void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700480{
481 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000482 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700483 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
484}
485
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700486void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700487{
Andy Hung79eacdb2023-11-30 19:34:24 -0800488 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700489 for (size_t i = 0; i < mNotificationClients.size(); i++) {
490 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
491 }
492}
493
Eric Laurenta9f86652018-11-28 17:23:11 -0800494void AudioPolicyService::onRecordingConfigurationUpdate(
495 int event,
496 const record_client_info_t *clientInfo,
497 const audio_config_base_t *clientConfig,
498 std::vector<effect_descriptor_t> clientEffects,
499 const audio_config_base_t *deviceConfig,
500 std::vector<effect_descriptor_t> effects,
501 audio_patch_handle_t patchHandle,
502 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800503{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800504 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800505 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800506}
507
Eric Laurenta9f86652018-11-28 17:23:11 -0800508void AudioPolicyService::doOnRecordingConfigurationUpdate(
509 int event,
510 const record_client_info_t *clientInfo,
511 const audio_config_base_t *clientConfig,
512 std::vector<effect_descriptor_t> clientEffects,
513 const audio_config_base_t *deviceConfig,
514 std::vector<effect_descriptor_t> effects,
515 audio_patch_handle_t patchHandle,
516 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800517{
Andy Hung79eacdb2023-11-30 19:34:24 -0800518 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800519 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800520 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800521 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800522 }
523}
524
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700525void AudioPolicyService::onRoutingUpdated()
526{
527 mOutputCommandThread->routingChangedCommand();
528}
529
530void AudioPolicyService::doOnRoutingUpdated()
531{
Andy Hung79eacdb2023-11-30 19:34:24 -0800532 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700533 for (size_t i = 0; i < mNotificationClients.size(); i++) {
534 mNotificationClients.valueAt(i)->onRoutingUpdated();
535 }
536}
537
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000538void AudioPolicyService::onVolumeRangeInitRequest()
539{
540 mOutputCommandThread->volRangeInitReqCommand();
541}
542
543void AudioPolicyService::doOnVolumeRangeInitRequest()
544{
Andy Hung79eacdb2023-11-30 19:34:24 -0800545 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000546 for (size_t i = 0; i < mNotificationClients.size(); i++) {
547 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
548 }
549}
550
Eric Laurent81dd0f52021-07-05 11:54:40 +0200551void AudioPolicyService::onCheckSpatializer()
552{
Andy Hung79eacdb2023-11-30 19:34:24 -0800553 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200554 onCheckSpatializer_l();
555}
556
557void AudioPolicyService::onCheckSpatializer_l()
558{
559 if (mSpatializer != nullptr) {
560 mOutputCommandThread->checkSpatializerCommand();
561 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200562}
563
564void AudioPolicyService::doOnCheckSpatializer()
565{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200566 ALOGV("%s mSpatializer %p level %d",
567 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200568
Eric Laurent39095982021-08-24 18:29:27 +0200569 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200570 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000571 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200572 audio_io_handle_t currentOutput = mSpatializer->getOutput();
573 audio_io_handle_t newOutput;
574 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
575 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200576
Andy Hung79eacdb2023-11-30 19:34:24 -0800577 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200578 status_t status =
579 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100580 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
581 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200582 if (status == NO_ERROR && currentOutput == newOutput) {
583 return;
584 }
Eric Laurent15903592022-02-24 20:44:36 +0100585 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Andy Hung79eacdb2023-11-30 19:34:24 -0800586 mMutex.unlock();
Eric Laurent39095982021-08-24 18:29:27 +0200587 // It is OK to call detachOutput() is none is already attached.
588 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200589 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
590 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200591 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800592 mMutex.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200593 if (status != NO_ERROR) {
594 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
595 }
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000596 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
597 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200598 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200599
Eric Laurent39095982021-08-24 18:29:27 +0200600 if (output != AUDIO_IO_HANDLE_NONE) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800601 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200602 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200603 }
604 }
605 }
606}
607
Eric Laurent11094172022-04-05 18:27:42 +0200608size_t AudioPolicyService::countActiveClientsOnOutput_l(
609 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100610 size_t count = 0;
611 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
612 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200613 if (client->io == output && client->active
614 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100615 count++;
616 }
617 }
618 return count;
619}
620
621void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
622 if (mSpatializer == nullptr) {
623 return;
624 }
625 mOutputCommandThread->updateActiveSpatializerTracksCommand();
626}
627
628void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
629{
Eric Laurent21270b62022-07-04 15:11:29 +0200630 if (mSpatializer == nullptr) {
631 return;
632 }
633 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200634 size_t activeClients;
635 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800636 audio_utils::lock_guard _l(mMutex);
Eric Laurent21270b62022-07-04 15:11:29 +0200637 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100638 }
Eric Laurent21270b62022-07-04 15:11:29 +0200639 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100640}
641
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800642status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
643 audio_patch_handle_t *handle,
644 int delayMs)
645{
646 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
647}
648
649status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
650 int delayMs)
651{
652 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
653}
654
Eric Laurente1715a42014-05-20 11:30:42 -0700655status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
656 int delayMs)
657{
658 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
659}
660
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800661AudioPolicyService::NotificationClient::NotificationClient(
662 const sp<AudioPolicyService>& service,
663 const sp<media::IAudioPolicyServiceClient>& client,
664 uid_t uid,
665 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800666 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100667 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700668{
669}
670
671AudioPolicyService::NotificationClient::~NotificationClient()
672{
673}
674
675void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
676{
677 sp<NotificationClient> keep(this);
678 sp<AudioPolicyService> service = mService.promote();
679 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800680 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700681 }
682}
683
684void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
685{
Eric Laurente8726fe2015-06-26 09:39:24 -0700686 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700687 mAudioPolicyServiceClient->onAudioPortListUpdate();
688 }
689}
690
691void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
692{
Eric Laurente8726fe2015-06-26 09:39:24 -0700693 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700694 mAudioPolicyServiceClient->onAudioPatchListUpdate();
695 }
696}
Eric Laurent57dae992011-07-24 13:36:09 -0700697
Pattydd807582021-11-04 21:01:03 +0800698void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100699 int flags)
700{
701 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
702 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
703 }
704}
705
706
Jean-Michel Trivide801052015-04-14 19:10:14 -0700707void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700708 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700709{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700710 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800711 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
712 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800713 }
714}
715
716void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800717 int event,
718 const record_client_info_t *clientInfo,
719 const audio_config_base_t *clientConfig,
720 std::vector<effect_descriptor_t> clientEffects,
721 const audio_config_base_t *deviceConfig,
722 std::vector<effect_descriptor_t> effects,
723 audio_patch_handle_t patchHandle,
724 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800725{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700726 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800727 status_t status = [&]() -> status_t {
728 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
729 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
730 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700731 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700732 legacy2aidl_audio_config_base_t_AudioConfigBase(
733 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800734 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
735 convertContainer<std::vector<media::EffectDescriptor>>(
736 clientEffects,
737 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700738 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700739 legacy2aidl_audio_config_base_t_AudioConfigBase(
740 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800741 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
742 convertContainer<std::vector<media::EffectDescriptor>>(
743 effects,
744 legacy2aidl_effect_descriptor_t_EffectDescriptor));
745 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
746 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700747 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
748 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800749 return aidl_utils::statusTFromBinderStatus(
750 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
751 clientInfoAidl,
752 clientConfigAidl,
753 clientEffectsAidl,
754 deviceConfigAidl,
755 effectsAidl,
756 patchHandleAidl,
757 sourceAidl));
758 }();
759 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700760 }
761}
762
Eric Laurente8726fe2015-06-26 09:39:24 -0700763void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
764{
765 mAudioPortCallbacksEnabled = enabled;
766}
767
François Gaffiecfe17322018-11-07 13:41:29 +0100768void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
769{
770 mAudioVolumeGroupCallbacksEnabled = enabled;
771}
Eric Laurente8726fe2015-06-26 09:39:24 -0700772
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700773void AudioPolicyService::NotificationClient::onRoutingUpdated()
774{
775 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
776 mAudioPolicyServiceClient->onRoutingUpdated();
777 }
778}
779
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000780void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
781{
782 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
783 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
784 }
785}
786
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700788 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700789 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790}
791
Andy Hung79eacdb2023-11-30 19:34:24 -0800792static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
793 RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000794{
795 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796}
797
798status_t AudioPolicyService::dumpInternals(int fd)
799{
800 const size_t SIZE = 256;
801 char buffer[SIZE];
802 String8 result;
803
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000804 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800805 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000806 std::stringstream msg;
807 size_t i = 0;
808 for (auto usage : mSupportedSystemUsages) {
809 if (i++ != 0) msg << ", ";
810 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
811 msg << strUsage;
812 } else {
813 msg << usage << " (unknown)";
814 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800815 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000816 if (i == 0) {
817 msg << "None";
818 }
819 msg << std::endl;
820 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800821
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000822 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800823
824 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 return NO_ERROR;
826}
827
Eric Laurente8c8b432018-10-17 10:08:02 -0700828void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800829{
Andy Hung79eacdb2023-11-30 19:34:24 -0800830 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -0700831 updateUidStates_l();
832}
833
834void AudioPolicyService::updateUidStates_l()
835{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800836// Go over all active clients and allow capture (does not force silence) in the
837// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800838// The client is in the active assistant list
839// AND is TOP
840// AND an accessibility service is TOP
841// AND source is either VOICE_RECOGNITION OR HOTWORD
842// OR there is no active privacy sensitive capture or call
843// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
844// AND source is VOICE_RECOGNITION OR HOTWORD
845// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800846// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700847// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800848// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800849// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800850// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
851// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800852// OR The client is an accessibility service
853// AND Is on TOP
854// AND the source is VOICE_RECOGNITION or HOTWORD
855// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700856// AND there is no active privacy sensitive capture or call
857// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800858// AND is on TOP
859// AND the source is VOICE_RECOGNITION or HOTWORD
860// OR the client source is virtual (remote submix, call audio TX or RX...)
861// OR the client source is HOTWORD
862// AND is on TOP
863// OR all active clients are using HOTWORD source
864// AND no call is active
865// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
866// OR the client is the current InputMethodService
867// AND a RTT call is active AND the source is VOICE_RECOGNITION
868// OR Any client
869// AND The assistant is not on TOP
870// AND is on TOP or latest started
871// AND there is no active privacy sensitive capture or call
872// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800873
Eric Laurent4e947da2019-10-17 15:24:06 -0700874
Eric Laurent4eb58f12018-12-07 16:41:02 -0800875 sp<AudioRecordClient> topActive;
876 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800877 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700878 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800879 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700880
Eric Laurenta46bedb2018-12-07 18:01:26 -0800881 nsecs_t topStartNs = 0;
882 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800883 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800884 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800885 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800886 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
887 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800888 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800889 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700890 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800891 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
892 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700893 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700894 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700895 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800896
Michael Groovercfd28302018-12-11 19:16:46 -0800897 // if Sensor Privacy is enabled then all recordings should be silenced.
898 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
899 silenceAllRecordings_l();
900 return;
901 }
902
Eric Laurente8c8b432018-10-17 10:08:02 -0700903 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
904 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000905 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
906 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800907 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700908 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800909 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700910
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700911 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700912 // clients which app is in IDLE state are not eligible for top active or
913 // latest active
914 if (appState == APP_STATE_IDLE) {
915 continue;
916 }
917
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700918 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700919 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800920 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700921 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700922 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800923 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800924 bool isPrivacySensitive =
925 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700926
Eric Laurentc21d5692020-02-25 10:24:36 -0800927 if (appState == APP_STATE_TOP) {
928 if (isPrivacySensitive) {
929 if (current->startTimeNs > topSensitiveStartNs) {
930 topSensitiveActive = current;
931 topSensitiveStartNs = current->startTimeNs;
932 }
933 } else {
934 if (current->startTimeNs > topStartNs) {
935 topActive = current;
936 topStartNs = current->startTimeNs;
937 }
938 }
939 if (isAssistant) {
940 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800941 if (isActiveAssistant) {
942 useActiveAssistantList = true;
943 } else if (!useActiveAssistantList) {
944 if (current->startTimeNs > latestAssistantStartNs) {
945 latestActiveAssistant = current;
946 latestAssistantStartNs = current->startTimeNs;
947 }
948 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800949 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800950 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800951 // Clients capturing for HOTWORD are not considered
952 // for latest active to avoid masking regular clients started before
953 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
954 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
955 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700956 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
957 // is marked latest sensitive active even if another app qualifies.
958 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700959 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700960 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700961 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000962 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700963 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700964 latestSensitiveActiveOrComm = current;
965 latestSensitiveStartNs = current->startTimeNs;
966 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800967 }
968 isSensitiveActive = true;
969 } else {
970 if (current->startTimeNs > latestStartNs) {
971 latestActive = current;
972 latestStartNs = current->startTimeNs;
973 }
974 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800975 }
976 }
François Gaffiedb1a4412023-10-10 17:32:33 +0000977 if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
978 !isVirtualSource(current->attributes.source)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700979 onlyHotwordActive = false;
980 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100981 if (currentUid == mPhoneStateOwnerUid &&
982 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700983 isPhoneStateOwnerActive = true;
984 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800985 }
986
Eric Laurent1ff16a72019-03-14 18:35:04 -0700987 // if no active client with UI on Top, consider latest active as top
988 if (topActive == nullptr) {
989 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800990 topStartNs = latestStartNs;
991 }
992 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700993 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800994 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700995 } else if (latestSensitiveActiveOrComm != nullptr) {
996 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
997 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700998 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000999 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001000 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -07001001 topSensitiveActive = latestSensitiveActiveOrComm;
1002 topSensitiveStartNs = latestSensitiveStartNs;
1003 }
Eric Laurentc21d5692020-02-25 10:24:36 -08001004 }
1005
1006 // If both privacy sensitive and regular capture are active:
1007 // if the regular capture is privileged
1008 // allow concurrency
1009 // else
1010 // favor the privacy sensitive case
1011 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001012 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001013 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001014 }
1015
1016 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1017 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001018 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001019 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001020 if (!current->active) {
1021 continue;
1022 }
1023
Eric Laurent4eb58f12018-12-07 16:41:02 -08001024 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001025 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001026 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001027 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001028 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001029 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1030 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001031
Andy Hung79eacdb2023-11-30 19:34:24 -08001032 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mMutex) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001033 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001034 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001035 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001036 bool canCaptureCommunication = recordClient->canCaptureOutput
1037 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001038 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001039 return !(isInCall && !canCaptureCall)
1040 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001041 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001042
1043 // By default allow capture if:
1044 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001045 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001046 // AND there is no active privacy sensitive capture or call
1047 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001048 bool allowSensitiveCapture =
1049 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001050 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001051 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001052 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001053 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001054
Eric Laurented726cc2021-07-01 14:26:41 +02001055 if (!current->hasOp()) {
1056 // Never allow capture if app op is denied
1057 allowCapture = false;
1058 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001059 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1060 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001061 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001062 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001063 // Active assistant list is not being used
1064 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001065 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001066 // OR there is no active privacy sensitive capture or call
1067 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1068 // AND is latest TOP assistant AND
1069 // uses VOICE_RECOGNITION OR uses HOTWORD
1070 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001071 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001072 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001073 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001074 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001075 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001076 && canCaptureIfInCallOrCommunication(current)) {
1077 if (isTopOrLatestAssistant
1078 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1079 || source == AUDIO_SOURCE_HOTWORD)) {
1080 allowCapture = true;
1081 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1082 allowCapture = true;
1083 }
1084 }
1085 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1086 // For assistant on active list and on top allow capture if:
1087 // An accessibility service is on TOP
1088 // AND the source is VOICE_RECOGNITION or HOTWORD
1089 // OR there is no active privacy sensitive capture or call
1090 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1091 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1092 if (isA11yOnTop) {
1093 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1094 allowCapture = true;
1095 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001096 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001097 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001098 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1099 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001100 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001101 }
1102 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001103 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001104 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001105 // The assistant is not on TOP
1106 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001107 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001108 // OR
1109 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1110 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001111 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001112 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001113 allowCapture = true;
1114 }
Eric Laurent589171c2019-07-25 18:04:29 -07001115 if (isA11yOnTop) {
1116 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1117 allowCapture = true;
1118 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001119 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001120 } else if (source == AUDIO_SOURCE_HOTWORD) {
1121 // For HOTWORD source allow capture when not on TOP if:
1122 // All active clients are using HOTWORD source
1123 // AND no call is active
1124 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001125 if (onlyHotwordActive
1126 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001127 allowCapture = true;
1128 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001129 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001130 // For current InputMethodService allow capture if:
1131 // A RTT call is active AND the source is VOICE_RECOGNITION
1132 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1133 allowCapture = true;
1134 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001135 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001136 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001137 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001138 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001139 }
1140}
1141
Michael Groovercfd28302018-12-11 19:16:46 -08001142void AudioPolicyService::silenceAllRecordings_l() {
1143 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1144 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001145 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001146 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001147 }
Michael Groovercfd28302018-12-11 19:16:46 -08001148 }
1149}
1150
Eric Laurente8c8b432018-10-17 10:08:02 -07001151/* static */
1152app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001153
1154 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001155 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001156 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1157 // include persistent services
1158 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001159 }
1160 return APP_STATE_FOREGROUND;
1161}
1162
Eric Laurent4eb58f12018-12-07 16:41:02 -08001163/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001164bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001165{
1166 switch (source) {
1167 case AUDIO_SOURCE_VOICE_UPLINK:
1168 case AUDIO_SOURCE_VOICE_DOWNLINK:
1169 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001170 case AUDIO_SOURCE_REMOTE_SUBMIX:
1171 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001172 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001173 return true;
1174 default:
1175 break;
1176 }
1177 return false;
1178}
1179
Eric Laurent8c7ef892021-06-10 13:32:16 +02001180void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001181{
1182 AutoCallerClear acc;
1183
1184 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001185 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001186 }
1187 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1188 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001189 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001190 if (client->silenced != silenced) {
1191 if (client->active) {
1192 if (silenced) {
Marvin Raminb03b49f2024-04-04 16:25:31 +02001193 finishRecording(client->attributionSource, client->virtualDeviceId,
1194 client->attributes.source);
Eric Laurent8c7ef892021-06-10 13:32:16 +02001195 } else {
1196 std::stringstream msg;
1197 msg << "Audio recording un-silenced on session " << client->session;
Marvin Raminb03b49f2024-04-04 16:25:31 +02001198 if (!startRecording(client->attributionSource, client->virtualDeviceId,
1199 String16(msg.str().c_str()), client->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001200 silenced = true;
1201 }
1202 }
1203 }
1204 af->setRecordSilenced(client->portId, silenced);
1205 client->silenced = silenced;
1206 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001207 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001208}
1209
Glenn Kasten0f11b512014-01-31 16:18:54 -08001210status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Andy Hung79eacdb2023-11-30 19:34:24 -08001211NO_THREAD_SAFETY_ANALYSIS // update for trylock.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001212{
Glenn Kasten44deb052012-02-05 18:09:08 -08001213 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 dumpPermissionDenial(fd);
1215 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001216 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 if (!locked) {
1218 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001219 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 }
1221
1222 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001223
1224 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001225 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001226 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 mAudioCommandThread->dump(fd);
1228 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001230 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001231 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001232 if (mOutputCommandThread != 0) {
1233 mOutputCommandThread->dump(fd);
1234 }
1235
Eric Laurentdce54a12014-03-10 12:19:46 -07001236 if (mAudioPolicyManager) {
1237 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001238 } else {
1239 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001240 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242
Kevin Rocard8be94972019-02-22 13:26:25 -08001243 mPackageManager.dump(fd);
1244
Andy Hung79eacdb2023-11-30 19:34:24 -08001245 dumpReleaseLock(mMutex, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001246
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001247 if (mSpatializer != nullptr) {
1248 std::string dumpString = mSpatializer->toString(1 /* level */);
1249 write(fd, dumpString.c_str(), dumpString.size());
1250 } else {
1251 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1252 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1253 }
1254
Andy Hungc747c532022-03-07 21:41:14 -08001255 {
1256 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1257 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1258 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 }
1261 return NO_ERROR;
1262}
1263
1264status_t AudioPolicyService::dumpPermissionDenial(int fd)
1265{
1266 const size_t SIZE = 256;
1267 char buffer[SIZE];
1268 String8 result;
1269 snprintf(buffer, SIZE, "Permission Denial: "
1270 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1271 IPCThreadState::self()->getCallingPid(),
1272 IPCThreadState::self()->getCallingUid());
1273 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001274 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275 return NO_ERROR;
1276}
1277
1278status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001279 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001280 // make sure transactions reserved to AudioFlinger do not come from other processes
1281 switch (code) {
1282 case TRANSACTION_startOutput:
1283 case TRANSACTION_stopOutput:
1284 case TRANSACTION_releaseOutput:
1285 case TRANSACTION_getInputForAttr:
1286 case TRANSACTION_startInput:
1287 case TRANSACTION_stopInput:
1288 case TRANSACTION_releaseInput:
1289 case TRANSACTION_getOutputForEffect:
1290 case TRANSACTION_registerEffect:
1291 case TRANSACTION_unregisterEffect:
1292 case TRANSACTION_setEffectEnabled:
1293 case TRANSACTION_getStrategyForStream:
1294 case TRANSACTION_getOutputForAttr:
1295 case TRANSACTION_moveEffectsToIo:
1296 ALOGW("%s: transaction %d received from PID %d",
1297 __func__, code, IPCThreadState::self()->getCallingPid());
1298 return INVALID_OPERATION;
1299 default:
1300 break;
1301 }
1302
1303 // make sure the following transactions come from system components
1304 switch (code) {
1305 case TRANSACTION_setDeviceConnectionState:
1306 case TRANSACTION_handleDeviceConfigChange:
1307 case TRANSACTION_setPhoneState:
1308//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1309// case TRANSACTION_setForceUse:
1310 case TRANSACTION_initStreamVolume:
1311 case TRANSACTION_setStreamVolumeIndex:
1312 case TRANSACTION_setVolumeIndexForAttributes:
1313 case TRANSACTION_getStreamVolumeIndex:
1314 case TRANSACTION_getVolumeIndexForAttributes:
1315 case TRANSACTION_getMinVolumeIndexForAttributes:
1316 case TRANSACTION_getMaxVolumeIndexForAttributes:
1317 case TRANSACTION_isStreamActive:
1318 case TRANSACTION_isStreamActiveRemotely:
1319 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001320 case TRANSACTION_registerPolicyMixes:
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02001321 case TRANSACTION_updatePolicyMixes:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001322 case TRANSACTION_setMasterMono:
1323 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001324 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001325 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001326 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001327 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001328 case TRANSACTION_setA11yServicesUids:
1329 case TRANSACTION_setUidDeviceAffinities:
1330 case TRANSACTION_removeUidDeviceAffinities:
1331 case TRANSACTION_setUserIdDeviceAffinities:
1332 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001333 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001334 case TRANSACTION_listAudioVolumeGroups:
1335 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1336 case TRANSACTION_acquireSoundTriggerSession:
1337 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001338 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001339 case TRANSACTION_setRttEnabled:
1340 case TRANSACTION_isCallScreenModeSupported:
1341 case TRANSACTION_setDevicesRoleForStrategy:
1342 case TRANSACTION_setSupportedSystemUsages:
1343 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001344 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001345 case TRANSACTION_getDevicesForRoleAndStrategy:
1346 case TRANSACTION_getDevicesForAttributes:
1347 case TRANSACTION_setAllowedCapturePolicy:
1348 case TRANSACTION_onNewAudioModulesAvailable:
1349 case TRANSACTION_setCurrentImeUid:
1350 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1351 case TRANSACTION_setDevicesRoleForCapturePreset:
1352 case TRANSACTION_addDevicesRoleForCapturePreset:
1353 case TRANSACTION_removeDevicesRoleForCapturePreset:
1354 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001355 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001356 case TRANSACTION_getSpatializer:
1357 case TRANSACTION_setPreferredMixerAttributes:
Marvin Raminbdefaf02023-11-01 09:10:32 +01001358 case TRANSACTION_clearPreferredMixerAttributes:
1359 case TRANSACTION_getRegisteredPolicyMixes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001360 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1361 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1362 __func__, code, IPCThreadState::self()->getCallingPid(),
1363 IPCThreadState::self()->getCallingUid());
1364 return INVALID_OPERATION;
1365 }
1366 } break;
1367 default:
1368 break;
1369 }
1370
Andy Hungc747c532022-03-07 21:41:14 -08001371 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1372 mediautils::TimeCheck check(
1373 std::string("IAudioPolicyService::").append(methodName),
1374 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1375 if (timeout) {
1376 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1377 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1378 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1379 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1380 .record();
1381 } else {
1382 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1383 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001384 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1385 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1386 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001387
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001388 switch (code) {
1389 case SHELL_COMMAND_TRANSACTION: {
1390 int in = data.readFileDescriptor();
1391 int out = data.readFileDescriptor();
1392 int err = data.readFileDescriptor();
1393 int argc = data.readInt32();
1394 Vector<String16> args;
1395 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1396 args.add(data.readString16());
1397 }
1398 sp<IBinder> unusedCallback;
1399 sp<IResultReceiver> resultReceiver;
1400 status_t status;
1401 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1402 return status;
1403 }
1404 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1405 return status;
1406 }
1407 status = shellCommand(in, out, err, args);
1408 if (resultReceiver != nullptr) {
1409 resultReceiver->send(status);
1410 }
1411 return NO_ERROR;
1412 }
1413 }
1414
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1416}
1417
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001418// ------------------- Shell command implementation -------------------
1419
1420// NOTE: This is a remote API - make sure all args are validated
1421status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1422 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1423 return PERMISSION_DENIED;
1424 }
1425 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1426 return BAD_VALUE;
1427 }
jovanakbe066e12019-09-02 11:54:39 -07001428 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001429 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001430 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001431 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001432 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001433 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001434 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1435 purgePermissionCache();
1436 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001437 } else if (args.size() == 1 && args[0] == String16("help")) {
1438 printHelp(out);
1439 return NO_ERROR;
1440 }
1441 printHelp(err);
1442 return BAD_VALUE;
1443}
1444
jovanakbe066e12019-09-02 11:54:39 -07001445static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1446 if (userId < 0) {
1447 ALOGE("Invalid user: %d", userId);
1448 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001449 return BAD_VALUE;
1450 }
jovanakbe066e12019-09-02 11:54:39 -07001451
1452 PermissionController pc;
1453 uid = pc.getPackageUid(packageName, 0);
1454 if (uid <= 0) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001455 ALOGE("Unknown package: '%s'", String8(packageName).c_str());
1456 dprintf(err, "Unknown package: '%s'\n", String8(packageName).c_str());
jovanakbe066e12019-09-02 11:54:39 -07001457 return BAD_VALUE;
1458 }
1459
1460 uid = multiuser_get_uid(userId, uid);
1461 return NO_ERROR;
1462}
1463
1464status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1465 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1466 if (!(args.size() == 3 || args.size() == 5)) {
1467 printHelp(err);
1468 return BAD_VALUE;
1469 }
1470
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001471 bool active = false;
1472 if (args[2] == String16("active")) {
1473 active = true;
1474 } else if ((args[2] != String16("idle"))) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001475 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).c_str());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001476 return BAD_VALUE;
1477 }
jovanakbe066e12019-09-02 11:54:39 -07001478
1479 int userId = 0;
1480 if (args.size() >= 5 && args[3] == String16("--user")) {
1481 userId = atoi(String8(args[4]));
1482 }
1483
1484 uid_t uid;
1485 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1486 return BAD_VALUE;
1487 }
1488
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001489 sp<UidPolicy> uidPolicy;
1490 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001491 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001492 uidPolicy = mUidPolicy;
1493 }
1494 if (uidPolicy) {
1495 uidPolicy->addOverrideUid(uid, active);
1496 return NO_ERROR;
1497 }
1498 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001499}
1500
1501status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001502 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1503 if (!(args.size() == 2 || args.size() == 4)) {
1504 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001505 return BAD_VALUE;
1506 }
jovanakbe066e12019-09-02 11:54:39 -07001507
1508 int userId = 0;
1509 if (args.size() >= 4 && args[2] == String16("--user")) {
1510 userId = atoi(String8(args[3]));
1511 }
1512
1513 uid_t uid;
1514 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1515 return BAD_VALUE;
1516 }
1517
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001518 sp<UidPolicy> uidPolicy;
1519 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001520 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001521 uidPolicy = mUidPolicy;
1522 }
1523 if (uidPolicy) {
1524 uidPolicy->removeOverrideUid(uid);
1525 return NO_ERROR;
1526 }
1527 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001528}
1529
1530status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001531 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1532 if (!(args.size() == 2 || args.size() == 4)) {
1533 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001534 return BAD_VALUE;
1535 }
jovanakbe066e12019-09-02 11:54:39 -07001536
1537 int userId = 0;
1538 if (args.size() >= 4 && args[2] == String16("--user")) {
1539 userId = atoi(String8(args[3]));
1540 }
1541
1542 uid_t uid;
1543 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1544 return BAD_VALUE;
1545 }
1546
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001547 sp<UidPolicy> uidPolicy;
1548 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001549 audio_utils::lock_guard _l(mMutex);
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001550 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001551 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001552 if (uidPolicy) {
1553 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1554 }
1555 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001556}
1557
1558status_t AudioPolicyService::printHelp(int out) {
1559 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001560 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1561 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1562 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001563 " help print this message\n");
1564}
1565
Eric Laurent0d13fea2022-11-04 17:12:08 +01001566status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1567 const audio_config_base_t& config,
1568 const audio_output_flags_t flags) {
1569 return mUsecaseValidator->registerStream(output, config, flags);
1570}
1571
1572status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1573 return mUsecaseValidator->unregisterStream(output);
1574}
1575
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001576// ----------- AudioPolicyService::UidPolicy implementation ----------
1577
1578void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001579 status_t res = mAm.linkToDeath(this);
1580 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001581 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001582 | ActivityManager::UID_OBSERVER_ACTIVE
1583 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001584 ActivityManager::PROCESS_STATE_UNKNOWN,
1585 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001586 if (!res) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001587 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001588 mObserverRegistered = true;
1589 } else {
1590 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001591
Steven Moreland2f348142019-07-02 15:59:07 -07001592 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001593 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001594}
1595
1596void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001597 mAm.unlinkToDeath(this);
1598 mAm.unregisterUidObserver(this);
Andy Hung79eacdb2023-11-30 19:34:24 -08001599 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001600 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001601}
1602
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001603void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001604 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001605 mCachedUids.clear();
1606 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001607}
1608
Eric Laurente8c8b432018-10-17 10:08:02 -07001609void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001610 bool needToReregister = false;
1611 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001612 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001613 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001614 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001615 if (needToReregister) {
1616 // Looks like ActivityManager has died previously, attempt to re-register.
1617 registerSelf();
1618 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001619}
1620
1621bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1622 if (isServiceUid(uid)) return true;
1623 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001624 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001625 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001626 auto overrideIter = mOverrideUids.find(uid);
1627 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001628 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001629 }
1630 // In an absense of the ActivityManager, assume everything to be active.
1631 if (!mObserverRegistered) return true;
1632 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001633 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001634 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001635 }
1636 }
1637 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001638 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001639 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001640 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001641 mCachedUids.insert(std::pair<uid_t,
1642 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1643 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001644 }
1645 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001646}
1647
Eric Laurente8c8b432018-10-17 10:08:02 -07001648int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1649 if (isServiceUid(uid)) {
1650 return ActivityManager::PROCESS_STATE_TOP;
1651 }
1652 checkRegistered();
1653 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001654 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001655 auto overrideIter = mOverrideUids.find(uid);
1656 if (overrideIter != mOverrideUids.end()) {
1657 if (overrideIter->second.first) {
1658 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1659 return overrideIter->second.second;
1660 } else {
1661 auto cacheIter = mCachedUids.find(uid);
1662 if (cacheIter != mCachedUids.end()) {
1663 return cacheIter->second.second;
1664 }
1665 }
1666 }
1667 return ActivityManager::PROCESS_STATE_UNKNOWN;
1668 }
1669 // In an absense of the ActivityManager, assume everything to be active.
1670 if (!mObserverRegistered) {
1671 return ActivityManager::PROCESS_STATE_TOP;
1672 }
1673 auto cacheIter = mCachedUids.find(uid);
1674 if (cacheIter != mCachedUids.end()) {
1675 if (cacheIter->second.first) {
1676 return cacheIter->second.second;
1677 } else {
1678 return ActivityManager::PROCESS_STATE_UNKNOWN;
1679 }
1680 }
1681 }
1682 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001683 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001684 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1685 if (active) {
1686 state = am.getUidProcessState(uid, String16("audioserver"));
1687 }
1688 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001689 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001690 mCachedUids.insert(std::pair<uid_t,
1691 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1692 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001693
Eric Laurente8c8b432018-10-17 10:08:02 -07001694 return state;
1695}
1696
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001697void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001698 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001699}
1700
1701void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001702 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001703}
1704
1705void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001706 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001707}
1708
Eric Laurente8c8b432018-10-17 10:08:02 -07001709void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1710 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001711 int64_t procStateSeq __unused,
1712 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001713 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1714 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001715 }
1716}
1717
Austin Borgerdddb7552023-03-30 17:53:01 -07001718void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001719}
1720
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001721void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001722 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1723}
1724
1725void AudioPolicyService::UidPolicy::notifyService() {
1726 sp<AudioPolicyService> service = mService.promote();
1727 if (service != nullptr) {
1728 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001729 }
1730}
1731
Eric Laurente8c8b432018-10-17 10:08:02 -07001732void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1733 std::pair<bool, int>> *uids,
1734 uid_t uid,
1735 bool active,
1736 int state,
1737 bool insert) {
1738 if (isServiceUid(uid)) {
1739 return;
1740 }
1741 bool wasActive = isUidActive(uid);
1742 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001743 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001744 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001745 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001746 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001747 if (wasActive != isUidActive(uid) || state != previousState) {
1748 notifyService();
1749 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001750}
1751
Eric Laurente8c8b432018-10-17 10:08:02 -07001752void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1753 std::pair<bool, int>> *uids,
1754 uid_t uid,
1755 bool active,
1756 int state,
1757 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001758 auto it = uids->find(uid);
1759 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001760 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001761 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1762 it->second.first = active;
1763 }
1764 if (it->second.first) {
1765 it->second.second = state;
1766 } else {
1767 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1768 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001769 } else {
1770 uids->erase(it);
1771 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001772 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1773 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1774 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001775 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001776}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777
Eric Laurent4eb58f12018-12-07 16:41:02 -08001778bool AudioPolicyService::UidPolicy::isA11yOnTop() {
Andy Hung79eacdb2023-11-30 19:34:24 -08001779 audio_utils::lock_guard _l(mMutex);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001780 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001781 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001782 continue;
1783 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001784 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1785 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001786 return true;
1787 }
1788 }
1789 return false;
1790}
1791
Eric Laurentb78763e2018-10-17 10:08:02 -07001792bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1793{
1794 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1795 return it != mA11yUids.end();
1796}
1797
Oscar Azucena829d90d2022-01-28 17:17:56 -08001798void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1799 mAssistantUids.clear();
1800 mAssistantUids = uids;
1801}
1802
1803bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1804{
1805 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1806 return it != mAssistantUids.end();
1807}
1808
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001809void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1810 mActiveAssistantUids = activeUids;
1811}
1812
1813bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1814{
1815 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1816 mActiveAssistantUids.end(), uid);
1817 return it != mActiveAssistantUids.end();
1818}
1819
Oscar Azucena829d90d2022-01-28 17:17:56 -08001820void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1821 const size_t SIZE = 256;
1822 char buffer[SIZE];
1823 String8 result;
1824 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1825 snprintf(buffer, SIZE, "\t%s: \n", title);
1826 result.append(buffer);
1827 int counter = 0;
1828 if (uids.empty()) {
1829 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1830 result.append(buffer);
1831 return;
1832 }
1833 for (const auto &uid : uids) {
1834 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1835 result.append(buffer);
1836 }
1837 };
1838
1839 snprintf(buffer, SIZE, "UID Policy:\n");
1840 result.append(buffer);
1841 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1842 result.append(buffer);
1843
1844 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001845 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001846
1847 appendUidsToResult("Accessibility UIDs", mA11yUids);
1848
1849 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1850 result.append(buffer);
1851
1852 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1853 result.append(buffer);
1854
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001855 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001856}
1857
Michael Groovercfd28302018-12-11 19:16:46 -08001858// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1859void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1860 SensorPrivacyManager spm;
1861 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1862 spm.addSensorPrivacyListener(this);
1863}
1864
1865void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1866 SensorPrivacyManager spm;
1867 spm.removeSensorPrivacyListener(this);
1868}
1869
1870bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1871 return mSensorPrivacyEnabled;
1872}
1873
Evan Seversond8dc6832022-01-27 10:47:03 -08001874binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1875 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001876 mSensorPrivacyEnabled = enabled;
1877 sp<AudioPolicyService> service = mService.promote();
1878 if (service != nullptr) {
1879 service->updateUidStates();
1880 }
1881 return binder::Status::ok();
1882}
1883
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1885
Eric Laurentbfb1b832013-01-07 09:53:42 -08001886AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1887 const wp<AudioPolicyService>& service)
1888 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890}
1891
1892
1893AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1894{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001895 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001896 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 }
1898 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899}
1900
1901void AudioPolicyService::AudioCommandThread::onFirstRef()
1902{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001903 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904}
1905
1906bool AudioPolicyService::AudioCommandThread::threadLoop()
1907{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001908 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909
Andy Hung79eacdb2023-11-30 19:34:24 -08001910 audio_utils::unique_lock ul(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911 while (!exitPending())
1912 {
Eric Laurent59a89232014-06-08 14:14:17 -07001913 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001914 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001915 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 nsecs_t curTime = systemTime();
1917 // commands are sorted by increasing time stamp: execute them from index 0 and up
1918 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001919 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001921 if (mAudioCommands.isEmpty()) {
1922 ++numTimesBecameEmpty;
1923 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001924 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925
1926 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001928 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001929 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001930 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001931 ul.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001932 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1933 data->mVolume,
1934 data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001935 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 }break;
1937 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001938 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001939 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001940 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001941 ul.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001942 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hung79eacdb2023-11-30 19:34:24 -08001943 ul.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001944 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001946 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001947 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001948 data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001949 ul.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001951 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001954 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001955 ALOGV("AudioCommandThread() processing stop output portId %d",
1956 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001957 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 if (svc == 0) {
1959 break;
1960 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001961 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001962 svc->doStopOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001963 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001964 }break;
1965 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001966 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001967 ALOGV("AudioCommandThread() processing release output portId %d",
1968 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001969 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 if (svc == 0) {
1971 break;
1972 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001973 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001974 svc->doReleaseOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001975 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001976 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001977 case CREATE_AUDIO_PATCH: {
1978 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1979 ALOGV("AudioCommandThread() processing create audio patch");
1980 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1981 if (af == 0) {
1982 command->mStatus = PERMISSION_DENIED;
1983 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001984 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001985 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001986 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001987 }
1988 } break;
1989 case RELEASE_AUDIO_PATCH: {
1990 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1991 ALOGV("AudioCommandThread() processing release audio patch");
1992 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1993 if (af == 0) {
1994 command->mStatus = PERMISSION_DENIED;
1995 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001996 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001997 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001998 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001999 }
2000 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07002001 case UPDATE_AUDIOPORT_LIST: {
2002 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07002003 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002004 if (svc == 0) {
2005 break;
2006 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002007 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002008 svc->doOnAudioPortListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08002009 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002010 }break;
2011 case UPDATE_AUDIOPATCH_LIST: {
2012 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07002013 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002014 if (svc == 0) {
2015 break;
2016 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002017 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002018 svc->doOnAudioPatchListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08002019 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07002020 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01002021 case CHANGED_AUDIOVOLUMEGROUP: {
2022 AudioVolumeGroupData *data =
2023 static_cast<AudioVolumeGroupData *>(command->mParam.get());
2024 ALOGV("AudioCommandThread() processing update audio volume group");
2025 svc = mService.promote();
2026 if (svc == 0) {
2027 break;
2028 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002029 ul.unlock();
François Gaffiecfe17322018-11-07 13:41:29 +01002030 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
Andy Hung79eacdb2023-11-30 19:34:24 -08002031 ul.lock();
François Gaffiecfe17322018-11-07 13:41:29 +01002032 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07002033 case SET_AUDIOPORT_CONFIG: {
2034 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
2035 ALOGV("AudioCommandThread() processing set port config");
2036 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2037 if (af == 0) {
2038 command->mStatus = PERMISSION_DENIED;
2039 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002040 ul.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07002041 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hung79eacdb2023-11-30 19:34:24 -08002042 ul.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07002043 }
2044 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07002045 case DYN_POLICY_MIX_STATE_UPDATE: {
2046 DynPolicyMixStateUpdateData *data =
2047 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002048 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002049 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002050 svc = mService.promote();
2051 if (svc == 0) {
2052 break;
2053 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002054 ul.unlock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002055 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
Andy Hung79eacdb2023-11-30 19:34:24 -08002056 ul.lock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002057 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002058 case RECORDING_CONFIGURATION_UPDATE: {
2059 RecordingConfigurationUpdateData *data =
2060 (RecordingConfigurationUpdateData *)command->mParam.get();
2061 ALOGV("AudioCommandThread() processing recording configuration update");
2062 svc = mService.promote();
2063 if (svc == 0) {
2064 break;
2065 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002066 ul.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002067 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08002068 &data->mClientConfig, data->mClientEffects,
2069 &data->mDeviceConfig, data->mEffects,
2070 data->mPatchHandle, data->mSource);
Andy Hung79eacdb2023-11-30 19:34:24 -08002071 ul.lock();
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002072 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002073 case SET_EFFECT_SUSPENDED: {
2074 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
2075 ALOGV("AudioCommandThread() processing set effect suspended");
2076 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2077 if (af != 0) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002078 ul.unlock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002079 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
Andy Hung79eacdb2023-11-30 19:34:24 -08002080 ul.lock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002081 }
2082 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002083 case AUDIO_MODULES_UPDATE: {
2084 ALOGV("AudioCommandThread() processing audio modules update");
2085 svc = mService.promote();
2086 if (svc == 0) {
2087 break;
2088 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002089 ul.unlock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002090 svc->doOnNewAudioModulesAvailable();
Andy Hung79eacdb2023-11-30 19:34:24 -08002091 ul.lock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002092 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002093 case ROUTING_UPDATED: {
2094 ALOGV("AudioCommandThread() processing routing update");
2095 svc = mService.promote();
2096 if (svc == 0) {
2097 break;
2098 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002099 ul.unlock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002100 svc->doOnRoutingUpdated();
Andy Hung79eacdb2023-11-30 19:34:24 -08002101 ul.lock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002102 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002103
Eric Laurented726cc2021-07-01 14:26:41 +02002104 case UPDATE_UID_STATES: {
2105 ALOGV("AudioCommandThread() processing updateUID states");
2106 svc = mService.promote();
2107 if (svc == 0) {
2108 break;
2109 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002110 ul.unlock();
Eric Laurented726cc2021-07-01 14:26:41 +02002111 svc->updateUidStates();
Andy Hung79eacdb2023-11-30 19:34:24 -08002112 ul.lock();
Eric Laurented726cc2021-07-01 14:26:41 +02002113 } break;
2114
Eric Laurent15903592022-02-24 20:44:36 +01002115 case CHECK_SPATIALIZER_OUTPUT: {
2116 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002117 svc = mService.promote();
2118 if (svc == 0) {
2119 break;
2120 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002121 ul.unlock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002122 svc->doOnCheckSpatializer();
Andy Hung79eacdb2023-11-30 19:34:24 -08002123 ul.lock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002124 } break;
2125
Eric Laurent15903592022-02-24 20:44:36 +01002126 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2127 ALOGV("AudioCommandThread() processing update spatializer tracks");
2128 svc = mService.promote();
2129 if (svc == 0) {
2130 break;
2131 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002132 ul.unlock();
Eric Laurent15903592022-02-24 20:44:36 +01002133 svc->doOnUpdateActiveSpatializerTracks();
Andy Hung79eacdb2023-11-30 19:34:24 -08002134 ul.lock();
Eric Laurent15903592022-02-24 20:44:36 +01002135 } break;
2136
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002137 case VOL_RANGE_INIT_REQUEST: {
2138 ALOGV("AudioCommandThread() processing volume range init request");
2139 svc = mService.promote();
2140 if (svc == 0) {
2141 break;
2142 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002143 ul.unlock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002144 svc->doOnVolumeRangeInitRequest();
Andy Hung79eacdb2023-11-30 19:34:24 -08002145 ul.lock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002146 } break;
2147
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002149 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002151 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002152 audio_utils::lock_guard _l(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002153 if (command->mWaitStatus) {
2154 command->mWaitStatus = false;
Andy Hung79eacdb2023-11-30 19:34:24 -08002155 command->mCond.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002156 }
2157 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002158 waitTime = -1;
Andy Hung79eacdb2023-11-30 19:34:24 -08002159 // release ul before releasing strong reference on the service as
Zach Janga754b4f2015-10-27 01:29:34 +00002160 // AudioPolicyService destructor calls AudioCommandThread::exit() which
Andy Hung79eacdb2023-11-30 19:34:24 -08002161 // acquires ul.
2162 ul.unlock();
Zach Janga754b4f2015-10-27 01:29:34 +00002163 svc.clear();
Andy Hung79eacdb2023-11-30 19:34:24 -08002164 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 } else {
2166 waitTime = mAudioCommands[0]->mTime - curTime;
2167 break;
2168 }
2169 }
Zach Janga754b4f2015-10-27 01:29:34 +00002170
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002171 // release delayed commands wake lock as many times as we made the queue is
2172 // empty during popping.
2173 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002174 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002175 }
2176
2177 // At this stage we have either an empty command queue or the first command in the queue
2178 // has a finite delay. So unless we are exiting it is safe to wait.
2179 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002180 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002181 if (waitTime == -1) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002182 mWaitWorkCV.wait(ul);
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002183 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002184 // discard return value.
2185 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002186 }
Eric Laurent59a89232014-06-08 14:14:17 -07002187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002189 // release delayed commands wake lock before quitting
2190 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002191 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 return false;
2194}
2195
2196status_t AudioPolicyService::AudioCommandThread::dump(int fd)
Andy Hung79eacdb2023-11-30 19:34:24 -08002197NO_THREAD_SAFETY_ANALYSIS // trylock
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198{
2199 const size_t SIZE = 256;
2200 char buffer[SIZE];
2201 String8 result;
2202
Andy Hung79eacdb2023-11-30 19:34:24 -08002203 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 if (!locked) {
2205 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002206 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 }
2208
2209 snprintf(buffer, SIZE, "- Commands:\n");
2210 result = String8(buffer);
2211 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002212 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213 mAudioCommands[i]->dump(buffer, SIZE);
2214 result.append(buffer);
2215 }
2216 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002217 if (mLastCommand != 0) {
2218 mLastCommand->dump(buffer, SIZE);
2219 result.append(buffer);
2220 } else {
2221 result.append(" none\n");
2222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002224 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225
Andy Hung79eacdb2023-11-30 19:34:24 -08002226 dumpReleaseLock(mMutex, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227
2228 return NO_ERROR;
2229}
2230
Glenn Kastenfff6d712012-01-12 16:38:12 -08002231status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002232 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002233 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002234 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235{
Eric Laurent0ede8922014-05-09 18:04:42 -07002236 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002238 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 data->mStream = stream;
2240 data->mVolume = volume;
2241 data->mIO = output;
2242 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002243 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002244 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002245 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002246 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247}
2248
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002249status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002250 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002251 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252{
Eric Laurent0ede8922014-05-09 18:04:42 -07002253 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002255 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002257 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002259 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002260 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002261 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002262 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263}
2264
2265status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2266{
Eric Laurent0ede8922014-05-09 18:04:42 -07002267 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002269 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 data->mVolume = volume;
2271 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002272 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002273 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002274 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275}
2276
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002277void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2278 audio_session_t sessionId,
2279 bool suspended)
2280{
2281 sp<AudioCommand> command = new AudioCommand();
2282 command->mCommand = SET_EFFECT_SUSPENDED;
2283 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2284 data->mEffectId = effectId;
2285 data->mSessionId = sessionId;
2286 data->mSuspended = suspended;
2287 command->mParam = data;
2288 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2289 effectId, sessionId, suspended);
2290 sendCommand(command);
2291}
2292
2293
Eric Laurentd7fe0862018-07-14 16:48:01 -07002294void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002295{
Eric Laurent0ede8922014-05-09 18:04:42 -07002296 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002298 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002299 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002300 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002301 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002302 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303}
2304
Eric Laurentd7fe0862018-07-14 16:48:01 -07002305void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002306{
Eric Laurent0ede8922014-05-09 18:04:42 -07002307 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002308 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002309 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002310 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002311 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002312 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002313 sendCommand(command);
2314}
2315
Eric Laurent951f4552014-05-20 10:48:17 -07002316status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2317 const struct audio_patch *patch,
2318 audio_patch_handle_t *handle,
2319 int delayMs)
2320{
2321 status_t status = NO_ERROR;
2322
2323 sp<AudioCommand> command = new AudioCommand();
2324 command->mCommand = CREATE_AUDIO_PATCH;
2325 CreateAudioPatchData *data = new CreateAudioPatchData();
2326 data->mPatch = *patch;
2327 data->mHandle = *handle;
2328 command->mParam = data;
2329 command->mWaitStatus = true;
2330 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2331 status = sendCommand(command, delayMs);
2332 if (status == NO_ERROR) {
2333 *handle = data->mHandle;
2334 }
2335 return status;
2336}
2337
2338status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2339 int delayMs)
2340{
2341 sp<AudioCommand> command = new AudioCommand();
2342 command->mCommand = RELEASE_AUDIO_PATCH;
2343 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2344 data->mHandle = handle;
2345 command->mParam = data;
2346 command->mWaitStatus = true;
2347 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2348 return sendCommand(command, delayMs);
2349}
2350
Eric Laurentb52c1522014-05-20 11:27:36 -07002351void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2352{
2353 sp<AudioCommand> command = new AudioCommand();
2354 command->mCommand = UPDATE_AUDIOPORT_LIST;
2355 ALOGV("AudioCommandThread() adding update audio port list");
2356 sendCommand(command);
2357}
2358
Eric Laurented726cc2021-07-01 14:26:41 +02002359void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2360{
2361 sp<AudioCommand> command = new AudioCommand();
2362 command->mCommand = UPDATE_UID_STATES;
2363 ALOGV("AudioCommandThread() adding update UID states");
2364 sendCommand(command);
2365}
2366
Eric Laurentb52c1522014-05-20 11:27:36 -07002367void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2368{
2369 sp<AudioCommand>command = new AudioCommand();
2370 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2371 ALOGV("AudioCommandThread() adding update audio patch list");
2372 sendCommand(command);
2373}
2374
François Gaffiecfe17322018-11-07 13:41:29 +01002375void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2376 int flags)
2377{
2378 sp<AudioCommand>command = new AudioCommand();
2379 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2380 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2381 data->mGroup = group;
2382 data->mFlags = flags;
2383 command->mParam = data;
2384 ALOGV("AudioCommandThread() adding audio volume group changed");
2385 sendCommand(command);
2386}
2387
Eric Laurente1715a42014-05-20 11:30:42 -07002388status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2389 const struct audio_port_config *config, int delayMs)
2390{
2391 sp<AudioCommand> command = new AudioCommand();
2392 command->mCommand = SET_AUDIOPORT_CONFIG;
2393 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2394 data->mConfig = *config;
2395 command->mParam = data;
2396 command->mWaitStatus = true;
2397 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2398 return sendCommand(command, delayMs);
2399}
2400
Jean-Michel Trivide801052015-04-14 19:10:14 -07002401void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002402 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002403{
2404 sp<AudioCommand> command = new AudioCommand();
2405 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2406 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2407 data->mRegId = regId;
2408 data->mState = state;
2409 command->mParam = data;
2410 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002411 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002412 sendCommand(command);
2413}
2414
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002415void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002416 int event,
2417 const record_client_info_t *clientInfo,
2418 const audio_config_base_t *clientConfig,
2419 std::vector<effect_descriptor_t> clientEffects,
2420 const audio_config_base_t *deviceConfig,
2421 std::vector<effect_descriptor_t> effects,
2422 audio_patch_handle_t patchHandle,
2423 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002424{
2425 sp<AudioCommand>command = new AudioCommand();
2426 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2427 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2428 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002429 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002430 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002431 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002432 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002433 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002434 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002435 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002436 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002437 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2438 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002439 sendCommand(command);
2440}
2441
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002442void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2443{
2444 sp<AudioCommand> command = new AudioCommand();
2445 command->mCommand = AUDIO_MODULES_UPDATE;
2446 sendCommand(command);
2447}
2448
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002449void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2450{
2451 sp<AudioCommand>command = new AudioCommand();
2452 command->mCommand = ROUTING_UPDATED;
2453 ALOGV("AudioCommandThread() adding routing update");
2454 sendCommand(command);
2455}
2456
Eric Laurent81dd0f52021-07-05 11:54:40 +02002457void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2458{
2459 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002460 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002461 ALOGV("AudioCommandThread() adding check spatializer");
2462 sendCommand(command);
2463}
2464
Eric Laurent15903592022-02-24 20:44:36 +01002465void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2466{
2467 sp<AudioCommand>command = new AudioCommand();
2468 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2469 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2470 sendCommand(command);
2471}
2472
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002473void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2474{
2475 sp<AudioCommand>command = new AudioCommand();
2476 command->mCommand = VOL_RANGE_INIT_REQUEST;
2477 ALOGV("AudioCommandThread() adding volume range init request");
2478 sendCommand(command);
2479}
2480
Eric Laurent0ede8922014-05-09 18:04:42 -07002481status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2482{
2483 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002484 audio_utils::lock_guard _l(mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002485 insertCommand_l(command, delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002486 mWaitWorkCV.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002487 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002488 audio_utils::unique_lock ul(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002489 while (command->mWaitStatus) {
2490 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002491 if (command->mCond.wait_for(
Andy Hung02ea2a02024-01-25 17:02:30 -08002492 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002493 command->mStatus = TIMED_OUT;
2494 command->mWaitStatus = false;
2495 }
2496 }
2497 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002498}
2499
Andy Hung79eacdb2023-11-30 19:34:24 -08002500// insertCommand_l() must be called with mMutex held
Eric Laurent0ede8922014-05-09 18:04:42 -07002501void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002503 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002504 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 command->mTime = systemTime() + milliseconds(delayMs);
2506
2507 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002508 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002509 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 }
2511
2512 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002513 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002514 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2516 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002517
2518 // create audio patch or release audio patch commands are equivalent
2519 // with regard to filtering
2520 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2521 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2522 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2523 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2524 continue;
2525 }
2526 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527
2528 switch (command->mCommand) {
2529 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002530 ParametersData *data = (ParametersData *)command->mParam.get();
2531 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002533 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002534 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2536 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2537 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002538 String8 key;
2539 String8 value;
2540 param.getAt(j, key, value);
2541 for (size_t k = 0; k < param2.size(); k++) {
2542 String8 key2;
2543 String8 value2;
2544 param2.getAt(k, key2, value2);
2545 if (key2 == key) {
2546 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002547 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002548 break;
2549 }
2550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002551 }
2552 // if all keys have been filtered out, remove the command.
2553 // otherwise, update the key value pairs
2554 if (param2.size() == 0) {
2555 removedCommands.add(command2);
2556 } else {
2557 data2->mKeyValuePairs = param2.toString();
2558 }
Eric Laurent21e54562013-09-23 12:08:05 -07002559 command->mTime = command2->mTime;
2560 // force delayMs to non 0 so that code below does not request to wait for
2561 // command status as the command is now delayed
2562 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 } break;
2564
2565 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002566 VolumeData *data = (VolumeData *)command->mParam.get();
2567 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 if (data->mIO != data2->mIO) break;
2569 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002570 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002571 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002573 command->mTime = command2->mTime;
2574 // force delayMs to non 0 so that code below does not request to wait for
2575 // command status as the command is now delayed
2576 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002578
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002579 case SET_VOICE_VOLUME: {
2580 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2581 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2582 ALOGV("Filtering out voice volume command value %f replaced by %f",
2583 data2->mVolume, data->mVolume);
2584 removedCommands.add(command2);
2585 command->mTime = command2->mTime;
2586 // force delayMs to non 0 so that code below does not request to wait for
2587 // command status as the command is now delayed
2588 delayMs = 1;
2589 } break;
2590
Eric Laurente45b48a2014-09-04 16:40:57 -07002591 case CREATE_AUDIO_PATCH:
2592 case RELEASE_AUDIO_PATCH: {
2593 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002594 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002595 if (command->mCommand == CREATE_AUDIO_PATCH) {
2596 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002597 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002598 } else {
2599 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002600 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002601 }
2602 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002603 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002604 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2605 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002606 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002607 } else {
2608 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002609 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002610 }
2611 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002612 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2613 same output. */
2614 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2615 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2616 bool isOutputDiff = false;
2617 if (patch.num_sources == patch2.num_sources) {
2618 for (unsigned count = 0; count < patch.num_sources; count++) {
2619 if (patch.sources[count].id != patch2.sources[count].id) {
2620 isOutputDiff = true;
2621 break;
2622 }
2623 }
2624 if (isOutputDiff)
2625 break;
2626 }
2627 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002628 ALOGV("Filtering out %s audio patch command for handle %d",
2629 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2630 removedCommands.add(command2);
2631 command->mTime = command2->mTime;
2632 // force delayMs to non 0 so that code below does not request to wait for
2633 // command status as the command is now delayed
2634 delayMs = 1;
2635 } break;
2636
Jean-Michel Trivide801052015-04-14 19:10:14 -07002637 case DYN_POLICY_MIX_STATE_UPDATE: {
2638
2639 } break;
2640
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002641 case RECORDING_CONFIGURATION_UPDATE: {
2642
2643 } break;
2644
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002645 case ROUTING_UPDATED: {
2646
2647 } break;
2648
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002649 case VOL_RANGE_INIT_REQUEST: {
2650 // command may come from different requests, do not filter
2651 } break;
2652
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 default:
2654 break;
2655 }
2656 }
2657
2658 // remove filtered commands
2659 for (size_t j = 0; j < removedCommands.size(); j++) {
2660 // removed commands always have time stamps greater than current command
2661 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002662 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002663 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 mAudioCommands.removeAt(k);
2665 break;
2666 }
2667 }
2668 }
2669 removedCommands.clear();
2670
Eric Laurentaa79bef2015-01-15 14:33:51 -08002671 // Disable wait for status if delay is not 0.
2672 // Except for create audio patch command because the returned patch handle
2673 // is needed by audio policy manager
2674 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002675 command->mWaitStatus = false;
2676 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002677
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002679 ALOGV("inserting command: %d at index %zd, num commands %zu",
2680 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 mAudioCommands.insertAt(command, i + 1);
2682}
2683
2684void AudioPolicyService::AudioCommandThread::exit()
2685{
Steve Block3856b092011-10-20 11:56:00 +01002686 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002688 audio_utils::lock_guard _l(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 requestExit();
Andy Hung79eacdb2023-11-30 19:34:24 -08002690 mWaitWorkCV.notify_one();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691 }
Zach Janga754b4f2015-10-27 01:29:34 +00002692 // Note that we can call it from the thread loop if all other references have been released
2693 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002694 requestExitAndWait();
2695}
2696
2697void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2698{
2699 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2700 mCommand,
2701 (int)ns2s(mTime),
2702 (int)ns2ms(mTime)%1000,
2703 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002704 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705}
2706
Dima Zavinfce7a472011-04-19 22:30:36 -07002707/******* helpers for the service_ops callbacks defined below *********/
2708void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2709 const char *keyValuePairs,
2710 int delayMs)
2711{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002712 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002713 delayMs);
2714}
2715
2716int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2717 float volume,
2718 audio_io_handle_t output,
2719 int delayMs)
2720{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002721 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002722 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002723}
2724
Dima Zavinfce7a472011-04-19 22:30:36 -07002725int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2726{
2727 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2728}
2729
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002730void AudioPolicyService::setEffectSuspended(int effectId,
2731 audio_session_t sessionId,
2732 bool suspended)
2733{
2734 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2735}
2736
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002737Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002738{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002739 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002740 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002741}
2742
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002743
Dima Zavinfce7a472011-04-19 22:30:36 -07002744extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002745audio_module_handle_t aps_load_hw_module(void *service __unused,
2746 const char *name);
2747audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002748 audio_devices_t *pDevices,
2749 uint32_t *pSamplingRate,
2750 audio_format_t *pFormat,
2751 audio_channel_mask_t *pChannelMask,
2752 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002753 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002754
Eric Laurent2d388ec2014-03-07 13:25:54 -08002755audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002756 audio_module_handle_t module,
2757 audio_devices_t *pDevices,
2758 uint32_t *pSamplingRate,
2759 audio_format_t *pFormat,
2760 audio_channel_mask_t *pChannelMask,
2761 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002762 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002763 const audio_offload_info_t *offloadInfo);
2764audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002765 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002766 audio_io_handle_t output2);
2767int aps_close_output(void *service __unused, audio_io_handle_t output);
2768int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2769int aps_restore_output(void *service __unused, audio_io_handle_t output);
2770audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002771 audio_devices_t *pDevices,
2772 uint32_t *pSamplingRate,
2773 audio_format_t *pFormat,
2774 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002775 audio_in_acoustics_t acoustics __unused);
2776audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002777 audio_module_handle_t module,
2778 audio_devices_t *pDevices,
2779 uint32_t *pSamplingRate,
2780 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002781 audio_channel_mask_t *pChannelMask);
2782int aps_close_input(void *service __unused, audio_io_handle_t input);
2783int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002784int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002785 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002786 audio_io_handle_t dst_output);
2787char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2788 const char *keys);
2789void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2790 const char *kv_pairs, int delay_ms);
2791int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002792 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002793 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002794int aps_set_voice_volume(void *service, float volume, int delay_ms);
2795};
Dima Zavinfce7a472011-04-19 22:30:36 -07002796
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002797} // namespace android