blob: 2e0aa3c52aa529266d9c374d94255244e025b8b0 [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) \
Vlad Popa87e0e582024-05-20 18:49:20 -070082BINDER_METHOD_ENTRY(setDeviceAbsoluteVolumeEnabled) \
Andy Hungc747c532022-03-07 21:41:14 -080083BINDER_METHOD_ENTRY(initStreamVolume) \
84BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
85BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
86BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
87BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
88BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
90BINDER_METHOD_ENTRY(getStrategyForStream) \
91BINDER_METHOD_ENTRY(getDevicesForAttributes) \
92BINDER_METHOD_ENTRY(getOutputForEffect) \
93BINDER_METHOD_ENTRY(registerEffect) \
94BINDER_METHOD_ENTRY(unregisterEffect) \
95BINDER_METHOD_ENTRY(setEffectEnabled) \
96BINDER_METHOD_ENTRY(moveEffectsToIo) \
97BINDER_METHOD_ENTRY(isStreamActive) \
98BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
99BINDER_METHOD_ENTRY(isSourceActive) \
100BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
101BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
102BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
103BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
104BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
105BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
106BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
107BINDER_METHOD_ENTRY(getOffloadSupport) \
108BINDER_METHOD_ENTRY(isDirectOutputSupported) \
109BINDER_METHOD_ENTRY(listAudioPorts) \
110BINDER_METHOD_ENTRY(getAudioPort) \
111BINDER_METHOD_ENTRY(createAudioPatch) \
112BINDER_METHOD_ENTRY(releaseAudioPatch) \
113BINDER_METHOD_ENTRY(listAudioPatches) \
114BINDER_METHOD_ENTRY(setAudioPortConfig) \
115BINDER_METHOD_ENTRY(registerClient) \
116BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
117BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
118BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
119BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
120BINDER_METHOD_ENTRY(getPhoneState) \
121BINDER_METHOD_ENTRY(registerPolicyMixes) \
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +0200122BINDER_METHOD_ENTRY(updatePolicyMixes) \
Andy Hungc747c532022-03-07 21:41:14 -0800123BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
124BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
125BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
126BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
127BINDER_METHOD_ENTRY(startAudioSource) \
128BINDER_METHOD_ENTRY(stopAudioSource) \
129BINDER_METHOD_ENTRY(setMasterMono) \
130BINDER_METHOD_ENTRY(getMasterMono) \
131BINDER_METHOD_ENTRY(getStreamVolumeDB) \
132BINDER_METHOD_ENTRY(getSurroundFormats) \
133BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
134BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
135BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
136BINDER_METHOD_ENTRY(setAssistantServicesUids) \
137BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
138BINDER_METHOD_ENTRY(setA11yServicesUids) \
139BINDER_METHOD_ENTRY(setCurrentImeUid) \
140BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
141BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800142BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800143BINDER_METHOD_ENTRY(listAudioProductStrategies) \
144BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
145BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
146BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
147BINDER_METHOD_ENTRY(setRttEnabled) \
148BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
149BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
150BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000151BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800152BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
153BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
154BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
155BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
156BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
157BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
158BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
159BINDER_METHOD_ENTRY(getSpatializer) \
160BINDER_METHOD_ENTRY(canBeSpatialized) \
161BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000162BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
163BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
164BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
165BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
166BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100167BINDER_METHOD_ENTRY(getRegisteredPolicyMixes) \
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700168BINDER_METHOD_ENTRY(getPermissionController) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100169 \
Andy Hungc747c532022-03-07 21:41:14 -0800170// singleton for Binder Method Statistics for IAudioPolicyService
171static auto& getIAudioPolicyServiceStatistics() {
172 using Code = int;
173
174#pragma push_macro("BINDER_METHOD_ENTRY")
175#undef BINDER_METHOD_ENTRY
176#define BINDER_METHOD_ENTRY(ENTRY) \
177 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
178
179 static mediautils::MethodStatistics<Code> methodStatistics{
180 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
181 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
182 };
183#pragma pop_macro("BINDER_METHOD_ENTRY")
184
185 return methodStatistics;
186}
187
Mathias Agopian65ab4712010-07-14 17:59:35 -0700188// ----------------------------------------------------------------------------
189
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530190static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
191{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700192 AudioPolicyManager *apm = nullptr;
193 media::AudioPolicyConfig apmConfig;
194 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
195 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
196 LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
197 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
198 "Only default engine is currently supported with the AIDL HAL");
199 apm = new AudioPolicyManager(config,
200 loadApmEngineLibraryAndCreateEngine(
201 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
202 clientInterface);
203 } else {
204 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
205 apm = new AudioPolicyManager(config,
206 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
207 clientInterface);
208 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530209 status_t status = apm->initialize();
210 if (status != NO_ERROR) {
211 delete apm;
212 apm = nullptr;
213 }
214 return apm;
215}
216
217static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
218{
219 delete interface;
220}
221// ----------------------------------------------------------------------------
222
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700224 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700225 mAudioPolicyManager(NULL),
226 mAudioPolicyClient(NULL),
227 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530228 mCaptureStateNotifier(false),
229 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100230 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700231 mUsecaseValidator(media::createUsecaseValidator()),
232 mPermissionController(sp<NativePermissionController>::make())
233{
Andy Hung225aef62022-12-06 16:33:20 -0800234 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Andy Hung58b01b12024-03-26 18:04:29 -0700235 setInheritRt(true);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530236}
237
238void AudioPolicyService::loadAudioPolicyManager()
239{
240 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
241 if (mLibraryHandle != nullptr) {
242 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
243 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
244 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
245 const char *lastError = dlerror();
246 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
247 __func__, lastError != nullptr ? lastError : "no error");
248
249 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
250 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
251 lastError = dlerror();
252 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
253 __func__, lastError != nullptr ? lastError : "no error");
254 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
255 unloadAudioPolicyManager();
256 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
257 }
258 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700259}
260
261void AudioPolicyService::onFirstRef()
262{
Andy Hungd47aca22022-03-15 11:50:51 -0700263 // Log an AudioPolicy "constructor" mediametrics event on first ref.
264 // This records the time it takes to load the audio modules and devices.
265 mediametrics::Defer defer([beginNs = systemTime()] {
266 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
267 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
268 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
269 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700270 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800271 audio_utils::lock_guard _l(mMutex);
Eric Laurent93575202011-01-18 18:39:02 -0800272
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700273 // start audio commands thread
274 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
275 // start output activity command thread
276 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700277
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700278 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530279
280 loadAudioPolicyManager();
281 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700282 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200283
bryant_liuba2b4392014-06-11 16:49:30 +0800284 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000285 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
Andy Hungd3595ed2023-12-19 15:34:46 -0800286 auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
287 auto uidPolicy = sp<UidPolicy>::make(this);
288 auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700289 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800290 audio_utils::lock_guard _l(mMutex);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700291 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000292 mUidPolicy = uidPolicy;
293 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700294 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000295 uidPolicy->registerSelf();
296 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200297
Eric Laurent81dd0f52021-07-05 11:54:40 +0200298 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200299 if (mAudioPolicyManager != nullptr) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800300 audio_utils::lock_guard _l(mMutex);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200301 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
302 AudioDeviceTypeAddrVector devices;
303 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
304 if (hasSpatializer) {
Andy Hung1040da52023-12-06 20:59:06 -0800305 // Unlock as Spatializer::create() will use the callback and acquire the
306 // AudioPolicyService_Mutex.
Andy Hung79eacdb2023-11-30 19:34:24 -0800307 mMutex.unlock();
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000308 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Andy Hung79eacdb2023-11-30 19:34:24 -0800309 mMutex.lock();
Eric Laurent52b0bd52021-09-27 15:25:40 +0200310 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700311 if (mSpatializer == nullptr) {
312 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
313 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
314 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
315 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200316 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200317 AudioSystem::audioPolicyReady();
Andy Hungb08b3752024-01-09 19:05:23 -0800318}
319
Atneya Nair87818d32024-05-23 10:59:30 -0700320const IPermissionProvider& AudioPolicyService::getPermissionProvider() const {
321 return *mPermissionController;
322}
323
Andy Hungb08b3752024-01-09 19:05:23 -0800324void AudioPolicyService::onAudioSystemReady() {
325 sp<AudioPolicyEffects> audioPolicyEffects;
326 {
327 audio_utils::lock_guard _l(mMutex);
328
329 audioPolicyEffects = mAudioPolicyEffects;
330 }
331 audioPolicyEffects->initDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332}
333
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530334void AudioPolicyService::unloadAudioPolicyManager()
335{
336 ALOGV("%s ", __func__);
337 if (mLibraryHandle != nullptr) {
338 dlclose(mLibraryHandle);
339 }
340 mLibraryHandle = nullptr;
341 mCreateAudioPolicyManager = nullptr;
342 mDestroyAudioPolicyManager = nullptr;
343}
344
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345AudioPolicyService::~AudioPolicyService()
346{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700348 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700349
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530350 mDestroyAudioPolicyManager(mAudioPolicyManager);
351 unloadAudioPolicyManager();
352
Eric Laurentdce54a12014-03-10 12:19:46 -0700353 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700354
355 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800356 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800357
358 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800359 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000360
361 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800362 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700363}
364
365// A notification client is always registered by AudioSystem when the client process
366// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800367Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700368{
Eric Laurent12590252015-08-21 18:40:20 -0700369 if (client == 0) {
370 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800371 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700372 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800373 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700374
375 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800376 pid_t pid = IPCThreadState::self()->getCallingPid();
377 int64_t token = ((int64_t)uid<<32) | pid;
378
379 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700380 sp<NotificationClient> notificationClient = new NotificationClient(this,
381 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800382 uid,
383 pid);
384 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700385
luochaojiang908c7d72018-06-21 14:58:04 +0800386 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700387
Marco Nelissenf8880202014-11-14 07:58:25 -0800388 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700389 binder->linkToDeath(notificationClient);
390 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800391 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700392}
393
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800394Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700395{
Andy Hung79eacdb2023-11-30 19:34:24 -0800396 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurente8726fe2015-06-26 09:39:24 -0700397
398 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800399 pid_t pid = IPCThreadState::self()->getCallingPid();
400 int64_t token = ((int64_t)uid<<32) | pid;
401
402 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800403 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700404 }
luochaojiang908c7d72018-06-21 14:58:04 +0800405 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800406 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700407}
408
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800409Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100410{
Andy Hung79eacdb2023-11-30 19:34:24 -0800411 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100412
413 uid_t uid = IPCThreadState::self()->getCallingUid();
414 pid_t pid = IPCThreadState::self()->getCallingPid();
415 int64_t token = ((int64_t)uid<<32) | pid;
416
417 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800418 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100419 }
420 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800421 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100422}
423
Eric Laurentb52c1522014-05-20 11:27:36 -0700424// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800425void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700426{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000427 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800428 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800429 audio_utils::lock_guard _l(mNotificationClientsMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800430 int64_t token = ((int64_t)uid<<32) | pid;
431 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800432 for (size_t i = 0; i < mNotificationClients.size(); i++) {
433 if (mNotificationClients.valueAt(i)->uid() == uid) {
434 hasSameUid = true;
435 break;
436 }
437 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000438 }
439 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800440 audio_utils::lock_guard _l(mMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800441 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700442 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700443 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700444 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800445 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700446}
447
448void AudioPolicyService::onAudioPortListUpdate()
449{
450 mOutputCommandThread->updateAudioPortListCommand();
451}
452
453void AudioPolicyService::doOnAudioPortListUpdate()
454{
Andy Hung79eacdb2023-11-30 19:34:24 -0800455 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700456 for (size_t i = 0; i < mNotificationClients.size(); i++) {
457 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
458 }
459}
460
461void AudioPolicyService::onAudioPatchListUpdate()
462{
463 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464}
465
Eric Laurentb52c1522014-05-20 11:27:36 -0700466void AudioPolicyService::doOnAudioPatchListUpdate()
467{
Andy Hung79eacdb2023-11-30 19:34:24 -0800468 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700469 for (size_t i = 0; i < mNotificationClients.size(); i++) {
470 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
471 }
472}
473
François Gaffiecfe17322018-11-07 13:41:29 +0100474void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
475{
476 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
477}
478
479void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
480{
Andy Hung79eacdb2023-11-30 19:34:24 -0800481 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100482 for (size_t i = 0; i < mNotificationClients.size(); i++) {
483 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
484 }
485}
486
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700487void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700488{
489 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000490 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700491 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
492}
493
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700494void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700495{
Andy Hung79eacdb2023-11-30 19:34:24 -0800496 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700497 for (size_t i = 0; i < mNotificationClients.size(); i++) {
498 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
499 }
500}
501
Eric Laurenta9f86652018-11-28 17:23:11 -0800502void AudioPolicyService::onRecordingConfigurationUpdate(
503 int event,
504 const record_client_info_t *clientInfo,
505 const audio_config_base_t *clientConfig,
506 std::vector<effect_descriptor_t> clientEffects,
507 const audio_config_base_t *deviceConfig,
508 std::vector<effect_descriptor_t> effects,
509 audio_patch_handle_t patchHandle,
510 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800511{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800512 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800513 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800514}
515
Eric Laurenta9f86652018-11-28 17:23:11 -0800516void AudioPolicyService::doOnRecordingConfigurationUpdate(
517 int event,
518 const record_client_info_t *clientInfo,
519 const audio_config_base_t *clientConfig,
520 std::vector<effect_descriptor_t> clientEffects,
521 const audio_config_base_t *deviceConfig,
522 std::vector<effect_descriptor_t> effects,
523 audio_patch_handle_t patchHandle,
524 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800525{
Andy Hung79eacdb2023-11-30 19:34:24 -0800526 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800527 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800528 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800529 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800530 }
531}
532
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700533void AudioPolicyService::onRoutingUpdated()
534{
535 mOutputCommandThread->routingChangedCommand();
536}
537
538void AudioPolicyService::doOnRoutingUpdated()
539{
Andy Hung79eacdb2023-11-30 19:34:24 -0800540 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700541 for (size_t i = 0; i < mNotificationClients.size(); i++) {
542 mNotificationClients.valueAt(i)->onRoutingUpdated();
543 }
544}
545
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000546void AudioPolicyService::onVolumeRangeInitRequest()
547{
548 mOutputCommandThread->volRangeInitReqCommand();
549}
550
551void AudioPolicyService::doOnVolumeRangeInitRequest()
552{
Andy Hung79eacdb2023-11-30 19:34:24 -0800553 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000554 for (size_t i = 0; i < mNotificationClients.size(); i++) {
555 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
556 }
557}
558
Eric Laurent81dd0f52021-07-05 11:54:40 +0200559void AudioPolicyService::onCheckSpatializer()
560{
Andy Hung79eacdb2023-11-30 19:34:24 -0800561 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200562 onCheckSpatializer_l();
563}
564
565void AudioPolicyService::onCheckSpatializer_l()
566{
567 if (mSpatializer != nullptr) {
568 mOutputCommandThread->checkSpatializerCommand();
569 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200570}
571
572void AudioPolicyService::doOnCheckSpatializer()
573{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200574 ALOGV("%s mSpatializer %p level %d",
575 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200576
Eric Laurent39095982021-08-24 18:29:27 +0200577 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200578 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000579 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200580 audio_io_handle_t currentOutput = mSpatializer->getOutput();
581 audio_io_handle_t newOutput;
582 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
583 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200584
Andy Hung79eacdb2023-11-30 19:34:24 -0800585 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200586 status_t status =
587 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100588 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
589 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200590 if (status == NO_ERROR && currentOutput == newOutput) {
591 return;
592 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000593 std::vector<audio_channel_mask_t> activeTracksMasks =
594 getActiveTracksMasks_l(newOutput);
Andy Hung79eacdb2023-11-30 19:34:24 -0800595 mMutex.unlock();
Eric Laurent39095982021-08-24 18:29:27 +0200596 // It is OK to call detachOutput() is none is already attached.
597 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200598 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000599 status = mSpatializer->attachOutput(newOutput, activeTracksMasks);
Eric Laurent39095982021-08-24 18:29:27 +0200600 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800601 mMutex.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200602 if (status != NO_ERROR) {
603 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
604 }
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000605 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
606 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200607 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200608
Eric Laurent39095982021-08-24 18:29:27 +0200609 if (output != AUDIO_IO_HANDLE_NONE) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800610 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200611 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200612 }
613 }
614 }
615}
616
Eric Laurentb16eac52024-08-02 16:46:08 +0000617std::vector<audio_channel_mask_t> AudioPolicyService::getActiveTracksMasks_l(
Eric Laurent11094172022-04-05 18:27:42 +0200618 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000619 std::vector<audio_channel_mask_t> activeTrackMasks;
Eric Laurent15903592022-02-24 20:44:36 +0100620 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
621 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200622 if (client->io == output && client->active
623 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000624 activeTrackMasks.push_back(client->channelMask);
Eric Laurent15903592022-02-24 20:44:36 +0100625 }
626 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000627 return activeTrackMasks;
Eric Laurent15903592022-02-24 20:44:36 +0100628}
629
630void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
631 if (mSpatializer == nullptr) {
632 return;
633 }
634 mOutputCommandThread->updateActiveSpatializerTracksCommand();
635}
636
637void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
638{
Eric Laurent21270b62022-07-04 15:11:29 +0200639 if (mSpatializer == nullptr) {
640 return;
641 }
642 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurentb16eac52024-08-02 16:46:08 +0000643 std::vector<audio_channel_mask_t> activeTracksMasks;
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200644 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800645 audio_utils::lock_guard _l(mMutex);
Eric Laurentb16eac52024-08-02 16:46:08 +0000646 activeTracksMasks = getActiveTracksMasks_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100647 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000648 mSpatializer->updateActiveTracks(activeTracksMasks);
Eric Laurent15903592022-02-24 20:44:36 +0100649}
650
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800651status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
652 audio_patch_handle_t *handle,
653 int delayMs)
654{
655 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
656}
657
658status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
659 int delayMs)
660{
661 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
662}
663
Eric Laurente1715a42014-05-20 11:30:42 -0700664status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
665 int delayMs)
666{
667 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
668}
669
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800670AudioPolicyService::NotificationClient::NotificationClient(
671 const sp<AudioPolicyService>& service,
672 const sp<media::IAudioPolicyServiceClient>& client,
673 uid_t uid,
674 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800675 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100676 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700677{
678}
679
680AudioPolicyService::NotificationClient::~NotificationClient()
681{
682}
683
684void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
685{
686 sp<NotificationClient> keep(this);
687 sp<AudioPolicyService> service = mService.promote();
688 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800689 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700690 }
691}
692
693void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
694{
Eric Laurente8726fe2015-06-26 09:39:24 -0700695 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700696 mAudioPolicyServiceClient->onAudioPortListUpdate();
697 }
698}
699
700void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
701{
Eric Laurente8726fe2015-06-26 09:39:24 -0700702 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700703 mAudioPolicyServiceClient->onAudioPatchListUpdate();
704 }
705}
Eric Laurent57dae992011-07-24 13:36:09 -0700706
Pattydd807582021-11-04 21:01:03 +0800707void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100708 int flags)
709{
710 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
711 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
712 }
713}
714
715
Jean-Michel Trivide801052015-04-14 19:10:14 -0700716void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700717 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700718{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700719 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800720 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
721 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800722 }
723}
724
725void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800726 int event,
727 const record_client_info_t *clientInfo,
728 const audio_config_base_t *clientConfig,
729 std::vector<effect_descriptor_t> clientEffects,
730 const audio_config_base_t *deviceConfig,
731 std::vector<effect_descriptor_t> effects,
732 audio_patch_handle_t patchHandle,
733 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800734{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700735 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800736 status_t status = [&]() -> status_t {
737 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
738 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
739 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700740 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700741 legacy2aidl_audio_config_base_t_AudioConfigBase(
742 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800743 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
744 convertContainer<std::vector<media::EffectDescriptor>>(
745 clientEffects,
746 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700747 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700748 legacy2aidl_audio_config_base_t_AudioConfigBase(
749 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800750 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
751 convertContainer<std::vector<media::EffectDescriptor>>(
752 effects,
753 legacy2aidl_effect_descriptor_t_EffectDescriptor));
754 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
755 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700756 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
757 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800758 return aidl_utils::statusTFromBinderStatus(
759 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
760 clientInfoAidl,
761 clientConfigAidl,
762 clientEffectsAidl,
763 deviceConfigAidl,
764 effectsAidl,
765 patchHandleAidl,
766 sourceAidl));
767 }();
768 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700769 }
770}
771
Eric Laurente8726fe2015-06-26 09:39:24 -0700772void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
773{
774 mAudioPortCallbacksEnabled = enabled;
775}
776
François Gaffiecfe17322018-11-07 13:41:29 +0100777void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
778{
779 mAudioVolumeGroupCallbacksEnabled = enabled;
780}
Eric Laurente8726fe2015-06-26 09:39:24 -0700781
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700782void AudioPolicyService::NotificationClient::onRoutingUpdated()
783{
784 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
785 mAudioPolicyServiceClient->onRoutingUpdated();
786 }
787}
788
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000789void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
790{
791 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
792 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
793 }
794}
795
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700797 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700798 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799}
800
Andy Hung79eacdb2023-11-30 19:34:24 -0800801static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
802 RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000803{
804 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805}
806
807status_t AudioPolicyService::dumpInternals(int fd)
808{
809 const size_t SIZE = 256;
810 char buffer[SIZE];
811 String8 result;
812
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000813 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800814 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000815 std::stringstream msg;
816 size_t i = 0;
817 for (auto usage : mSupportedSystemUsages) {
818 if (i++ != 0) msg << ", ";
819 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
820 msg << strUsage;
821 } else {
822 msg << usage << " (unknown)";
823 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800824 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000825 if (i == 0) {
826 msg << "None";
827 }
828 msg << std::endl;
829 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800830
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000831 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800832
833 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 return NO_ERROR;
835}
836
Eric Laurente8c8b432018-10-17 10:08:02 -0700837void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800838{
Andy Hung79eacdb2023-11-30 19:34:24 -0800839 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -0700840 updateUidStates_l();
841}
842
843void AudioPolicyService::updateUidStates_l()
844{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800845// Go over all active clients and allow capture (does not force silence) in the
846// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800847// The client is in the active assistant list
848// AND is TOP
849// AND an accessibility service is TOP
850// AND source is either VOICE_RECOGNITION OR HOTWORD
851// OR there is no active privacy sensitive capture or call
852// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
853// AND source is VOICE_RECOGNITION OR HOTWORD
854// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800855// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700856// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800857// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800858// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800859// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
860// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800861// OR The client is an accessibility service
862// AND Is on TOP
863// AND the source is VOICE_RECOGNITION or HOTWORD
864// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700865// AND there is no active privacy sensitive capture or call
866// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800867// AND is on TOP
868// AND the source is VOICE_RECOGNITION or HOTWORD
869// OR the client source is virtual (remote submix, call audio TX or RX...)
870// OR the client source is HOTWORD
871// AND is on TOP
872// OR all active clients are using HOTWORD source
873// AND no call is active
874// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
875// OR the client is the current InputMethodService
876// AND a RTT call is active AND the source is VOICE_RECOGNITION
Shunkai Yao7c868ca2024-05-07 01:08:11 +0000877// OR The client is an active communication owner
878// AND is on TOP or latest started
Evan Severson1f700cd2021-02-10 13:10:37 -0800879// OR Any client
880// AND The assistant is not on TOP
881// AND is on TOP or latest started
882// AND there is no active privacy sensitive capture or call
883// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800884
Eric Laurent4e947da2019-10-17 15:24:06 -0700885
Eric Laurent4eb58f12018-12-07 16:41:02 -0800886 sp<AudioRecordClient> topActive;
887 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800888 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700889 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800890 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700891
Eric Laurenta46bedb2018-12-07 18:01:26 -0800892 nsecs_t topStartNs = 0;
893 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800894 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800895 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800896 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800897 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
898 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800899 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800900 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700901 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800902 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
903 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700904 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700905 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700906 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800907
Michael Groovercfd28302018-12-11 19:16:46 -0800908 // if Sensor Privacy is enabled then all recordings should be silenced.
909 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
910 silenceAllRecordings_l();
911 return;
912 }
913
Eric Laurente8c8b432018-10-17 10:08:02 -0700914 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
915 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000916 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
917 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800918 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700919 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800920 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700921
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700922 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700923 // clients which app is in IDLE state are not eligible for top active or
924 // latest active
925 if (appState == APP_STATE_IDLE) {
926 continue;
927 }
928
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700929 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700930 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800931 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700932 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700933 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800934 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800935 bool isPrivacySensitive =
936 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700937
Eric Laurentc21d5692020-02-25 10:24:36 -0800938 if (appState == APP_STATE_TOP) {
939 if (isPrivacySensitive) {
940 if (current->startTimeNs > topSensitiveStartNs) {
941 topSensitiveActive = current;
942 topSensitiveStartNs = current->startTimeNs;
943 }
944 } else {
945 if (current->startTimeNs > topStartNs) {
946 topActive = current;
947 topStartNs = current->startTimeNs;
948 }
949 }
950 if (isAssistant) {
951 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800952 if (isActiveAssistant) {
953 useActiveAssistantList = true;
954 } else if (!useActiveAssistantList) {
955 if (current->startTimeNs > latestAssistantStartNs) {
956 latestActiveAssistant = current;
957 latestAssistantStartNs = current->startTimeNs;
958 }
959 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800960 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800961 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800962 // Clients capturing for HOTWORD are not considered
963 // for latest active to avoid masking regular clients started before
964 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
965 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
966 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700967 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
968 // is marked latest sensitive active even if another app qualifies.
969 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700970 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700971 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700972 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000973 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700974 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700975 latestSensitiveActiveOrComm = current;
976 latestSensitiveStartNs = current->startTimeNs;
977 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800978 }
979 isSensitiveActive = true;
980 } else {
981 if (current->startTimeNs > latestStartNs) {
982 latestActive = current;
983 latestStartNs = current->startTimeNs;
984 }
985 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800986 }
987 }
François Gaffiedb1a4412023-10-10 17:32:33 +0000988 if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
989 !isVirtualSource(current->attributes.source)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700990 onlyHotwordActive = false;
991 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100992 if (currentUid == mPhoneStateOwnerUid &&
993 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700994 isPhoneStateOwnerActive = true;
995 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800996 }
997
Eric Laurent1ff16a72019-03-14 18:35:04 -0700998 // if no active client with UI on Top, consider latest active as top
999 if (topActive == nullptr) {
1000 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -08001001 topStartNs = latestStartNs;
1002 }
1003 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -07001004 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -08001005 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -07001006 } else if (latestSensitiveActiveOrComm != nullptr) {
1007 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
1008 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001009 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +00001010 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001011 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -07001012 topSensitiveActive = latestSensitiveActiveOrComm;
1013 topSensitiveStartNs = latestSensitiveStartNs;
1014 }
Eric Laurentc21d5692020-02-25 10:24:36 -08001015 }
1016
1017 // If both privacy sensitive and regular capture are active:
1018 // if the regular capture is privileged
1019 // allow concurrency
1020 // else
1021 // favor the privacy sensitive case
1022 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001023 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001024 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001025 }
1026
1027 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1028 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001029 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001030 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001031 if (!current->active) {
1032 continue;
1033 }
1034
Eric Laurent4eb58f12018-12-07 16:41:02 -08001035 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001036 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001037 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001038 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001039 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001040 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1041 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001042
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001043 // TODO: b/339112720
1044 // Refine this logic when we have the correct phone state owner UID. The current issue is
1045 // when a VOIP APP use Telecom API to manage calls, the mPhoneStateOwnerUid is AID_SYSTEM
1046 // instead of the actual VOIP APP UID, so isPhoneStateOwnerActive here is not accurate.
1047 const bool canCaptureIfInCallOrCommunication = [&](const auto& recordClient) REQUIRES(
1048 mMutex) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001049 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001050 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001051 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001052 bool canCaptureCommunication = recordClient->canCaptureOutput
1053 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001054 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001055 return !(isInCall && !canCaptureCall)
1056 && !(isInCommunication && !canCaptureCommunication);
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001057 }(current);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001058
1059 // By default allow capture if:
1060 // The assistant is not on TOP
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001061 // AND is on TOP or latest started
1062 // AND there is no active privacy sensitive capture or call
Eric Laurent1ff16a72019-03-14 18:35:04 -07001063 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001064 // The assistant is on TOP
1065 // AND is ongoing communication owner
1066 // AND is on TOP or latest started
1067 const bool allowSensitiveCapture =
Eric Laurent4ab18412022-11-07 16:25:32 +01001068 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001069 bool allowCapture = false;
1070 if (!isAssistantOnTop) {
1071 allowCapture = (isTopOrLatestActive || isTopOrLatestSensitive) &&
1072 allowSensitiveCapture && canCaptureIfInCallOrCommunication;
1073 } else {
1074 allowCapture = isInCommunication && isTopOrLatestSensitive &&
1075 canCaptureIfInCallOrCommunication;
1076 }
Eric Laurent2dc962b2019-03-01 08:25:25 -08001077
Eric Laurented726cc2021-07-01 14:26:41 +02001078 if (!current->hasOp()) {
1079 // Never allow capture if app op is denied
1080 allowCapture = false;
1081 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001082 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1083 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001084 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001085 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001086 // Active assistant list is not being used
1087 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001088 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001089 // OR there is no active privacy sensitive capture or call
1090 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1091 // AND is latest TOP assistant AND
1092 // uses VOICE_RECOGNITION OR uses HOTWORD
1093 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001094 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001095 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001096 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001097 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001098 } else if (allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001099 && canCaptureIfInCallOrCommunication) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001100 if (isTopOrLatestAssistant
1101 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1102 || source == AUDIO_SOURCE_HOTWORD)) {
1103 allowCapture = true;
1104 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1105 allowCapture = true;
1106 }
1107 }
1108 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1109 // For assistant on active list and on top allow capture if:
1110 // An accessibility service is on TOP
1111 // AND the source is VOICE_RECOGNITION or HOTWORD
1112 // OR there is no active privacy sensitive capture or call
1113 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1114 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1115 if (isA11yOnTop) {
1116 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1117 allowCapture = true;
1118 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001119 } else if (allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001120 && canCaptureIfInCallOrCommunication) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001121 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1122 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001123 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001124 }
1125 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001126 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001127 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001128 // The assistant is not on TOP
1129 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001130 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001131 // OR
1132 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1133 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001134 && allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001135 && canCaptureIfInCallOrCommunication) {
Eric Laurent47670c92019-08-28 16:59:05 -07001136 allowCapture = true;
1137 }
Eric Laurent589171c2019-07-25 18:04:29 -07001138 if (isA11yOnTop) {
1139 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1140 allowCapture = true;
1141 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001142 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001143 } else if (source == AUDIO_SOURCE_HOTWORD) {
1144 // For HOTWORD source allow capture when not on TOP if:
1145 // All active clients are using HOTWORD source
1146 // AND no call is active
1147 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001148 if (onlyHotwordActive
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001149 && canCaptureIfInCallOrCommunication) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001150 allowCapture = true;
1151 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001152 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001153 // For current InputMethodService allow capture if:
1154 // A RTT call is active AND the source is VOICE_RECOGNITION
1155 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1156 allowCapture = true;
1157 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001158 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001159 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001160 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001161 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001162 }
1163}
1164
Michael Groovercfd28302018-12-11 19:16:46 -08001165void AudioPolicyService::silenceAllRecordings_l() {
1166 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1167 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001168 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001169 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001170 }
Michael Groovercfd28302018-12-11 19:16:46 -08001171 }
1172}
1173
Eric Laurente8c8b432018-10-17 10:08:02 -07001174/* static */
1175app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001176
1177 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001178 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001179 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1180 // include persistent services
1181 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001182 }
1183 return APP_STATE_FOREGROUND;
1184}
1185
Eric Laurent4eb58f12018-12-07 16:41:02 -08001186/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001187bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001188{
1189 switch (source) {
1190 case AUDIO_SOURCE_VOICE_UPLINK:
1191 case AUDIO_SOURCE_VOICE_DOWNLINK:
1192 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001193 case AUDIO_SOURCE_REMOTE_SUBMIX:
1194 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001195 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001196 return true;
1197 default:
1198 break;
1199 }
1200 return false;
1201}
1202
Eric Laurent8c7ef892021-06-10 13:32:16 +02001203void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001204{
1205 AutoCallerClear acc;
1206
1207 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001208 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001209 }
1210 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1211 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001212 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001213 if (client->silenced != silenced) {
1214 if (client->active) {
1215 if (silenced) {
Marvin Raminb03b49f2024-04-04 16:25:31 +02001216 finishRecording(client->attributionSource, client->virtualDeviceId,
1217 client->attributes.source);
Eric Laurent8c7ef892021-06-10 13:32:16 +02001218 } else {
1219 std::stringstream msg;
1220 msg << "Audio recording un-silenced on session " << client->session;
Marvin Raminb03b49f2024-04-04 16:25:31 +02001221 if (!startRecording(client->attributionSource, client->virtualDeviceId,
1222 String16(msg.str().c_str()), client->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001223 silenced = true;
1224 }
1225 }
1226 }
1227 af->setRecordSilenced(client->portId, silenced);
1228 client->silenced = silenced;
1229 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001230 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001231}
1232
Glenn Kasten0f11b512014-01-31 16:18:54 -08001233status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Andy Hung79eacdb2023-11-30 19:34:24 -08001234NO_THREAD_SAFETY_ANALYSIS // update for trylock.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235{
Glenn Kasten44deb052012-02-05 18:09:08 -08001236 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 dumpPermissionDenial(fd);
1238 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001239 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 if (!locked) {
1241 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001242 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243 }
1244
1245 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001246
1247 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001248 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001249 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250 mAudioCommandThread->dump(fd);
1251 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001253 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001254 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001255 if (mOutputCommandThread != 0) {
1256 mOutputCommandThread->dump(fd);
1257 }
1258
Eric Laurentdce54a12014-03-10 12:19:46 -07001259 if (mAudioPolicyManager) {
1260 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001261 } else {
1262 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001263 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265
Kevin Rocard8be94972019-02-22 13:26:25 -08001266 mPackageManager.dump(fd);
1267
Andy Hung79eacdb2023-11-30 19:34:24 -08001268 dumpReleaseLock(mMutex, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001269
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001270 if (mSpatializer != nullptr) {
1271 std::string dumpString = mSpatializer->toString(1 /* level */);
1272 write(fd, dumpString.c_str(), dumpString.size());
1273 } else {
1274 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1275 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1276 }
1277
Andy Hungc747c532022-03-07 21:41:14 -08001278 {
1279 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1280 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1281 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 }
1284 return NO_ERROR;
1285}
1286
1287status_t AudioPolicyService::dumpPermissionDenial(int fd)
1288{
1289 const size_t SIZE = 256;
1290 char buffer[SIZE];
1291 String8 result;
1292 snprintf(buffer, SIZE, "Permission Denial: "
1293 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1294 IPCThreadState::self()->getCallingPid(),
1295 IPCThreadState::self()->getCallingUid());
1296 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001297 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298 return NO_ERROR;
1299}
1300
1301status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001302 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001303 // make sure transactions reserved to AudioFlinger do not come from other processes
1304 switch (code) {
1305 case TRANSACTION_startOutput:
1306 case TRANSACTION_stopOutput:
1307 case TRANSACTION_releaseOutput:
1308 case TRANSACTION_getInputForAttr:
1309 case TRANSACTION_startInput:
1310 case TRANSACTION_stopInput:
1311 case TRANSACTION_releaseInput:
1312 case TRANSACTION_getOutputForEffect:
1313 case TRANSACTION_registerEffect:
1314 case TRANSACTION_unregisterEffect:
1315 case TRANSACTION_setEffectEnabled:
1316 case TRANSACTION_getStrategyForStream:
1317 case TRANSACTION_getOutputForAttr:
1318 case TRANSACTION_moveEffectsToIo:
1319 ALOGW("%s: transaction %d received from PID %d",
1320 __func__, code, IPCThreadState::self()->getCallingPid());
1321 return INVALID_OPERATION;
1322 default:
1323 break;
1324 }
1325
1326 // make sure the following transactions come from system components
1327 switch (code) {
1328 case TRANSACTION_setDeviceConnectionState:
1329 case TRANSACTION_handleDeviceConfigChange:
1330 case TRANSACTION_setPhoneState:
1331//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1332// case TRANSACTION_setForceUse:
Vlad Popa87e0e582024-05-20 18:49:20 -07001333 case TRANSACTION_setDeviceAbsoluteVolumeEnabled:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001334 case TRANSACTION_initStreamVolume:
1335 case TRANSACTION_setStreamVolumeIndex:
1336 case TRANSACTION_setVolumeIndexForAttributes:
1337 case TRANSACTION_getStreamVolumeIndex:
1338 case TRANSACTION_getVolumeIndexForAttributes:
1339 case TRANSACTION_getMinVolumeIndexForAttributes:
1340 case TRANSACTION_getMaxVolumeIndexForAttributes:
1341 case TRANSACTION_isStreamActive:
1342 case TRANSACTION_isStreamActiveRemotely:
1343 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001344 case TRANSACTION_registerPolicyMixes:
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02001345 case TRANSACTION_updatePolicyMixes:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001346 case TRANSACTION_setMasterMono:
1347 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001348 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001349 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001350 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001351 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001352 case TRANSACTION_setA11yServicesUids:
1353 case TRANSACTION_setUidDeviceAffinities:
1354 case TRANSACTION_removeUidDeviceAffinities:
1355 case TRANSACTION_setUserIdDeviceAffinities:
1356 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001357 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001358 case TRANSACTION_listAudioVolumeGroups:
1359 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1360 case TRANSACTION_acquireSoundTriggerSession:
1361 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001362 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001363 case TRANSACTION_setRttEnabled:
1364 case TRANSACTION_isCallScreenModeSupported:
1365 case TRANSACTION_setDevicesRoleForStrategy:
1366 case TRANSACTION_setSupportedSystemUsages:
1367 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001368 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001369 case TRANSACTION_getDevicesForRoleAndStrategy:
1370 case TRANSACTION_getDevicesForAttributes:
1371 case TRANSACTION_setAllowedCapturePolicy:
1372 case TRANSACTION_onNewAudioModulesAvailable:
1373 case TRANSACTION_setCurrentImeUid:
1374 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1375 case TRANSACTION_setDevicesRoleForCapturePreset:
1376 case TRANSACTION_addDevicesRoleForCapturePreset:
1377 case TRANSACTION_removeDevicesRoleForCapturePreset:
1378 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001379 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001380 case TRANSACTION_getSpatializer:
1381 case TRANSACTION_setPreferredMixerAttributes:
Marvin Raminbdefaf02023-11-01 09:10:32 +01001382 case TRANSACTION_clearPreferredMixerAttributes:
1383 case TRANSACTION_getRegisteredPolicyMixes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001384 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1385 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1386 __func__, code, IPCThreadState::self()->getCallingPid(),
1387 IPCThreadState::self()->getCallingUid());
1388 return INVALID_OPERATION;
1389 }
1390 } break;
1391 default:
1392 break;
1393 }
1394
Atneya Nair9f91a5e2024-05-09 16:25:05 -07001395 switch (code) {
1396 case TRANSACTION_getPermissionController: {
1397 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1398 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1399 __func__, code, IPCThreadState::self()->getCallingPid(),
1400 IPCThreadState::self()->getCallingUid());
1401 return INVALID_OPERATION;
1402 }
1403 }
1404 }
1405
Andy Hungc747c532022-03-07 21:41:14 -08001406 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1407 mediautils::TimeCheck check(
1408 std::string("IAudioPolicyService::").append(methodName),
1409 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1410 if (timeout) {
1411 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1412 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1413 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1414 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1415 .record();
1416 } else {
1417 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1418 }
Andy Hung7cd77742024-08-06 15:17:16 -07001419 }, mediautils::TimeCheck::getDefaultTimeoutDuration(),
1420 mediautils::TimeCheck::getDefaultSecondChanceDuration(),
Atneya Nairc5b34362024-08-27 17:31:38 -07001421 !property_get_bool("audio.timecheck.disabled", false) /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001422
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001423 switch (code) {
1424 case SHELL_COMMAND_TRANSACTION: {
1425 int in = data.readFileDescriptor();
1426 int out = data.readFileDescriptor();
1427 int err = data.readFileDescriptor();
1428 int argc = data.readInt32();
1429 Vector<String16> args;
1430 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1431 args.add(data.readString16());
1432 }
1433 sp<IBinder> unusedCallback;
1434 sp<IResultReceiver> resultReceiver;
1435 status_t status;
1436 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1437 return status;
1438 }
1439 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1440 return status;
1441 }
1442 status = shellCommand(in, out, err, args);
1443 if (resultReceiver != nullptr) {
1444 resultReceiver->send(status);
1445 }
1446 return NO_ERROR;
1447 }
1448 }
1449
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1451}
1452
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001453// ------------------- Shell command implementation -------------------
1454
1455// NOTE: This is a remote API - make sure all args are validated
1456status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1457 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1458 return PERMISSION_DENIED;
1459 }
1460 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1461 return BAD_VALUE;
1462 }
Atneya Nair56a436a2024-04-03 11:11:58 -07001463 if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
Eric Laurent269acb42021-04-23 16:53:22 +02001464 purgePermissionCache();
1465 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001466 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001467 return BAD_VALUE;
1468}
1469
Eric Laurent0d13fea2022-11-04 17:12:08 +01001470status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1471 const audio_config_base_t& config,
1472 const audio_output_flags_t flags) {
1473 return mUsecaseValidator->registerStream(output, config, flags);
1474}
1475
1476status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1477 return mUsecaseValidator->unregisterStream(output);
1478}
1479
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001480// ----------- AudioPolicyService::UidPolicy implementation ----------
1481
1482void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001483 status_t res = mAm.linkToDeath(this);
1484 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001485 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001486 | ActivityManager::UID_OBSERVER_ACTIVE
1487 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001488 ActivityManager::PROCESS_STATE_UNKNOWN,
1489 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001490 if (!res) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001491 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001492 mObserverRegistered = true;
1493 } else {
1494 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001495
Steven Moreland2f348142019-07-02 15:59:07 -07001496 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001497 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001498}
1499
1500void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001501 mAm.unlinkToDeath(this);
1502 mAm.unregisterUidObserver(this);
Andy Hung79eacdb2023-11-30 19:34:24 -08001503 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001504 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001505}
1506
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001507void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001508 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001509 mCachedUids.clear();
1510 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001511}
1512
Eric Laurente8c8b432018-10-17 10:08:02 -07001513void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001514 bool needToReregister = false;
1515 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001516 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001517 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001518 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001519 if (needToReregister) {
1520 // Looks like ActivityManager has died previously, attempt to re-register.
1521 registerSelf();
1522 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001523}
1524
1525bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1526 if (isServiceUid(uid)) return true;
1527 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001528 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001529 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001530 // In an absense of the ActivityManager, assume everything to be active.
1531 if (!mObserverRegistered) return true;
1532 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001533 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001534 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001535 }
1536 }
1537 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001538 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001539 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001540 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001541 mCachedUids.insert(std::pair<uid_t,
1542 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1543 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001544 }
1545 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001546}
1547
Eric Laurente8c8b432018-10-17 10:08:02 -07001548int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1549 if (isServiceUid(uid)) {
1550 return ActivityManager::PROCESS_STATE_TOP;
1551 }
1552 checkRegistered();
1553 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001554 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001555 // In an absense of the ActivityManager, assume everything to be active.
1556 if (!mObserverRegistered) {
1557 return ActivityManager::PROCESS_STATE_TOP;
1558 }
1559 auto cacheIter = mCachedUids.find(uid);
1560 if (cacheIter != mCachedUids.end()) {
1561 if (cacheIter->second.first) {
1562 return cacheIter->second.second;
1563 } else {
1564 return ActivityManager::PROCESS_STATE_UNKNOWN;
1565 }
1566 }
1567 }
1568 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001569 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001570 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1571 if (active) {
1572 state = am.getUidProcessState(uid, String16("audioserver"));
1573 }
1574 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001575 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001576 mCachedUids.insert(std::pair<uid_t,
1577 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1578 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001579
Eric Laurente8c8b432018-10-17 10:08:02 -07001580 return state;
1581}
1582
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001583void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001584 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001585}
1586
1587void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001588 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001589}
1590
1591void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001592 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001593}
1594
Eric Laurente8c8b432018-10-17 10:08:02 -07001595void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1596 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001597 int64_t procStateSeq __unused,
1598 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001599 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1600 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001601 }
1602}
1603
Austin Borgerdddb7552023-03-30 17:53:01 -07001604void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001605}
1606
Eric Laurente8c8b432018-10-17 10:08:02 -07001607void AudioPolicyService::UidPolicy::notifyService() {
1608 sp<AudioPolicyService> service = mService.promote();
1609 if (service != nullptr) {
1610 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001611 }
1612}
1613
Eric Laurente8c8b432018-10-17 10:08:02 -07001614void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1615 std::pair<bool, int>> *uids,
1616 uid_t uid,
1617 bool active,
1618 int state,
1619 bool insert) {
1620 if (isServiceUid(uid)) {
1621 return;
1622 }
1623 bool wasActive = isUidActive(uid);
1624 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001625 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001626 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001627 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001628 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001629 if (wasActive != isUidActive(uid) || state != previousState) {
1630 notifyService();
1631 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001632}
1633
Eric Laurente8c8b432018-10-17 10:08:02 -07001634void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1635 std::pair<bool, int>> *uids,
1636 uid_t uid,
1637 bool active,
1638 int state,
1639 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001640 auto it = uids->find(uid);
1641 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001642 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001643 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1644 it->second.first = active;
1645 }
1646 if (it->second.first) {
1647 it->second.second = state;
1648 } else {
1649 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1650 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001651 } else {
1652 uids->erase(it);
1653 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001654 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1655 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1656 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001657 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001658}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659
Eric Laurent4eb58f12018-12-07 16:41:02 -08001660bool AudioPolicyService::UidPolicy::isA11yOnTop() {
Andy Hung79eacdb2023-11-30 19:34:24 -08001661 audio_utils::lock_guard _l(mMutex);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001662 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001663 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001664 continue;
1665 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001666 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1667 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001668 return true;
1669 }
1670 }
1671 return false;
1672}
1673
Eric Laurentb78763e2018-10-17 10:08:02 -07001674bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1675{
1676 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1677 return it != mA11yUids.end();
1678}
1679
Oscar Azucena829d90d2022-01-28 17:17:56 -08001680void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1681 mAssistantUids.clear();
1682 mAssistantUids = uids;
1683}
1684
1685bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1686{
1687 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1688 return it != mAssistantUids.end();
1689}
1690
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001691void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1692 mActiveAssistantUids = activeUids;
1693}
1694
1695bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1696{
1697 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1698 mActiveAssistantUids.end(), uid);
1699 return it != mActiveAssistantUids.end();
1700}
1701
Oscar Azucena829d90d2022-01-28 17:17:56 -08001702void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1703 const size_t SIZE = 256;
1704 char buffer[SIZE];
1705 String8 result;
1706 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1707 snprintf(buffer, SIZE, "\t%s: \n", title);
1708 result.append(buffer);
1709 int counter = 0;
1710 if (uids.empty()) {
1711 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1712 result.append(buffer);
1713 return;
1714 }
1715 for (const auto &uid : uids) {
1716 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1717 result.append(buffer);
1718 }
1719 };
1720
1721 snprintf(buffer, SIZE, "UID Policy:\n");
1722 result.append(buffer);
1723 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1724 result.append(buffer);
1725
1726 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001727 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001728
1729 appendUidsToResult("Accessibility UIDs", mA11yUids);
1730
1731 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1732 result.append(buffer);
1733
1734 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1735 result.append(buffer);
1736
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001737 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001738}
1739
Michael Groovercfd28302018-12-11 19:16:46 -08001740// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1741void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1742 SensorPrivacyManager spm;
1743 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1744 spm.addSensorPrivacyListener(this);
1745}
1746
1747void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1748 SensorPrivacyManager spm;
1749 spm.removeSensorPrivacyListener(this);
1750}
1751
1752bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1753 return mSensorPrivacyEnabled;
1754}
1755
Evan Seversond8dc6832022-01-27 10:47:03 -08001756binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1757 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001758 mSensorPrivacyEnabled = enabled;
1759 sp<AudioPolicyService> service = mService.promote();
1760 if (service != nullptr) {
1761 service->updateUidStates();
1762 }
1763 return binder::Status::ok();
1764}
1765
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1767
Eric Laurentbfb1b832013-01-07 09:53:42 -08001768AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1769 const wp<AudioPolicyService>& service)
1770 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772}
1773
1774
1775AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1776{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001777 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001778 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 }
1780 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781}
1782
1783void AudioPolicyService::AudioCommandThread::onFirstRef()
1784{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001785 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786}
1787
1788bool AudioPolicyService::AudioCommandThread::threadLoop()
1789{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001790 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791
Andy Hung79eacdb2023-11-30 19:34:24 -08001792 audio_utils::unique_lock ul(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 while (!exitPending())
1794 {
Eric Laurent59a89232014-06-08 14:14:17 -07001795 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001796 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001797 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 nsecs_t curTime = systemTime();
1799 // commands are sorted by increasing time stamp: execute them from index 0 and up
1800 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001801 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001803 if (mAudioCommands.isEmpty()) {
1804 ++numTimesBecameEmpty;
1805 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001806 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807
1808 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001810 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001811 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001812 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001813 ul.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001814 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1815 data->mVolume,
1816 data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001817 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818 }break;
Andy Hung6b137d12024-08-27 22:35:17 +00001819 case SET_PORTS_VOLUME: {
1820 VolumePortsData *data = (VolumePortsData *)command->mParam.get();
1821 ALOGV("AudioCommandThread() processing set volume Ports %s volume %f, \
1822 output %d", data->dumpPorts().c_str(), data->mVolume, data->mIO);
1823 ul.unlock();
1824 command->mStatus = AudioSystem::setPortsVolume(data->mPorts,
1825 data->mVolume,
1826 data->mIO);
1827 ul.lock();
1828 } break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001830 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001831 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001832 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001833 ul.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001834 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hung79eacdb2023-11-30 19:34:24 -08001835 ul.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001836 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001838 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001839 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001840 data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001841 ul.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001843 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001846 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001847 ALOGV("AudioCommandThread() processing stop output portId %d",
1848 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001849 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850 if (svc == 0) {
1851 break;
1852 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001853 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001854 svc->doStopOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001855 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856 }break;
1857 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001858 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001859 ALOGV("AudioCommandThread() processing release output portId %d",
1860 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001861 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862 if (svc == 0) {
1863 break;
1864 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001865 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001866 svc->doReleaseOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001867 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001869 case CREATE_AUDIO_PATCH: {
1870 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1871 ALOGV("AudioCommandThread() processing create audio patch");
1872 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1873 if (af == 0) {
1874 command->mStatus = PERMISSION_DENIED;
1875 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001876 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001877 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001878 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001879 }
1880 } break;
1881 case RELEASE_AUDIO_PATCH: {
1882 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1883 ALOGV("AudioCommandThread() processing release audio patch");
1884 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1885 if (af == 0) {
1886 command->mStatus = PERMISSION_DENIED;
1887 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001888 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001889 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001890 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001891 }
1892 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001893 case UPDATE_AUDIOPORT_LIST: {
1894 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001895 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001896 if (svc == 0) {
1897 break;
1898 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001899 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001900 svc->doOnAudioPortListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001901 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001902 }break;
1903 case UPDATE_AUDIOPATCH_LIST: {
1904 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001905 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001906 if (svc == 0) {
1907 break;
1908 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001909 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001910 svc->doOnAudioPatchListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001911 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001912 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001913 case CHANGED_AUDIOVOLUMEGROUP: {
1914 AudioVolumeGroupData *data =
1915 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1916 ALOGV("AudioCommandThread() processing update audio volume group");
1917 svc = mService.promote();
1918 if (svc == 0) {
1919 break;
1920 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001921 ul.unlock();
François Gaffiecfe17322018-11-07 13:41:29 +01001922 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
Andy Hung79eacdb2023-11-30 19:34:24 -08001923 ul.lock();
François Gaffiecfe17322018-11-07 13:41:29 +01001924 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001925 case SET_AUDIOPORT_CONFIG: {
1926 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1927 ALOGV("AudioCommandThread() processing set port config");
1928 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1929 if (af == 0) {
1930 command->mStatus = PERMISSION_DENIED;
1931 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001932 ul.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001933 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hung79eacdb2023-11-30 19:34:24 -08001934 ul.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001935 }
1936 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001937 case DYN_POLICY_MIX_STATE_UPDATE: {
1938 DynPolicyMixStateUpdateData *data =
1939 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001940 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001941 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07001942 svc = mService.promote();
1943 if (svc == 0) {
1944 break;
1945 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001946 ul.unlock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001947 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
Andy Hung79eacdb2023-11-30 19:34:24 -08001948 ul.lock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001949 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001950 case RECORDING_CONFIGURATION_UPDATE: {
1951 RecordingConfigurationUpdateData *data =
1952 (RecordingConfigurationUpdateData *)command->mParam.get();
1953 ALOGV("AudioCommandThread() processing recording configuration update");
1954 svc = mService.promote();
1955 if (svc == 0) {
1956 break;
1957 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001958 ul.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001959 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001960 &data->mClientConfig, data->mClientEffects,
1961 &data->mDeviceConfig, data->mEffects,
1962 data->mPatchHandle, data->mSource);
Andy Hung79eacdb2023-11-30 19:34:24 -08001963 ul.lock();
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001964 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001965 case SET_EFFECT_SUSPENDED: {
1966 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1967 ALOGV("AudioCommandThread() processing set effect suspended");
1968 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1969 if (af != 0) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001970 ul.unlock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001971 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
Andy Hung79eacdb2023-11-30 19:34:24 -08001972 ul.lock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001973 }
1974 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001975 case AUDIO_MODULES_UPDATE: {
1976 ALOGV("AudioCommandThread() processing audio modules update");
1977 svc = mService.promote();
1978 if (svc == 0) {
1979 break;
1980 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001981 ul.unlock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001982 svc->doOnNewAudioModulesAvailable();
Andy Hung79eacdb2023-11-30 19:34:24 -08001983 ul.lock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001984 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001985 case ROUTING_UPDATED: {
1986 ALOGV("AudioCommandThread() processing routing update");
1987 svc = mService.promote();
1988 if (svc == 0) {
1989 break;
1990 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001991 ul.unlock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001992 svc->doOnRoutingUpdated();
Andy Hung79eacdb2023-11-30 19:34:24 -08001993 ul.lock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001994 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001995
Eric Laurented726cc2021-07-01 14:26:41 +02001996 case UPDATE_UID_STATES: {
1997 ALOGV("AudioCommandThread() processing updateUID states");
1998 svc = mService.promote();
1999 if (svc == 0) {
2000 break;
2001 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002002 ul.unlock();
Eric Laurented726cc2021-07-01 14:26:41 +02002003 svc->updateUidStates();
Andy Hung79eacdb2023-11-30 19:34:24 -08002004 ul.lock();
Eric Laurented726cc2021-07-01 14:26:41 +02002005 } break;
2006
Eric Laurent15903592022-02-24 20:44:36 +01002007 case CHECK_SPATIALIZER_OUTPUT: {
2008 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002009 svc = mService.promote();
2010 if (svc == 0) {
2011 break;
2012 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002013 ul.unlock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002014 svc->doOnCheckSpatializer();
Andy Hung79eacdb2023-11-30 19:34:24 -08002015 ul.lock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002016 } break;
2017
Eric Laurent15903592022-02-24 20:44:36 +01002018 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2019 ALOGV("AudioCommandThread() processing update spatializer tracks");
2020 svc = mService.promote();
2021 if (svc == 0) {
2022 break;
2023 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002024 ul.unlock();
Eric Laurent15903592022-02-24 20:44:36 +01002025 svc->doOnUpdateActiveSpatializerTracks();
Andy Hung79eacdb2023-11-30 19:34:24 -08002026 ul.lock();
Eric Laurent15903592022-02-24 20:44:36 +01002027 } break;
2028
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002029 case VOL_RANGE_INIT_REQUEST: {
2030 ALOGV("AudioCommandThread() processing volume range init request");
2031 svc = mService.promote();
2032 if (svc == 0) {
2033 break;
2034 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002035 ul.unlock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002036 svc->doOnVolumeRangeInitRequest();
Andy Hung79eacdb2023-11-30 19:34:24 -08002037 ul.lock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002038 } break;
2039
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002041 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002043 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002044 audio_utils::lock_guard _l(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002045 if (command->mWaitStatus) {
2046 command->mWaitStatus = false;
Andy Hung79eacdb2023-11-30 19:34:24 -08002047 command->mCond.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002048 }
2049 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002050 waitTime = -1;
Andy Hung79eacdb2023-11-30 19:34:24 -08002051 // release ul before releasing strong reference on the service as
Zach Janga754b4f2015-10-27 01:29:34 +00002052 // AudioPolicyService destructor calls AudioCommandThread::exit() which
Andy Hung79eacdb2023-11-30 19:34:24 -08002053 // acquires ul.
2054 ul.unlock();
Zach Janga754b4f2015-10-27 01:29:34 +00002055 svc.clear();
Andy Hung79eacdb2023-11-30 19:34:24 -08002056 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 } else {
2058 waitTime = mAudioCommands[0]->mTime - curTime;
2059 break;
2060 }
2061 }
Zach Janga754b4f2015-10-27 01:29:34 +00002062
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002063 // release delayed commands wake lock as many times as we made the queue is
2064 // empty during popping.
2065 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002066 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002067 }
2068
2069 // At this stage we have either an empty command queue or the first command in the queue
2070 // has a finite delay. So unless we are exiting it is safe to wait.
2071 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002072 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002073 if (waitTime == -1) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002074 mWaitWorkCV.wait(ul);
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002075 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002076 // discard return value.
2077 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002078 }
Eric Laurent59a89232014-06-08 14:14:17 -07002079 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002081 // release delayed commands wake lock before quitting
2082 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002083 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 return false;
2086}
2087
2088status_t AudioPolicyService::AudioCommandThread::dump(int fd)
Andy Hung79eacdb2023-11-30 19:34:24 -08002089NO_THREAD_SAFETY_ANALYSIS // trylock
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090{
2091 const size_t SIZE = 256;
2092 char buffer[SIZE];
2093 String8 result;
2094
Andy Hung79eacdb2023-11-30 19:34:24 -08002095 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 if (!locked) {
2097 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002098 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 }
2100
2101 snprintf(buffer, SIZE, "- Commands:\n");
2102 result = String8(buffer);
2103 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002104 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 mAudioCommands[i]->dump(buffer, SIZE);
2106 result.append(buffer);
2107 }
2108 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002109 if (mLastCommand != 0) {
2110 mLastCommand->dump(buffer, SIZE);
2111 result.append(buffer);
2112 } else {
2113 result.append(" none\n");
2114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002116 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117
Andy Hung79eacdb2023-11-30 19:34:24 -08002118 dumpReleaseLock(mMutex, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119
2120 return NO_ERROR;
2121}
2122
Glenn Kastenfff6d712012-01-12 16:38:12 -08002123status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002124 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002125 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002126 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127{
Eric Laurent0ede8922014-05-09 18:04:42 -07002128 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002130 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131 data->mStream = stream;
2132 data->mVolume = volume;
2133 data->mIO = output;
2134 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002135 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002136 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002137 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002138 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139}
2140
Andy Hung6b137d12024-08-27 22:35:17 +00002141status_t AudioPolicyService::AudioCommandThread::volumePortsCommand(
2142 const std::vector<audio_port_handle_t> &ports, float volume, audio_io_handle_t output,
2143 int delayMs)
2144{
2145 sp<AudioCommand> command = new AudioCommand();
2146 command->mCommand = SET_PORTS_VOLUME;
2147 sp<VolumePortsData> data = new VolumePortsData();
2148 data->mPorts = ports;
2149 data->mVolume = volume;
2150 data->mIO = output;
2151 command->mParam = data;
2152 command->mWaitStatus = true;
2153 ALOGV("AudioCommandThread() adding set volume ports %s, volume %f, output %d",
2154 data->dumpPorts().c_str(), volume, output);
2155 return sendCommand(command, delayMs);
2156}
2157
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002158status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002159 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002160 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161{
Eric Laurent0ede8922014-05-09 18:04:42 -07002162 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002164 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002166 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002168 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002169 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002170 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002171 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172}
2173
2174status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2175{
Eric Laurent0ede8922014-05-09 18:04:42 -07002176 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002178 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 data->mVolume = volume;
2180 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002181 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002182 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002183 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184}
2185
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002186void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2187 audio_session_t sessionId,
2188 bool suspended)
2189{
2190 sp<AudioCommand> command = new AudioCommand();
2191 command->mCommand = SET_EFFECT_SUSPENDED;
2192 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2193 data->mEffectId = effectId;
2194 data->mSessionId = sessionId;
2195 data->mSuspended = suspended;
2196 command->mParam = data;
2197 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2198 effectId, sessionId, suspended);
2199 sendCommand(command);
2200}
2201
2202
Eric Laurentd7fe0862018-07-14 16:48:01 -07002203void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204{
Eric Laurent0ede8922014-05-09 18:04:42 -07002205 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002207 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002208 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002209 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002210 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002211 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002212}
2213
Eric Laurentd7fe0862018-07-14 16:48:01 -07002214void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002215{
Eric Laurent0ede8922014-05-09 18:04:42 -07002216 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002218 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002219 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002220 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002221 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002222 sendCommand(command);
2223}
2224
Eric Laurent951f4552014-05-20 10:48:17 -07002225status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2226 const struct audio_patch *patch,
2227 audio_patch_handle_t *handle,
2228 int delayMs)
2229{
2230 status_t status = NO_ERROR;
2231
2232 sp<AudioCommand> command = new AudioCommand();
2233 command->mCommand = CREATE_AUDIO_PATCH;
2234 CreateAudioPatchData *data = new CreateAudioPatchData();
2235 data->mPatch = *patch;
2236 data->mHandle = *handle;
2237 command->mParam = data;
2238 command->mWaitStatus = true;
2239 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2240 status = sendCommand(command, delayMs);
2241 if (status == NO_ERROR) {
2242 *handle = data->mHandle;
2243 }
2244 return status;
2245}
2246
2247status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2248 int delayMs)
2249{
2250 sp<AudioCommand> command = new AudioCommand();
2251 command->mCommand = RELEASE_AUDIO_PATCH;
2252 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2253 data->mHandle = handle;
2254 command->mParam = data;
2255 command->mWaitStatus = true;
2256 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2257 return sendCommand(command, delayMs);
2258}
2259
Eric Laurentb52c1522014-05-20 11:27:36 -07002260void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2261{
2262 sp<AudioCommand> command = new AudioCommand();
2263 command->mCommand = UPDATE_AUDIOPORT_LIST;
2264 ALOGV("AudioCommandThread() adding update audio port list");
2265 sendCommand(command);
2266}
2267
Eric Laurented726cc2021-07-01 14:26:41 +02002268void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2269{
2270 sp<AudioCommand> command = new AudioCommand();
2271 command->mCommand = UPDATE_UID_STATES;
2272 ALOGV("AudioCommandThread() adding update UID states");
2273 sendCommand(command);
2274}
2275
Eric Laurentb52c1522014-05-20 11:27:36 -07002276void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2277{
2278 sp<AudioCommand>command = new AudioCommand();
2279 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2280 ALOGV("AudioCommandThread() adding update audio patch list");
2281 sendCommand(command);
2282}
2283
François Gaffiecfe17322018-11-07 13:41:29 +01002284void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2285 int flags)
2286{
2287 sp<AudioCommand>command = new AudioCommand();
2288 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2289 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2290 data->mGroup = group;
2291 data->mFlags = flags;
2292 command->mParam = data;
2293 ALOGV("AudioCommandThread() adding audio volume group changed");
2294 sendCommand(command);
2295}
2296
Eric Laurente1715a42014-05-20 11:30:42 -07002297status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2298 const struct audio_port_config *config, int delayMs)
2299{
2300 sp<AudioCommand> command = new AudioCommand();
2301 command->mCommand = SET_AUDIOPORT_CONFIG;
2302 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2303 data->mConfig = *config;
2304 command->mParam = data;
2305 command->mWaitStatus = true;
2306 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2307 return sendCommand(command, delayMs);
2308}
2309
Jean-Michel Trivide801052015-04-14 19:10:14 -07002310void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002311 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002312{
2313 sp<AudioCommand> command = new AudioCommand();
2314 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2315 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2316 data->mRegId = regId;
2317 data->mState = state;
2318 command->mParam = data;
2319 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002320 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002321 sendCommand(command);
2322}
2323
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002324void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002325 int event,
2326 const record_client_info_t *clientInfo,
2327 const audio_config_base_t *clientConfig,
2328 std::vector<effect_descriptor_t> clientEffects,
2329 const audio_config_base_t *deviceConfig,
2330 std::vector<effect_descriptor_t> effects,
2331 audio_patch_handle_t patchHandle,
2332 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002333{
2334 sp<AudioCommand>command = new AudioCommand();
2335 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2336 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2337 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002338 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002339 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002340 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002341 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002342 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002343 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002344 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002345 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002346 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2347 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002348 sendCommand(command);
2349}
2350
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002351void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2352{
2353 sp<AudioCommand> command = new AudioCommand();
2354 command->mCommand = AUDIO_MODULES_UPDATE;
2355 sendCommand(command);
2356}
2357
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002358void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2359{
2360 sp<AudioCommand>command = new AudioCommand();
2361 command->mCommand = ROUTING_UPDATED;
2362 ALOGV("AudioCommandThread() adding routing update");
2363 sendCommand(command);
2364}
2365
Eric Laurent81dd0f52021-07-05 11:54:40 +02002366void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2367{
2368 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002369 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002370 ALOGV("AudioCommandThread() adding check spatializer");
2371 sendCommand(command);
2372}
2373
Eric Laurent15903592022-02-24 20:44:36 +01002374void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2375{
2376 sp<AudioCommand>command = new AudioCommand();
2377 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2378 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2379 sendCommand(command);
2380}
2381
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002382void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2383{
2384 sp<AudioCommand>command = new AudioCommand();
2385 command->mCommand = VOL_RANGE_INIT_REQUEST;
2386 ALOGV("AudioCommandThread() adding volume range init request");
2387 sendCommand(command);
2388}
2389
Eric Laurent0ede8922014-05-09 18:04:42 -07002390status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2391{
2392 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002393 audio_utils::lock_guard _l(mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002394 insertCommand_l(command, delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002395 mWaitWorkCV.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002396 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002397 audio_utils::unique_lock ul(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002398 while (command->mWaitStatus) {
2399 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002400 if (command->mCond.wait_for(
Andy Hung02ea2a02024-01-25 17:02:30 -08002401 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002402 command->mStatus = TIMED_OUT;
2403 command->mWaitStatus = false;
2404 }
2405 }
2406 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407}
2408
Andy Hung79eacdb2023-11-30 19:34:24 -08002409// insertCommand_l() must be called with mMutex held
Eric Laurent0ede8922014-05-09 18:04:42 -07002410void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002412 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002413 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 command->mTime = systemTime() + milliseconds(delayMs);
2415
2416 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002417 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002418 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 }
2420
2421 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002422 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002423 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2425 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002426
2427 // create audio patch or release audio patch commands are equivalent
2428 // with regard to filtering
2429 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2430 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2431 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2432 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2433 continue;
2434 }
2435 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436
2437 switch (command->mCommand) {
2438 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002439 ParametersData *data = (ParametersData *)command->mParam.get();
2440 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002442 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002443 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2445 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2446 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002447 String8 key;
2448 String8 value;
2449 param.getAt(j, key, value);
2450 for (size_t k = 0; k < param2.size(); k++) {
2451 String8 key2;
2452 String8 value2;
2453 param2.getAt(k, key2, value2);
2454 if (key2 == key) {
2455 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002456 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002457 break;
2458 }
2459 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 }
2461 // if all keys have been filtered out, remove the command.
2462 // otherwise, update the key value pairs
2463 if (param2.size() == 0) {
2464 removedCommands.add(command2);
2465 } else {
2466 data2->mKeyValuePairs = param2.toString();
2467 }
Eric Laurent21e54562013-09-23 12:08:05 -07002468 command->mTime = command2->mTime;
2469 // force delayMs to non 0 so that code below does not request to wait for
2470 // command status as the command is now delayed
2471 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 } break;
2473
2474 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002475 VolumeData *data = (VolumeData *)command->mParam.get();
2476 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 if (data->mIO != data2->mIO) break;
2478 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002479 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002480 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002482 command->mTime = command2->mTime;
2483 // force delayMs to non 0 so that code below does not request to wait for
2484 // command status as the command is now delayed
2485 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002487
Andy Hung6b137d12024-08-27 22:35:17 +00002488 case SET_PORTS_VOLUME: {
2489 VolumePortsData *data = (VolumePortsData *)command->mParam.get();
2490 VolumePortsData *data2 = (VolumePortsData *)command2->mParam.get();
2491 if (data->mIO != data2->mIO) break;
2492 // Can remove command only if port ids list is the same, otherwise, remove from
2493 // command 2 all port whose volume will be replaced with command 1 volume.
2494 std::vector<audio_port_handle_t> portsOnlyInCommand2{};
2495 std::copy_if(data2->mPorts.begin(), data2->mPorts.end(),
2496 std::back_inserter(portsOnlyInCommand2), [&](const auto &portId) {
2497 return std::find(data->mPorts.begin(), data->mPorts.end(), portId) ==
2498 data->mPorts.end();
2499 });
2500 if (!portsOnlyInCommand2.empty()) {
2501 data2->mPorts = portsOnlyInCommand2;
2502 break;
2503 }
2504 ALOGV("Filtering out volume command on output %d for ports %s",
2505 data->mIO, data->dumpPorts().c_str());
2506 removedCommands.add(command2);
2507 command->mTime = command2->mTime;
2508 // force delayMs to non 0 so that code below does not request to wait for
2509 // command status as the command is now delayed
2510 delayMs = 1;
2511 } break;
2512
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002513 case SET_VOICE_VOLUME: {
2514 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2515 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2516 ALOGV("Filtering out voice volume command value %f replaced by %f",
2517 data2->mVolume, data->mVolume);
2518 removedCommands.add(command2);
2519 command->mTime = command2->mTime;
2520 // force delayMs to non 0 so that code below does not request to wait for
2521 // command status as the command is now delayed
2522 delayMs = 1;
2523 } break;
2524
Eric Laurente45b48a2014-09-04 16:40:57 -07002525 case CREATE_AUDIO_PATCH:
2526 case RELEASE_AUDIO_PATCH: {
2527 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002528 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002529 if (command->mCommand == CREATE_AUDIO_PATCH) {
2530 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002531 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002532 } else {
2533 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002534 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002535 }
2536 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002537 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002538 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2539 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002540 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002541 } else {
2542 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002543 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002544 }
2545 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002546 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2547 same output. */
2548 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2549 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2550 bool isOutputDiff = false;
2551 if (patch.num_sources == patch2.num_sources) {
2552 for (unsigned count = 0; count < patch.num_sources; count++) {
2553 if (patch.sources[count].id != patch2.sources[count].id) {
2554 isOutputDiff = true;
2555 break;
2556 }
2557 }
2558 if (isOutputDiff)
2559 break;
2560 }
2561 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002562 ALOGV("Filtering out %s audio patch command for handle %d",
2563 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2564 removedCommands.add(command2);
2565 command->mTime = command2->mTime;
2566 // force delayMs to non 0 so that code below does not request to wait for
2567 // command status as the command is now delayed
2568 delayMs = 1;
2569 } break;
2570
Jean-Michel Trivide801052015-04-14 19:10:14 -07002571 case DYN_POLICY_MIX_STATE_UPDATE: {
2572
2573 } break;
2574
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002575 case RECORDING_CONFIGURATION_UPDATE: {
2576
2577 } break;
2578
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002579 case ROUTING_UPDATED: {
2580
2581 } break;
2582
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002583 case VOL_RANGE_INIT_REQUEST: {
2584 // command may come from different requests, do not filter
2585 } break;
2586
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 default:
2588 break;
2589 }
2590 }
2591
2592 // remove filtered commands
2593 for (size_t j = 0; j < removedCommands.size(); j++) {
2594 // removed commands always have time stamps greater than current command
2595 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002596 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002597 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598 mAudioCommands.removeAt(k);
2599 break;
2600 }
2601 }
2602 }
2603 removedCommands.clear();
2604
Eric Laurentaa79bef2015-01-15 14:33:51 -08002605 // Disable wait for status if delay is not 0.
2606 // Except for create audio patch command because the returned patch handle
2607 // is needed by audio policy manager
2608 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002609 command->mWaitStatus = false;
2610 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002611
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002613 ALOGV("inserting command: %d at index %zd, num commands %zu",
2614 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 mAudioCommands.insertAt(command, i + 1);
2616}
2617
2618void AudioPolicyService::AudioCommandThread::exit()
2619{
Steve Block3856b092011-10-20 11:56:00 +01002620 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002622 audio_utils::lock_guard _l(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 requestExit();
Andy Hung79eacdb2023-11-30 19:34:24 -08002624 mWaitWorkCV.notify_one();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 }
Zach Janga754b4f2015-10-27 01:29:34 +00002626 // Note that we can call it from the thread loop if all other references have been released
2627 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 requestExitAndWait();
2629}
2630
2631void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2632{
2633 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2634 mCommand,
2635 (int)ns2s(mTime),
2636 (int)ns2ms(mTime)%1000,
2637 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002638 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639}
2640
Dima Zavinfce7a472011-04-19 22:30:36 -07002641/******* helpers for the service_ops callbacks defined below *********/
2642void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2643 const char *keyValuePairs,
2644 int delayMs)
2645{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002646 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002647 delayMs);
2648}
2649
2650int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2651 float volume,
2652 audio_io_handle_t output,
2653 int delayMs)
2654{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002655 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002656 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002657}
2658
Andy Hung6b137d12024-08-27 22:35:17 +00002659int AudioPolicyService::setPortsVolume(const std::vector<audio_port_handle_t> &ports, float volume,
2660 audio_io_handle_t output, int delayMs)
2661{
2662 return (int)mAudioCommandThread->volumePortsCommand(ports, volume, output, delayMs);
2663}
2664
Dima Zavinfce7a472011-04-19 22:30:36 -07002665int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2666{
2667 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2668}
2669
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002670void AudioPolicyService::setEffectSuspended(int effectId,
2671 audio_session_t sessionId,
2672 bool suspended)
2673{
2674 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2675}
2676
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002677Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002678{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002679 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002680 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002681}
2682
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002683
Dima Zavinfce7a472011-04-19 22:30:36 -07002684extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002685audio_module_handle_t aps_load_hw_module(void *service __unused,
2686 const char *name);
2687audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002688 audio_devices_t *pDevices,
2689 uint32_t *pSamplingRate,
2690 audio_format_t *pFormat,
2691 audio_channel_mask_t *pChannelMask,
2692 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002693 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002694
Eric Laurent2d388ec2014-03-07 13:25:54 -08002695audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002696 audio_module_handle_t module,
2697 audio_devices_t *pDevices,
2698 uint32_t *pSamplingRate,
2699 audio_format_t *pFormat,
2700 audio_channel_mask_t *pChannelMask,
2701 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002702 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002703 const audio_offload_info_t *offloadInfo);
2704audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002705 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002706 audio_io_handle_t output2);
2707int aps_close_output(void *service __unused, audio_io_handle_t output);
2708int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2709int aps_restore_output(void *service __unused, audio_io_handle_t output);
2710audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002711 audio_devices_t *pDevices,
2712 uint32_t *pSamplingRate,
2713 audio_format_t *pFormat,
2714 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002715 audio_in_acoustics_t acoustics __unused);
2716audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002717 audio_module_handle_t module,
2718 audio_devices_t *pDevices,
2719 uint32_t *pSamplingRate,
2720 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002721 audio_channel_mask_t *pChannelMask);
2722int aps_close_input(void *service __unused, audio_io_handle_t input);
2723int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002724int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002725 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002726 audio_io_handle_t dst_output);
2727char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2728 const char *keys);
2729void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2730 const char *kv_pairs, int delay_ms);
2731int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002732 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002733 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002734int aps_set_voice_volume(void *service, float volume, int delay_ms);
2735};
Dima Zavinfce7a472011-04-19 22:30:36 -07002736
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002737} // namespace android