blob: aa83946f7ef9f80f5e463eea64893be64d03b678 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioPolicyService"
18//#define LOG_NDEBUG 0
19
Glenn Kasten153b9fe2013-07-15 11:23:36 -070020#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070021#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070022#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053023#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070024
25#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070026#include <binder/IServiceManager.h>
27#include <utils/Log.h>
28#include <cutils/properties.h>
29#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080030#include <binder/PermissionController.h>
31#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Atneya Nair5b1ed642023-06-23 14:43:37 -070034#include "AudioRecordClient.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080037#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070038#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080039#include <media/AudioParameter.h>
Andy Hungc747c532022-03-07 21:41:14 -080040#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070041#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080042#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080043#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
Dima Zavin64760242011-05-11 14:15:23 -070045#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070046#include <system/audio_policy.h>
Mikhail Naganov68e3f642023-04-28 13:06:32 -070047#include <AudioPolicyConfig.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053048#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080051using binder::Status;
Shunkai Yao49bc61f2023-10-10 19:31:10 +000052using media::audio::common::Spatialization;
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Glenn Kasten8dad0e32012-01-09 08:41:22 -080054static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
55static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053056static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mikhail Naganov959e2d02019-03-28 11:08:19 -070058static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Eric Laurent0ede8922014-05-09 18:04:42 -070060static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010061
Svet Ganovf4ddfef2018-01-16 07:37:58 -080062static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070063
Andy Hungc747c532022-03-07 21:41:14 -080064// Creates an association between Binder code to name for IAudioPolicyService.
65#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
66BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
67BINDER_METHOD_ENTRY(setDeviceConnectionState) \
68BINDER_METHOD_ENTRY(getDeviceConnectionState) \
69BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
70BINDER_METHOD_ENTRY(setPhoneState) \
71BINDER_METHOD_ENTRY(setForceUse) \
72BINDER_METHOD_ENTRY(getForceUse) \
73BINDER_METHOD_ENTRY(getOutput) \
74BINDER_METHOD_ENTRY(getOutputForAttr) \
75BINDER_METHOD_ENTRY(startOutput) \
76BINDER_METHOD_ENTRY(stopOutput) \
77BINDER_METHOD_ENTRY(releaseOutput) \
78BINDER_METHOD_ENTRY(getInputForAttr) \
79BINDER_METHOD_ENTRY(startInput) \
80BINDER_METHOD_ENTRY(stopInput) \
81BINDER_METHOD_ENTRY(releaseInput) \
82BINDER_METHOD_ENTRY(initStreamVolume) \
83BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
84BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
85BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
86BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
87BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
88BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getStrategyForStream) \
90BINDER_METHOD_ENTRY(getDevicesForAttributes) \
91BINDER_METHOD_ENTRY(getOutputForEffect) \
92BINDER_METHOD_ENTRY(registerEffect) \
93BINDER_METHOD_ENTRY(unregisterEffect) \
94BINDER_METHOD_ENTRY(setEffectEnabled) \
95BINDER_METHOD_ENTRY(moveEffectsToIo) \
96BINDER_METHOD_ENTRY(isStreamActive) \
97BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
98BINDER_METHOD_ENTRY(isSourceActive) \
99BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
100BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
101BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
102BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
103BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
104BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
105BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
106BINDER_METHOD_ENTRY(getOffloadSupport) \
107BINDER_METHOD_ENTRY(isDirectOutputSupported) \
108BINDER_METHOD_ENTRY(listAudioPorts) \
109BINDER_METHOD_ENTRY(getAudioPort) \
110BINDER_METHOD_ENTRY(createAudioPatch) \
111BINDER_METHOD_ENTRY(releaseAudioPatch) \
112BINDER_METHOD_ENTRY(listAudioPatches) \
113BINDER_METHOD_ENTRY(setAudioPortConfig) \
114BINDER_METHOD_ENTRY(registerClient) \
115BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
116BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
117BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
118BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
119BINDER_METHOD_ENTRY(getPhoneState) \
120BINDER_METHOD_ENTRY(registerPolicyMixes) \
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +0200121BINDER_METHOD_ENTRY(updatePolicyMixes) \
Andy Hungc747c532022-03-07 21:41:14 -0800122BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
123BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
124BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
125BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
126BINDER_METHOD_ENTRY(startAudioSource) \
127BINDER_METHOD_ENTRY(stopAudioSource) \
128BINDER_METHOD_ENTRY(setMasterMono) \
129BINDER_METHOD_ENTRY(getMasterMono) \
130BINDER_METHOD_ENTRY(getStreamVolumeDB) \
131BINDER_METHOD_ENTRY(getSurroundFormats) \
132BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
133BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
134BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
135BINDER_METHOD_ENTRY(setAssistantServicesUids) \
136BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
137BINDER_METHOD_ENTRY(setA11yServicesUids) \
138BINDER_METHOD_ENTRY(setCurrentImeUid) \
139BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
140BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800141BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800142BINDER_METHOD_ENTRY(listAudioProductStrategies) \
143BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
144BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
145BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
146BINDER_METHOD_ENTRY(setRttEnabled) \
147BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
148BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
149BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000150BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800151BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
152BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
153BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
154BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
155BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
156BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
157BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
158BINDER_METHOD_ENTRY(getSpatializer) \
159BINDER_METHOD_ENTRY(canBeSpatialized) \
160BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000161BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
162BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
163BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
164BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
165BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100166BINDER_METHOD_ENTRY(getRegisteredPolicyMixes) \
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700167BINDER_METHOD_ENTRY(getPermissionController) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100168 \
Andy Hungc747c532022-03-07 21:41:14 -0800169// singleton for Binder Method Statistics for IAudioPolicyService
170static auto& getIAudioPolicyServiceStatistics() {
171 using Code = int;
172
173#pragma push_macro("BINDER_METHOD_ENTRY")
174#undef BINDER_METHOD_ENTRY
175#define BINDER_METHOD_ENTRY(ENTRY) \
176 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
177
178 static mediautils::MethodStatistics<Code> methodStatistics{
179 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
180 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
181 };
182#pragma pop_macro("BINDER_METHOD_ENTRY")
183
184 return methodStatistics;
185}
186
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187// ----------------------------------------------------------------------------
188
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530189static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
190{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700191 AudioPolicyManager *apm = nullptr;
192 media::AudioPolicyConfig apmConfig;
193 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
194 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
195 LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
196 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
197 "Only default engine is currently supported with the AIDL HAL");
198 apm = new AudioPolicyManager(config,
199 loadApmEngineLibraryAndCreateEngine(
200 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
201 clientInterface);
202 } else {
203 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
204 apm = new AudioPolicyManager(config,
205 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
206 clientInterface);
207 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530208 status_t status = apm->initialize();
209 if (status != NO_ERROR) {
210 delete apm;
211 apm = nullptr;
212 }
213 return apm;
214}
215
216static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
217{
218 delete interface;
219}
220// ----------------------------------------------------------------------------
221
Mathias Agopian65ab4712010-07-14 17:59:35 -0700222AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700223 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700224 mAudioPolicyManager(NULL),
225 mAudioPolicyClient(NULL),
226 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530227 mCaptureStateNotifier(false),
228 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100229 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700230 mUsecaseValidator(media::createUsecaseValidator()),
231 mPermissionController(sp<NativePermissionController>::make())
232{
Andy Hung225aef62022-12-06 16:33:20 -0800233 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Andy Hung58b01b12024-03-26 18:04:29 -0700234 setInheritRt(true);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530235}
236
237void AudioPolicyService::loadAudioPolicyManager()
238{
239 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
240 if (mLibraryHandle != nullptr) {
241 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
242 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
243 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
244 const char *lastError = dlerror();
245 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
246 __func__, lastError != nullptr ? lastError : "no error");
247
248 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
249 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
250 lastError = dlerror();
251 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
252 __func__, lastError != nullptr ? lastError : "no error");
253 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
254 unloadAudioPolicyManager();
255 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
256 }
257 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700258}
259
260void AudioPolicyService::onFirstRef()
261{
Andy Hungd47aca22022-03-15 11:50:51 -0700262 // Log an AudioPolicy "constructor" mediametrics event on first ref.
263 // This records the time it takes to load the audio modules and devices.
264 mediametrics::Defer defer([beginNs = systemTime()] {
265 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
266 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
267 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
268 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700269 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800270 audio_utils::lock_guard _l(mMutex);
Eric Laurent93575202011-01-18 18:39:02 -0800271
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700272 // start audio commands thread
273 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
274 // start output activity command thread
275 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700276
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700277 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530278
279 loadAudioPolicyManager();
280 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700281 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200282
bryant_liuba2b4392014-06-11 16:49:30 +0800283 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000284 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
Andy Hungd3595ed2023-12-19 15:34:46 -0800285 auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
286 auto uidPolicy = sp<UidPolicy>::make(this);
287 auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700288 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800289 audio_utils::lock_guard _l(mMutex);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700290 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000291 mUidPolicy = uidPolicy;
292 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700293 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000294 uidPolicy->registerSelf();
295 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200296
Eric Laurent81dd0f52021-07-05 11:54:40 +0200297 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200298 if (mAudioPolicyManager != nullptr) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800299 audio_utils::lock_guard _l(mMutex);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200300 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
301 AudioDeviceTypeAddrVector devices;
302 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
303 if (hasSpatializer) {
Andy Hung1040da52023-12-06 20:59:06 -0800304 // Unlock as Spatializer::create() will use the callback and acquire the
305 // AudioPolicyService_Mutex.
Andy Hung79eacdb2023-11-30 19:34:24 -0800306 mMutex.unlock();
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000307 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Andy Hung79eacdb2023-11-30 19:34:24 -0800308 mMutex.lock();
Eric Laurent52b0bd52021-09-27 15:25:40 +0200309 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700310 if (mSpatializer == nullptr) {
311 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
312 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
313 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
314 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200315 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200316 AudioSystem::audioPolicyReady();
Andy Hungb08b3752024-01-09 19:05:23 -0800317}
318
Atneya Nair87818d32024-05-23 10:59:30 -0700319const IPermissionProvider& AudioPolicyService::getPermissionProvider() const {
320 return *mPermissionController;
321}
322
Andy Hungb08b3752024-01-09 19:05:23 -0800323void AudioPolicyService::onAudioSystemReady() {
324 sp<AudioPolicyEffects> audioPolicyEffects;
325 {
326 audio_utils::lock_guard _l(mMutex);
327
328 audioPolicyEffects = mAudioPolicyEffects;
329 }
330 audioPolicyEffects->initDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331}
332
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530333void AudioPolicyService::unloadAudioPolicyManager()
334{
335 ALOGV("%s ", __func__);
336 if (mLibraryHandle != nullptr) {
337 dlclose(mLibraryHandle);
338 }
339 mLibraryHandle = nullptr;
340 mCreateAudioPolicyManager = nullptr;
341 mDestroyAudioPolicyManager = nullptr;
342}
343
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344AudioPolicyService::~AudioPolicyService()
345{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700346 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700347 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700348
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530349 mDestroyAudioPolicyManager(mAudioPolicyManager);
350 unloadAudioPolicyManager();
351
Eric Laurentdce54a12014-03-10 12:19:46 -0700352 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700353
354 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800355 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800356
357 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800358 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000359
360 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800361 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700362}
363
364// A notification client is always registered by AudioSystem when the client process
365// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800366Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700367{
Eric Laurent12590252015-08-21 18:40:20 -0700368 if (client == 0) {
369 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800370 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700371 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800372 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700373
374 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800375 pid_t pid = IPCThreadState::self()->getCallingPid();
376 int64_t token = ((int64_t)uid<<32) | pid;
377
378 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700379 sp<NotificationClient> notificationClient = new NotificationClient(this,
380 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800381 uid,
382 pid);
383 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700384
luochaojiang908c7d72018-06-21 14:58:04 +0800385 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700386
Marco Nelissenf8880202014-11-14 07:58:25 -0800387 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700388 binder->linkToDeath(notificationClient);
389 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800390 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700391}
392
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800393Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700394{
Andy Hung79eacdb2023-11-30 19:34:24 -0800395 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurente8726fe2015-06-26 09:39:24 -0700396
397 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800398 pid_t pid = IPCThreadState::self()->getCallingPid();
399 int64_t token = ((int64_t)uid<<32) | pid;
400
401 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800402 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700403 }
luochaojiang908c7d72018-06-21 14:58:04 +0800404 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800405 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700406}
407
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800408Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100409{
Andy Hung79eacdb2023-11-30 19:34:24 -0800410 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100411
412 uid_t uid = IPCThreadState::self()->getCallingUid();
413 pid_t pid = IPCThreadState::self()->getCallingPid();
414 int64_t token = ((int64_t)uid<<32) | pid;
415
416 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800417 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100418 }
419 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800420 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100421}
422
Eric Laurentb52c1522014-05-20 11:27:36 -0700423// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800424void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700425{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000426 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800427 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800428 audio_utils::lock_guard _l(mNotificationClientsMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800429 int64_t token = ((int64_t)uid<<32) | pid;
430 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800431 for (size_t i = 0; i < mNotificationClients.size(); i++) {
432 if (mNotificationClients.valueAt(i)->uid() == uid) {
433 hasSameUid = true;
434 break;
435 }
436 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000437 }
438 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800439 audio_utils::lock_guard _l(mMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800440 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700441 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700442 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700443 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800444 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700445}
446
447void AudioPolicyService::onAudioPortListUpdate()
448{
449 mOutputCommandThread->updateAudioPortListCommand();
450}
451
452void AudioPolicyService::doOnAudioPortListUpdate()
453{
Andy Hung79eacdb2023-11-30 19:34:24 -0800454 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700455 for (size_t i = 0; i < mNotificationClients.size(); i++) {
456 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
457 }
458}
459
460void AudioPolicyService::onAudioPatchListUpdate()
461{
462 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463}
464
Eric Laurentb52c1522014-05-20 11:27:36 -0700465void AudioPolicyService::doOnAudioPatchListUpdate()
466{
Andy Hung79eacdb2023-11-30 19:34:24 -0800467 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700468 for (size_t i = 0; i < mNotificationClients.size(); i++) {
469 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
470 }
471}
472
François Gaffiecfe17322018-11-07 13:41:29 +0100473void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
474{
475 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
476}
477
478void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
479{
Andy Hung79eacdb2023-11-30 19:34:24 -0800480 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100481 for (size_t i = 0; i < mNotificationClients.size(); i++) {
482 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
483 }
484}
485
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700486void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700487{
488 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000489 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700490 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
491}
492
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700493void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700494{
Andy Hung79eacdb2023-11-30 19:34:24 -0800495 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700496 for (size_t i = 0; i < mNotificationClients.size(); i++) {
497 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
498 }
499}
500
Eric Laurenta9f86652018-11-28 17:23:11 -0800501void AudioPolicyService::onRecordingConfigurationUpdate(
502 int event,
503 const record_client_info_t *clientInfo,
504 const audio_config_base_t *clientConfig,
505 std::vector<effect_descriptor_t> clientEffects,
506 const audio_config_base_t *deviceConfig,
507 std::vector<effect_descriptor_t> effects,
508 audio_patch_handle_t patchHandle,
509 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800510{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800511 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800512 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800513}
514
Eric Laurenta9f86652018-11-28 17:23:11 -0800515void AudioPolicyService::doOnRecordingConfigurationUpdate(
516 int event,
517 const record_client_info_t *clientInfo,
518 const audio_config_base_t *clientConfig,
519 std::vector<effect_descriptor_t> clientEffects,
520 const audio_config_base_t *deviceConfig,
521 std::vector<effect_descriptor_t> effects,
522 audio_patch_handle_t patchHandle,
523 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800524{
Andy Hung79eacdb2023-11-30 19:34:24 -0800525 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800526 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800527 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800528 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800529 }
530}
531
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700532void AudioPolicyService::onRoutingUpdated()
533{
534 mOutputCommandThread->routingChangedCommand();
535}
536
537void AudioPolicyService::doOnRoutingUpdated()
538{
Andy Hung79eacdb2023-11-30 19:34:24 -0800539 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700540 for (size_t i = 0; i < mNotificationClients.size(); i++) {
541 mNotificationClients.valueAt(i)->onRoutingUpdated();
542 }
543}
544
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000545void AudioPolicyService::onVolumeRangeInitRequest()
546{
547 mOutputCommandThread->volRangeInitReqCommand();
548}
549
550void AudioPolicyService::doOnVolumeRangeInitRequest()
551{
Andy Hung79eacdb2023-11-30 19:34:24 -0800552 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000553 for (size_t i = 0; i < mNotificationClients.size(); i++) {
554 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
555 }
556}
557
Eric Laurent81dd0f52021-07-05 11:54:40 +0200558void AudioPolicyService::onCheckSpatializer()
559{
Andy Hung79eacdb2023-11-30 19:34:24 -0800560 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200561 onCheckSpatializer_l();
562}
563
564void AudioPolicyService::onCheckSpatializer_l()
565{
566 if (mSpatializer != nullptr) {
567 mOutputCommandThread->checkSpatializerCommand();
568 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200569}
570
571void AudioPolicyService::doOnCheckSpatializer()
572{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200573 ALOGV("%s mSpatializer %p level %d",
574 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200575
Eric Laurent39095982021-08-24 18:29:27 +0200576 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200577 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000578 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200579 audio_io_handle_t currentOutput = mSpatializer->getOutput();
580 audio_io_handle_t newOutput;
581 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
582 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200583
Andy Hung79eacdb2023-11-30 19:34:24 -0800584 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200585 status_t status =
586 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100587 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
588 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200589 if (status == NO_ERROR && currentOutput == newOutput) {
590 return;
591 }
Eric Laurent15903592022-02-24 20:44:36 +0100592 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Andy Hung79eacdb2023-11-30 19:34:24 -0800593 mMutex.unlock();
Eric Laurent39095982021-08-24 18:29:27 +0200594 // It is OK to call detachOutput() is none is already attached.
595 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200596 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
597 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200598 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800599 mMutex.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200600 if (status != NO_ERROR) {
601 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
602 }
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000603 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
604 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200605 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200606
Eric Laurent39095982021-08-24 18:29:27 +0200607 if (output != AUDIO_IO_HANDLE_NONE) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800608 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200609 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200610 }
611 }
612 }
613}
614
Eric Laurent11094172022-04-05 18:27:42 +0200615size_t AudioPolicyService::countActiveClientsOnOutput_l(
616 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100617 size_t count = 0;
618 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
619 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200620 if (client->io == output && client->active
621 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100622 count++;
623 }
624 }
625 return count;
626}
627
628void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
629 if (mSpatializer == nullptr) {
630 return;
631 }
632 mOutputCommandThread->updateActiveSpatializerTracksCommand();
633}
634
635void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
636{
Eric Laurent21270b62022-07-04 15:11:29 +0200637 if (mSpatializer == nullptr) {
638 return;
639 }
640 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200641 size_t activeClients;
642 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800643 audio_utils::lock_guard _l(mMutex);
Eric Laurent21270b62022-07-04 15:11:29 +0200644 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100645 }
Eric Laurent21270b62022-07-04 15:11:29 +0200646 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100647}
648
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800649status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
650 audio_patch_handle_t *handle,
651 int delayMs)
652{
653 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
654}
655
656status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
657 int delayMs)
658{
659 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
660}
661
Eric Laurente1715a42014-05-20 11:30:42 -0700662status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
663 int delayMs)
664{
665 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
666}
667
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800668AudioPolicyService::NotificationClient::NotificationClient(
669 const sp<AudioPolicyService>& service,
670 const sp<media::IAudioPolicyServiceClient>& client,
671 uid_t uid,
672 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800673 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100674 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700675{
676}
677
678AudioPolicyService::NotificationClient::~NotificationClient()
679{
680}
681
682void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
683{
684 sp<NotificationClient> keep(this);
685 sp<AudioPolicyService> service = mService.promote();
686 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800687 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700688 }
689}
690
691void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
692{
Eric Laurente8726fe2015-06-26 09:39:24 -0700693 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700694 mAudioPolicyServiceClient->onAudioPortListUpdate();
695 }
696}
697
698void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
699{
Eric Laurente8726fe2015-06-26 09:39:24 -0700700 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700701 mAudioPolicyServiceClient->onAudioPatchListUpdate();
702 }
703}
Eric Laurent57dae992011-07-24 13:36:09 -0700704
Pattydd807582021-11-04 21:01:03 +0800705void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100706 int flags)
707{
708 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
709 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
710 }
711}
712
713
Jean-Michel Trivide801052015-04-14 19:10:14 -0700714void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700715 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700716{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700717 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800718 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
719 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800720 }
721}
722
723void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800724 int event,
725 const record_client_info_t *clientInfo,
726 const audio_config_base_t *clientConfig,
727 std::vector<effect_descriptor_t> clientEffects,
728 const audio_config_base_t *deviceConfig,
729 std::vector<effect_descriptor_t> effects,
730 audio_patch_handle_t patchHandle,
731 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800732{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700733 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800734 status_t status = [&]() -> status_t {
735 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
736 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
737 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700738 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700739 legacy2aidl_audio_config_base_t_AudioConfigBase(
740 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800741 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
742 convertContainer<std::vector<media::EffectDescriptor>>(
743 clientEffects,
744 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700745 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700746 legacy2aidl_audio_config_base_t_AudioConfigBase(
747 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800748 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
749 convertContainer<std::vector<media::EffectDescriptor>>(
750 effects,
751 legacy2aidl_effect_descriptor_t_EffectDescriptor));
752 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
753 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700754 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
755 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800756 return aidl_utils::statusTFromBinderStatus(
757 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
758 clientInfoAidl,
759 clientConfigAidl,
760 clientEffectsAidl,
761 deviceConfigAidl,
762 effectsAidl,
763 patchHandleAidl,
764 sourceAidl));
765 }();
766 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700767 }
768}
769
Eric Laurente8726fe2015-06-26 09:39:24 -0700770void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
771{
772 mAudioPortCallbacksEnabled = enabled;
773}
774
François Gaffiecfe17322018-11-07 13:41:29 +0100775void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
776{
777 mAudioVolumeGroupCallbacksEnabled = enabled;
778}
Eric Laurente8726fe2015-06-26 09:39:24 -0700779
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700780void AudioPolicyService::NotificationClient::onRoutingUpdated()
781{
782 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
783 mAudioPolicyServiceClient->onRoutingUpdated();
784 }
785}
786
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000787void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
788{
789 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
790 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
791 }
792}
793
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700795 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700796 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797}
798
Andy Hung79eacdb2023-11-30 19:34:24 -0800799static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
800 RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000801{
802 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803}
804
805status_t AudioPolicyService::dumpInternals(int fd)
806{
807 const size_t SIZE = 256;
808 char buffer[SIZE];
809 String8 result;
810
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000811 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800812 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000813 std::stringstream msg;
814 size_t i = 0;
815 for (auto usage : mSupportedSystemUsages) {
816 if (i++ != 0) msg << ", ";
817 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
818 msg << strUsage;
819 } else {
820 msg << usage << " (unknown)";
821 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800822 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000823 if (i == 0) {
824 msg << "None";
825 }
826 msg << std::endl;
827 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800828
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000829 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800830
831 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 return NO_ERROR;
833}
834
Eric Laurente8c8b432018-10-17 10:08:02 -0700835void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800836{
Andy Hung79eacdb2023-11-30 19:34:24 -0800837 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -0700838 updateUidStates_l();
839}
840
841void AudioPolicyService::updateUidStates_l()
842{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800843// Go over all active clients and allow capture (does not force silence) in the
844// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800845// The client is in the active assistant list
846// AND is TOP
847// AND an accessibility service is TOP
848// AND source is either VOICE_RECOGNITION OR HOTWORD
849// OR there is no active privacy sensitive capture or call
850// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
851// AND source is VOICE_RECOGNITION OR HOTWORD
852// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800853// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700854// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800855// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800856// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800857// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
858// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800859// OR The client is an accessibility service
860// AND Is on TOP
861// AND the source is VOICE_RECOGNITION or HOTWORD
862// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700863// AND there is no active privacy sensitive capture or call
864// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800865// AND is on TOP
866// AND the source is VOICE_RECOGNITION or HOTWORD
867// OR the client source is virtual (remote submix, call audio TX or RX...)
868// OR the client source is HOTWORD
869// AND is on TOP
870// OR all active clients are using HOTWORD source
871// AND no call is active
872// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
873// OR the client is the current InputMethodService
874// AND a RTT call is active AND the source is VOICE_RECOGNITION
875// OR Any client
876// AND The assistant is not on TOP
877// AND is on TOP or latest started
878// AND there is no active privacy sensitive capture or call
879// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800880
Eric Laurent4e947da2019-10-17 15:24:06 -0700881
Eric Laurent4eb58f12018-12-07 16:41:02 -0800882 sp<AudioRecordClient> topActive;
883 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800884 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700885 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800886 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700887
Eric Laurenta46bedb2018-12-07 18:01:26 -0800888 nsecs_t topStartNs = 0;
889 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800890 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800891 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800892 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800893 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
894 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800895 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800896 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700897 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800898 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
899 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700900 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700901 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700902 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800903
Michael Groovercfd28302018-12-11 19:16:46 -0800904 // if Sensor Privacy is enabled then all recordings should be silenced.
905 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
906 silenceAllRecordings_l();
907 return;
908 }
909
Eric Laurente8c8b432018-10-17 10:08:02 -0700910 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
911 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000912 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
913 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800914 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700915 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800916 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700917
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700918 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700919 // clients which app is in IDLE state are not eligible for top active or
920 // latest active
921 if (appState == APP_STATE_IDLE) {
922 continue;
923 }
924
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700925 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700926 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800927 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700928 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700929 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800930 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800931 bool isPrivacySensitive =
932 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700933
Eric Laurentc21d5692020-02-25 10:24:36 -0800934 if (appState == APP_STATE_TOP) {
935 if (isPrivacySensitive) {
936 if (current->startTimeNs > topSensitiveStartNs) {
937 topSensitiveActive = current;
938 topSensitiveStartNs = current->startTimeNs;
939 }
940 } else {
941 if (current->startTimeNs > topStartNs) {
942 topActive = current;
943 topStartNs = current->startTimeNs;
944 }
945 }
946 if (isAssistant) {
947 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800948 if (isActiveAssistant) {
949 useActiveAssistantList = true;
950 } else if (!useActiveAssistantList) {
951 if (current->startTimeNs > latestAssistantStartNs) {
952 latestActiveAssistant = current;
953 latestAssistantStartNs = current->startTimeNs;
954 }
955 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800956 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800957 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800958 // Clients capturing for HOTWORD are not considered
959 // for latest active to avoid masking regular clients started before
960 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
961 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
962 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700963 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
964 // is marked latest sensitive active even if another app qualifies.
965 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700966 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700967 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700968 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000969 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700970 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700971 latestSensitiveActiveOrComm = current;
972 latestSensitiveStartNs = current->startTimeNs;
973 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800974 }
975 isSensitiveActive = true;
976 } else {
977 if (current->startTimeNs > latestStartNs) {
978 latestActive = current;
979 latestStartNs = current->startTimeNs;
980 }
981 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800982 }
983 }
François Gaffiedb1a4412023-10-10 17:32:33 +0000984 if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
985 !isVirtualSource(current->attributes.source)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700986 onlyHotwordActive = false;
987 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100988 if (currentUid == mPhoneStateOwnerUid &&
989 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700990 isPhoneStateOwnerActive = true;
991 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800992 }
993
Eric Laurent1ff16a72019-03-14 18:35:04 -0700994 // if no active client with UI on Top, consider latest active as top
995 if (topActive == nullptr) {
996 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800997 topStartNs = latestStartNs;
998 }
999 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -07001000 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -08001001 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -07001002 } else if (latestSensitiveActiveOrComm != nullptr) {
1003 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
1004 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001005 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +00001006 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001007 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -07001008 topSensitiveActive = latestSensitiveActiveOrComm;
1009 topSensitiveStartNs = latestSensitiveStartNs;
1010 }
Eric Laurentc21d5692020-02-25 10:24:36 -08001011 }
1012
1013 // If both privacy sensitive and regular capture are active:
1014 // if the regular capture is privileged
1015 // allow concurrency
1016 // else
1017 // favor the privacy sensitive case
1018 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001019 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001020 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001021 }
1022
1023 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1024 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001025 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001026 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001027 if (!current->active) {
1028 continue;
1029 }
1030
Eric Laurent4eb58f12018-12-07 16:41:02 -08001031 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001032 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001033 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001034 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001035 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001036 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1037 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001038
Andy Hung79eacdb2023-11-30 19:34:24 -08001039 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mMutex) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001040 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001041 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001042 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001043 bool canCaptureCommunication = recordClient->canCaptureOutput
1044 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001045 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001046 return !(isInCall && !canCaptureCall)
1047 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001048 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001049
1050 // By default allow capture if:
1051 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001052 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001053 // AND there is no active privacy sensitive capture or call
1054 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001055 bool allowSensitiveCapture =
1056 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001057 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001058 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001059 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001060 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001061
Eric Laurented726cc2021-07-01 14:26:41 +02001062 if (!current->hasOp()) {
1063 // Never allow capture if app op is denied
1064 allowCapture = false;
1065 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001066 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1067 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001068 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001069 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001070 // Active assistant list is not being used
1071 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001072 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001073 // OR there is no active privacy sensitive capture or call
1074 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1075 // AND is latest TOP assistant AND
1076 // uses VOICE_RECOGNITION OR uses HOTWORD
1077 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001078 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001079 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001080 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001081 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001082 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001083 && canCaptureIfInCallOrCommunication(current)) {
1084 if (isTopOrLatestAssistant
1085 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1086 || source == AUDIO_SOURCE_HOTWORD)) {
1087 allowCapture = true;
1088 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1089 allowCapture = true;
1090 }
1091 }
1092 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1093 // For assistant on active list and on top allow capture if:
1094 // An accessibility service is on TOP
1095 // AND the source is VOICE_RECOGNITION or HOTWORD
1096 // OR there is no active privacy sensitive capture or call
1097 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1098 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1099 if (isA11yOnTop) {
1100 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1101 allowCapture = true;
1102 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001103 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001104 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001105 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1106 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001107 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001108 }
1109 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001110 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001111 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001112 // The assistant is not on TOP
1113 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001114 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001115 // OR
1116 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1117 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001118 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001119 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001120 allowCapture = true;
1121 }
Eric Laurent589171c2019-07-25 18:04:29 -07001122 if (isA11yOnTop) {
1123 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1124 allowCapture = true;
1125 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001126 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001127 } else if (source == AUDIO_SOURCE_HOTWORD) {
1128 // For HOTWORD source allow capture when not on TOP if:
1129 // All active clients are using HOTWORD source
1130 // AND no call is active
1131 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001132 if (onlyHotwordActive
1133 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001134 allowCapture = true;
1135 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001136 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001137 // For current InputMethodService allow capture if:
1138 // A RTT call is active AND the source is VOICE_RECOGNITION
1139 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1140 allowCapture = true;
1141 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001142 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001143 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001144 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001145 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001146 }
1147}
1148
Michael Groovercfd28302018-12-11 19:16:46 -08001149void AudioPolicyService::silenceAllRecordings_l() {
1150 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1151 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001152 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001153 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001154 }
Michael Groovercfd28302018-12-11 19:16:46 -08001155 }
1156}
1157
Eric Laurente8c8b432018-10-17 10:08:02 -07001158/* static */
1159app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001160
1161 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001162 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001163 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1164 // include persistent services
1165 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001166 }
1167 return APP_STATE_FOREGROUND;
1168}
1169
Eric Laurent4eb58f12018-12-07 16:41:02 -08001170/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001171bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001172{
1173 switch (source) {
1174 case AUDIO_SOURCE_VOICE_UPLINK:
1175 case AUDIO_SOURCE_VOICE_DOWNLINK:
1176 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001177 case AUDIO_SOURCE_REMOTE_SUBMIX:
1178 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001179 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001180 return true;
1181 default:
1182 break;
1183 }
1184 return false;
1185}
1186
Eric Laurent8c7ef892021-06-10 13:32:16 +02001187void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001188{
1189 AutoCallerClear acc;
1190
1191 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001192 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001193 }
1194 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1195 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001196 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001197 if (client->silenced != silenced) {
1198 if (client->active) {
1199 if (silenced) {
Marvin Raminb03b49f2024-04-04 16:25:31 +02001200 finishRecording(client->attributionSource, client->virtualDeviceId,
1201 client->attributes.source);
Eric Laurent8c7ef892021-06-10 13:32:16 +02001202 } else {
1203 std::stringstream msg;
1204 msg << "Audio recording un-silenced on session " << client->session;
Marvin Raminb03b49f2024-04-04 16:25:31 +02001205 if (!startRecording(client->attributionSource, client->virtualDeviceId,
1206 String16(msg.str().c_str()), client->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001207 silenced = true;
1208 }
1209 }
1210 }
1211 af->setRecordSilenced(client->portId, silenced);
1212 client->silenced = silenced;
1213 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001214 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001215}
1216
Glenn Kasten0f11b512014-01-31 16:18:54 -08001217status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Andy Hung79eacdb2023-11-30 19:34:24 -08001218NO_THREAD_SAFETY_ANALYSIS // update for trylock.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219{
Glenn Kasten44deb052012-02-05 18:09:08 -08001220 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 dumpPermissionDenial(fd);
1222 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001223 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 if (!locked) {
1225 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001226 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 }
1228
1229 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001230
1231 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001232 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001233 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 mAudioCommandThread->dump(fd);
1235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001237 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001238 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001239 if (mOutputCommandThread != 0) {
1240 mOutputCommandThread->dump(fd);
1241 }
1242
Eric Laurentdce54a12014-03-10 12:19:46 -07001243 if (mAudioPolicyManager) {
1244 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001245 } else {
1246 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001247 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249
Kevin Rocard8be94972019-02-22 13:26:25 -08001250 mPackageManager.dump(fd);
1251
Andy Hung79eacdb2023-11-30 19:34:24 -08001252 dumpReleaseLock(mMutex, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001253
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001254 if (mSpatializer != nullptr) {
1255 std::string dumpString = mSpatializer->toString(1 /* level */);
1256 write(fd, dumpString.c_str(), dumpString.size());
1257 } else {
1258 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1259 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1260 }
1261
Andy Hungc747c532022-03-07 21:41:14 -08001262 {
1263 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1264 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1265 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1266 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267 }
1268 return NO_ERROR;
1269}
1270
1271status_t AudioPolicyService::dumpPermissionDenial(int fd)
1272{
1273 const size_t SIZE = 256;
1274 char buffer[SIZE];
1275 String8 result;
1276 snprintf(buffer, SIZE, "Permission Denial: "
1277 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1278 IPCThreadState::self()->getCallingPid(),
1279 IPCThreadState::self()->getCallingUid());
1280 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001281 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282 return NO_ERROR;
1283}
1284
1285status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001286 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001287 // make sure transactions reserved to AudioFlinger do not come from other processes
1288 switch (code) {
1289 case TRANSACTION_startOutput:
1290 case TRANSACTION_stopOutput:
1291 case TRANSACTION_releaseOutput:
1292 case TRANSACTION_getInputForAttr:
1293 case TRANSACTION_startInput:
1294 case TRANSACTION_stopInput:
1295 case TRANSACTION_releaseInput:
1296 case TRANSACTION_getOutputForEffect:
1297 case TRANSACTION_registerEffect:
1298 case TRANSACTION_unregisterEffect:
1299 case TRANSACTION_setEffectEnabled:
1300 case TRANSACTION_getStrategyForStream:
1301 case TRANSACTION_getOutputForAttr:
1302 case TRANSACTION_moveEffectsToIo:
1303 ALOGW("%s: transaction %d received from PID %d",
1304 __func__, code, IPCThreadState::self()->getCallingPid());
1305 return INVALID_OPERATION;
1306 default:
1307 break;
1308 }
1309
1310 // make sure the following transactions come from system components
1311 switch (code) {
1312 case TRANSACTION_setDeviceConnectionState:
1313 case TRANSACTION_handleDeviceConfigChange:
1314 case TRANSACTION_setPhoneState:
1315//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1316// case TRANSACTION_setForceUse:
1317 case TRANSACTION_initStreamVolume:
1318 case TRANSACTION_setStreamVolumeIndex:
1319 case TRANSACTION_setVolumeIndexForAttributes:
1320 case TRANSACTION_getStreamVolumeIndex:
1321 case TRANSACTION_getVolumeIndexForAttributes:
1322 case TRANSACTION_getMinVolumeIndexForAttributes:
1323 case TRANSACTION_getMaxVolumeIndexForAttributes:
1324 case TRANSACTION_isStreamActive:
1325 case TRANSACTION_isStreamActiveRemotely:
1326 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001327 case TRANSACTION_registerPolicyMixes:
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02001328 case TRANSACTION_updatePolicyMixes:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001329 case TRANSACTION_setMasterMono:
1330 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001331 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001332 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001333 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001334 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001335 case TRANSACTION_setA11yServicesUids:
1336 case TRANSACTION_setUidDeviceAffinities:
1337 case TRANSACTION_removeUidDeviceAffinities:
1338 case TRANSACTION_setUserIdDeviceAffinities:
1339 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001340 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001341 case TRANSACTION_listAudioVolumeGroups:
1342 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1343 case TRANSACTION_acquireSoundTriggerSession:
1344 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001345 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001346 case TRANSACTION_setRttEnabled:
1347 case TRANSACTION_isCallScreenModeSupported:
1348 case TRANSACTION_setDevicesRoleForStrategy:
1349 case TRANSACTION_setSupportedSystemUsages:
1350 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001351 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001352 case TRANSACTION_getDevicesForRoleAndStrategy:
1353 case TRANSACTION_getDevicesForAttributes:
1354 case TRANSACTION_setAllowedCapturePolicy:
1355 case TRANSACTION_onNewAudioModulesAvailable:
1356 case TRANSACTION_setCurrentImeUid:
1357 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1358 case TRANSACTION_setDevicesRoleForCapturePreset:
1359 case TRANSACTION_addDevicesRoleForCapturePreset:
1360 case TRANSACTION_removeDevicesRoleForCapturePreset:
1361 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001362 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001363 case TRANSACTION_getSpatializer:
1364 case TRANSACTION_setPreferredMixerAttributes:
Marvin Raminbdefaf02023-11-01 09:10:32 +01001365 case TRANSACTION_clearPreferredMixerAttributes:
1366 case TRANSACTION_getRegisteredPolicyMixes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001367 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1368 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1369 __func__, code, IPCThreadState::self()->getCallingPid(),
1370 IPCThreadState::self()->getCallingUid());
1371 return INVALID_OPERATION;
1372 }
1373 } break;
1374 default:
1375 break;
1376 }
1377
Atneya Nair9f91a5e2024-05-09 16:25:05 -07001378 switch (code) {
1379 case TRANSACTION_getPermissionController: {
1380 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1381 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1382 __func__, code, IPCThreadState::self()->getCallingPid(),
1383 IPCThreadState::self()->getCallingUid());
1384 return INVALID_OPERATION;
1385 }
1386 }
1387 }
1388
Andy Hungc747c532022-03-07 21:41:14 -08001389 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1390 mediautils::TimeCheck check(
1391 std::string("IAudioPolicyService::").append(methodName),
1392 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1393 if (timeout) {
1394 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1395 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1396 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1397 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1398 .record();
1399 } else {
1400 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1401 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001402 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1403 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1404 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001405
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001406 switch (code) {
1407 case SHELL_COMMAND_TRANSACTION: {
1408 int in = data.readFileDescriptor();
1409 int out = data.readFileDescriptor();
1410 int err = data.readFileDescriptor();
1411 int argc = data.readInt32();
1412 Vector<String16> args;
1413 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1414 args.add(data.readString16());
1415 }
1416 sp<IBinder> unusedCallback;
1417 sp<IResultReceiver> resultReceiver;
1418 status_t status;
1419 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1420 return status;
1421 }
1422 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1423 return status;
1424 }
1425 status = shellCommand(in, out, err, args);
1426 if (resultReceiver != nullptr) {
1427 resultReceiver->send(status);
1428 }
1429 return NO_ERROR;
1430 }
1431 }
1432
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1434}
1435
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001436// ------------------- Shell command implementation -------------------
1437
1438// NOTE: This is a remote API - make sure all args are validated
1439status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1440 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1441 return PERMISSION_DENIED;
1442 }
1443 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1444 return BAD_VALUE;
1445 }
Atneya Nair56a436a2024-04-03 11:11:58 -07001446 if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
Eric Laurent269acb42021-04-23 16:53:22 +02001447 purgePermissionCache();
1448 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001449 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001450 return BAD_VALUE;
1451}
1452
Eric Laurent0d13fea2022-11-04 17:12:08 +01001453status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1454 const audio_config_base_t& config,
1455 const audio_output_flags_t flags) {
1456 return mUsecaseValidator->registerStream(output, config, flags);
1457}
1458
1459status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1460 return mUsecaseValidator->unregisterStream(output);
1461}
1462
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001463// ----------- AudioPolicyService::UidPolicy implementation ----------
1464
1465void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001466 status_t res = mAm.linkToDeath(this);
1467 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001468 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001469 | ActivityManager::UID_OBSERVER_ACTIVE
1470 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001471 ActivityManager::PROCESS_STATE_UNKNOWN,
1472 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001473 if (!res) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001474 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001475 mObserverRegistered = true;
1476 } else {
1477 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001478
Steven Moreland2f348142019-07-02 15:59:07 -07001479 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001480 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001481}
1482
1483void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001484 mAm.unlinkToDeath(this);
1485 mAm.unregisterUidObserver(this);
Andy Hung79eacdb2023-11-30 19:34:24 -08001486 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001487 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001488}
1489
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001490void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001491 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001492 mCachedUids.clear();
1493 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001494}
1495
Eric Laurente8c8b432018-10-17 10:08:02 -07001496void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001497 bool needToReregister = false;
1498 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001499 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001500 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001501 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001502 if (needToReregister) {
1503 // Looks like ActivityManager has died previously, attempt to re-register.
1504 registerSelf();
1505 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001506}
1507
1508bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1509 if (isServiceUid(uid)) return true;
1510 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001511 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001512 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001513 // In an absense of the ActivityManager, assume everything to be active.
1514 if (!mObserverRegistered) return true;
1515 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001516 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001517 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001518 }
1519 }
1520 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001521 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001522 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001523 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001524 mCachedUids.insert(std::pair<uid_t,
1525 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1526 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001527 }
1528 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001529}
1530
Eric Laurente8c8b432018-10-17 10:08:02 -07001531int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1532 if (isServiceUid(uid)) {
1533 return ActivityManager::PROCESS_STATE_TOP;
1534 }
1535 checkRegistered();
1536 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001537 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001538 // In an absense of the ActivityManager, assume everything to be active.
1539 if (!mObserverRegistered) {
1540 return ActivityManager::PROCESS_STATE_TOP;
1541 }
1542 auto cacheIter = mCachedUids.find(uid);
1543 if (cacheIter != mCachedUids.end()) {
1544 if (cacheIter->second.first) {
1545 return cacheIter->second.second;
1546 } else {
1547 return ActivityManager::PROCESS_STATE_UNKNOWN;
1548 }
1549 }
1550 }
1551 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001552 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001553 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1554 if (active) {
1555 state = am.getUidProcessState(uid, String16("audioserver"));
1556 }
1557 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001558 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001559 mCachedUids.insert(std::pair<uid_t,
1560 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1561 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001562
Eric Laurente8c8b432018-10-17 10:08:02 -07001563 return state;
1564}
1565
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001566void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001567 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001568}
1569
1570void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001571 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001572}
1573
1574void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001575 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001576}
1577
Eric Laurente8c8b432018-10-17 10:08:02 -07001578void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1579 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001580 int64_t procStateSeq __unused,
1581 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001582 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1583 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001584 }
1585}
1586
Austin Borgerdddb7552023-03-30 17:53:01 -07001587void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001588}
1589
Eric Laurente8c8b432018-10-17 10:08:02 -07001590void AudioPolicyService::UidPolicy::notifyService() {
1591 sp<AudioPolicyService> service = mService.promote();
1592 if (service != nullptr) {
1593 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001594 }
1595}
1596
Eric Laurente8c8b432018-10-17 10:08:02 -07001597void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1598 std::pair<bool, int>> *uids,
1599 uid_t uid,
1600 bool active,
1601 int state,
1602 bool insert) {
1603 if (isServiceUid(uid)) {
1604 return;
1605 }
1606 bool wasActive = isUidActive(uid);
1607 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001608 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001609 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001610 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001611 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001612 if (wasActive != isUidActive(uid) || state != previousState) {
1613 notifyService();
1614 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001615}
1616
Eric Laurente8c8b432018-10-17 10:08:02 -07001617void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1618 std::pair<bool, int>> *uids,
1619 uid_t uid,
1620 bool active,
1621 int state,
1622 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001623 auto it = uids->find(uid);
1624 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001625 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001626 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1627 it->second.first = active;
1628 }
1629 if (it->second.first) {
1630 it->second.second = state;
1631 } else {
1632 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1633 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001634 } else {
1635 uids->erase(it);
1636 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001637 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1638 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1639 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001640 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001641}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642
Eric Laurent4eb58f12018-12-07 16:41:02 -08001643bool AudioPolicyService::UidPolicy::isA11yOnTop() {
Andy Hung79eacdb2023-11-30 19:34:24 -08001644 audio_utils::lock_guard _l(mMutex);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001645 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001646 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001647 continue;
1648 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001649 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1650 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001651 return true;
1652 }
1653 }
1654 return false;
1655}
1656
Eric Laurentb78763e2018-10-17 10:08:02 -07001657bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1658{
1659 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1660 return it != mA11yUids.end();
1661}
1662
Oscar Azucena829d90d2022-01-28 17:17:56 -08001663void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1664 mAssistantUids.clear();
1665 mAssistantUids = uids;
1666}
1667
1668bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1669{
1670 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1671 return it != mAssistantUids.end();
1672}
1673
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001674void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1675 mActiveAssistantUids = activeUids;
1676}
1677
1678bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1679{
1680 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1681 mActiveAssistantUids.end(), uid);
1682 return it != mActiveAssistantUids.end();
1683}
1684
Oscar Azucena829d90d2022-01-28 17:17:56 -08001685void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1686 const size_t SIZE = 256;
1687 char buffer[SIZE];
1688 String8 result;
1689 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1690 snprintf(buffer, SIZE, "\t%s: \n", title);
1691 result.append(buffer);
1692 int counter = 0;
1693 if (uids.empty()) {
1694 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1695 result.append(buffer);
1696 return;
1697 }
1698 for (const auto &uid : uids) {
1699 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1700 result.append(buffer);
1701 }
1702 };
1703
1704 snprintf(buffer, SIZE, "UID Policy:\n");
1705 result.append(buffer);
1706 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1707 result.append(buffer);
1708
1709 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001710 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001711
1712 appendUidsToResult("Accessibility UIDs", mA11yUids);
1713
1714 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1715 result.append(buffer);
1716
1717 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1718 result.append(buffer);
1719
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001720 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001721}
1722
Michael Groovercfd28302018-12-11 19:16:46 -08001723// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1724void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1725 SensorPrivacyManager spm;
1726 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1727 spm.addSensorPrivacyListener(this);
1728}
1729
1730void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1731 SensorPrivacyManager spm;
1732 spm.removeSensorPrivacyListener(this);
1733}
1734
1735bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1736 return mSensorPrivacyEnabled;
1737}
1738
Evan Seversond8dc6832022-01-27 10:47:03 -08001739binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1740 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001741 mSensorPrivacyEnabled = enabled;
1742 sp<AudioPolicyService> service = mService.promote();
1743 if (service != nullptr) {
1744 service->updateUidStates();
1745 }
1746 return binder::Status::ok();
1747}
1748
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1750
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1752 const wp<AudioPolicyService>& service)
1753 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755}
1756
1757
1758AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1759{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001760 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001761 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 }
1763 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764}
1765
1766void AudioPolicyService::AudioCommandThread::onFirstRef()
1767{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001768 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769}
1770
1771bool AudioPolicyService::AudioCommandThread::threadLoop()
1772{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001773 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774
Andy Hung79eacdb2023-11-30 19:34:24 -08001775 audio_utils::unique_lock ul(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 while (!exitPending())
1777 {
Eric Laurent59a89232014-06-08 14:14:17 -07001778 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001779 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001780 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781 nsecs_t curTime = systemTime();
1782 // commands are sorted by increasing time stamp: execute them from index 0 and up
1783 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001784 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001786 if (mAudioCommands.isEmpty()) {
1787 ++numTimesBecameEmpty;
1788 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001789 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790
1791 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001793 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001794 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001795 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001796 ul.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001797 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1798 data->mVolume,
1799 data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001800 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 }break;
1802 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001803 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001804 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001805 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001806 ul.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001807 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hung79eacdb2023-11-30 19:34:24 -08001808 ul.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001809 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001811 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001812 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001813 data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001814 ul.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001816 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001818 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001819 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001820 ALOGV("AudioCommandThread() processing stop output portId %d",
1821 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001822 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001823 if (svc == 0) {
1824 break;
1825 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001826 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001827 svc->doStopOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001828 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001829 }break;
1830 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001831 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001832 ALOGV("AudioCommandThread() processing release output portId %d",
1833 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001834 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001835 if (svc == 0) {
1836 break;
1837 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001838 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001839 svc->doReleaseOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001840 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001841 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001842 case CREATE_AUDIO_PATCH: {
1843 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1844 ALOGV("AudioCommandThread() processing create audio patch");
1845 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1846 if (af == 0) {
1847 command->mStatus = PERMISSION_DENIED;
1848 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001849 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001850 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001851 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001852 }
1853 } break;
1854 case RELEASE_AUDIO_PATCH: {
1855 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1856 ALOGV("AudioCommandThread() processing release audio patch");
1857 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1858 if (af == 0) {
1859 command->mStatus = PERMISSION_DENIED;
1860 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001861 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001862 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001863 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001864 }
1865 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001866 case UPDATE_AUDIOPORT_LIST: {
1867 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001868 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001869 if (svc == 0) {
1870 break;
1871 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001872 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001873 svc->doOnAudioPortListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001874 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001875 }break;
1876 case UPDATE_AUDIOPATCH_LIST: {
1877 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001878 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001879 if (svc == 0) {
1880 break;
1881 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001882 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001883 svc->doOnAudioPatchListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001884 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001885 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001886 case CHANGED_AUDIOVOLUMEGROUP: {
1887 AudioVolumeGroupData *data =
1888 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1889 ALOGV("AudioCommandThread() processing update audio volume group");
1890 svc = mService.promote();
1891 if (svc == 0) {
1892 break;
1893 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001894 ul.unlock();
François Gaffiecfe17322018-11-07 13:41:29 +01001895 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
Andy Hung79eacdb2023-11-30 19:34:24 -08001896 ul.lock();
François Gaffiecfe17322018-11-07 13:41:29 +01001897 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001898 case SET_AUDIOPORT_CONFIG: {
1899 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1900 ALOGV("AudioCommandThread() processing set port config");
1901 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1902 if (af == 0) {
1903 command->mStatus = PERMISSION_DENIED;
1904 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001905 ul.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001906 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hung79eacdb2023-11-30 19:34:24 -08001907 ul.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001908 }
1909 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001910 case DYN_POLICY_MIX_STATE_UPDATE: {
1911 DynPolicyMixStateUpdateData *data =
1912 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001913 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001914 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07001915 svc = mService.promote();
1916 if (svc == 0) {
1917 break;
1918 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001919 ul.unlock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001920 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
Andy Hung79eacdb2023-11-30 19:34:24 -08001921 ul.lock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001922 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001923 case RECORDING_CONFIGURATION_UPDATE: {
1924 RecordingConfigurationUpdateData *data =
1925 (RecordingConfigurationUpdateData *)command->mParam.get();
1926 ALOGV("AudioCommandThread() processing recording configuration update");
1927 svc = mService.promote();
1928 if (svc == 0) {
1929 break;
1930 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001931 ul.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001932 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001933 &data->mClientConfig, data->mClientEffects,
1934 &data->mDeviceConfig, data->mEffects,
1935 data->mPatchHandle, data->mSource);
Andy Hung79eacdb2023-11-30 19:34:24 -08001936 ul.lock();
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001937 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001938 case SET_EFFECT_SUSPENDED: {
1939 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1940 ALOGV("AudioCommandThread() processing set effect suspended");
1941 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1942 if (af != 0) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001943 ul.unlock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001944 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
Andy Hung79eacdb2023-11-30 19:34:24 -08001945 ul.lock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001946 }
1947 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001948 case AUDIO_MODULES_UPDATE: {
1949 ALOGV("AudioCommandThread() processing audio modules update");
1950 svc = mService.promote();
1951 if (svc == 0) {
1952 break;
1953 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001954 ul.unlock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001955 svc->doOnNewAudioModulesAvailable();
Andy Hung79eacdb2023-11-30 19:34:24 -08001956 ul.lock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001957 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001958 case ROUTING_UPDATED: {
1959 ALOGV("AudioCommandThread() processing routing update");
1960 svc = mService.promote();
1961 if (svc == 0) {
1962 break;
1963 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001964 ul.unlock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001965 svc->doOnRoutingUpdated();
Andy Hung79eacdb2023-11-30 19:34:24 -08001966 ul.lock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001967 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001968
Eric Laurented726cc2021-07-01 14:26:41 +02001969 case UPDATE_UID_STATES: {
1970 ALOGV("AudioCommandThread() processing updateUID states");
1971 svc = mService.promote();
1972 if (svc == 0) {
1973 break;
1974 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001975 ul.unlock();
Eric Laurented726cc2021-07-01 14:26:41 +02001976 svc->updateUidStates();
Andy Hung79eacdb2023-11-30 19:34:24 -08001977 ul.lock();
Eric Laurented726cc2021-07-01 14:26:41 +02001978 } break;
1979
Eric Laurent15903592022-02-24 20:44:36 +01001980 case CHECK_SPATIALIZER_OUTPUT: {
1981 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02001982 svc = mService.promote();
1983 if (svc == 0) {
1984 break;
1985 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001986 ul.unlock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02001987 svc->doOnCheckSpatializer();
Andy Hung79eacdb2023-11-30 19:34:24 -08001988 ul.lock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02001989 } break;
1990
Eric Laurent15903592022-02-24 20:44:36 +01001991 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
1992 ALOGV("AudioCommandThread() processing update spatializer tracks");
1993 svc = mService.promote();
1994 if (svc == 0) {
1995 break;
1996 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001997 ul.unlock();
Eric Laurent15903592022-02-24 20:44:36 +01001998 svc->doOnUpdateActiveSpatializerTracks();
Andy Hung79eacdb2023-11-30 19:34:24 -08001999 ul.lock();
Eric Laurent15903592022-02-24 20:44:36 +01002000 } break;
2001
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002002 case VOL_RANGE_INIT_REQUEST: {
2003 ALOGV("AudioCommandThread() processing volume range init request");
2004 svc = mService.promote();
2005 if (svc == 0) {
2006 break;
2007 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002008 ul.unlock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002009 svc->doOnVolumeRangeInitRequest();
Andy Hung79eacdb2023-11-30 19:34:24 -08002010 ul.lock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002011 } break;
2012
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002014 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002016 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002017 audio_utils::lock_guard _l(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002018 if (command->mWaitStatus) {
2019 command->mWaitStatus = false;
Andy Hung79eacdb2023-11-30 19:34:24 -08002020 command->mCond.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002021 }
2022 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002023 waitTime = -1;
Andy Hung79eacdb2023-11-30 19:34:24 -08002024 // release ul before releasing strong reference on the service as
Zach Janga754b4f2015-10-27 01:29:34 +00002025 // AudioPolicyService destructor calls AudioCommandThread::exit() which
Andy Hung79eacdb2023-11-30 19:34:24 -08002026 // acquires ul.
2027 ul.unlock();
Zach Janga754b4f2015-10-27 01:29:34 +00002028 svc.clear();
Andy Hung79eacdb2023-11-30 19:34:24 -08002029 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 } else {
2031 waitTime = mAudioCommands[0]->mTime - curTime;
2032 break;
2033 }
2034 }
Zach Janga754b4f2015-10-27 01:29:34 +00002035
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002036 // release delayed commands wake lock as many times as we made the queue is
2037 // empty during popping.
2038 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002039 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002040 }
2041
2042 // At this stage we have either an empty command queue or the first command in the queue
2043 // has a finite delay. So unless we are exiting it is safe to wait.
2044 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002045 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002046 if (waitTime == -1) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002047 mWaitWorkCV.wait(ul);
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002048 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002049 // discard return value.
2050 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002051 }
Eric Laurent59a89232014-06-08 14:14:17 -07002052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002054 // release delayed commands wake lock before quitting
2055 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002056 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 return false;
2059}
2060
2061status_t AudioPolicyService::AudioCommandThread::dump(int fd)
Andy Hung79eacdb2023-11-30 19:34:24 -08002062NO_THREAD_SAFETY_ANALYSIS // trylock
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063{
2064 const size_t SIZE = 256;
2065 char buffer[SIZE];
2066 String8 result;
2067
Andy Hung79eacdb2023-11-30 19:34:24 -08002068 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 if (!locked) {
2070 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002071 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 }
2073
2074 snprintf(buffer, SIZE, "- Commands:\n");
2075 result = String8(buffer);
2076 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002077 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 mAudioCommands[i]->dump(buffer, SIZE);
2079 result.append(buffer);
2080 }
2081 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002082 if (mLastCommand != 0) {
2083 mLastCommand->dump(buffer, SIZE);
2084 result.append(buffer);
2085 } else {
2086 result.append(" none\n");
2087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002089 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090
Andy Hung79eacdb2023-11-30 19:34:24 -08002091 dumpReleaseLock(mMutex, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092
2093 return NO_ERROR;
2094}
2095
Glenn Kastenfff6d712012-01-12 16:38:12 -08002096status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002097 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002098 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002099 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100{
Eric Laurent0ede8922014-05-09 18:04:42 -07002101 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002103 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104 data->mStream = stream;
2105 data->mVolume = volume;
2106 data->mIO = output;
2107 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002108 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002109 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002110 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002111 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112}
2113
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002114status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002115 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002116 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117{
Eric Laurent0ede8922014-05-09 18:04:42 -07002118 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002120 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002122 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002124 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002125 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002126 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002127 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128}
2129
2130status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2131{
Eric Laurent0ede8922014-05-09 18:04:42 -07002132 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002134 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 data->mVolume = volume;
2136 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002137 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002138 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002139 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140}
2141
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002142void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2143 audio_session_t sessionId,
2144 bool suspended)
2145{
2146 sp<AudioCommand> command = new AudioCommand();
2147 command->mCommand = SET_EFFECT_SUSPENDED;
2148 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2149 data->mEffectId = effectId;
2150 data->mSessionId = sessionId;
2151 data->mSuspended = suspended;
2152 command->mParam = data;
2153 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2154 effectId, sessionId, suspended);
2155 sendCommand(command);
2156}
2157
2158
Eric Laurentd7fe0862018-07-14 16:48:01 -07002159void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002160{
Eric Laurent0ede8922014-05-09 18:04:42 -07002161 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002163 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002164 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002165 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002166 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002167 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168}
2169
Eric Laurentd7fe0862018-07-14 16:48:01 -07002170void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171{
Eric Laurent0ede8922014-05-09 18:04:42 -07002172 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002173 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002174 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002175 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002176 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002177 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002178 sendCommand(command);
2179}
2180
Eric Laurent951f4552014-05-20 10:48:17 -07002181status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2182 const struct audio_patch *patch,
2183 audio_patch_handle_t *handle,
2184 int delayMs)
2185{
2186 status_t status = NO_ERROR;
2187
2188 sp<AudioCommand> command = new AudioCommand();
2189 command->mCommand = CREATE_AUDIO_PATCH;
2190 CreateAudioPatchData *data = new CreateAudioPatchData();
2191 data->mPatch = *patch;
2192 data->mHandle = *handle;
2193 command->mParam = data;
2194 command->mWaitStatus = true;
2195 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2196 status = sendCommand(command, delayMs);
2197 if (status == NO_ERROR) {
2198 *handle = data->mHandle;
2199 }
2200 return status;
2201}
2202
2203status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2204 int delayMs)
2205{
2206 sp<AudioCommand> command = new AudioCommand();
2207 command->mCommand = RELEASE_AUDIO_PATCH;
2208 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2209 data->mHandle = handle;
2210 command->mParam = data;
2211 command->mWaitStatus = true;
2212 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2213 return sendCommand(command, delayMs);
2214}
2215
Eric Laurentb52c1522014-05-20 11:27:36 -07002216void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2217{
2218 sp<AudioCommand> command = new AudioCommand();
2219 command->mCommand = UPDATE_AUDIOPORT_LIST;
2220 ALOGV("AudioCommandThread() adding update audio port list");
2221 sendCommand(command);
2222}
2223
Eric Laurented726cc2021-07-01 14:26:41 +02002224void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2225{
2226 sp<AudioCommand> command = new AudioCommand();
2227 command->mCommand = UPDATE_UID_STATES;
2228 ALOGV("AudioCommandThread() adding update UID states");
2229 sendCommand(command);
2230}
2231
Eric Laurentb52c1522014-05-20 11:27:36 -07002232void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2233{
2234 sp<AudioCommand>command = new AudioCommand();
2235 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2236 ALOGV("AudioCommandThread() adding update audio patch list");
2237 sendCommand(command);
2238}
2239
François Gaffiecfe17322018-11-07 13:41:29 +01002240void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2241 int flags)
2242{
2243 sp<AudioCommand>command = new AudioCommand();
2244 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2245 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2246 data->mGroup = group;
2247 data->mFlags = flags;
2248 command->mParam = data;
2249 ALOGV("AudioCommandThread() adding audio volume group changed");
2250 sendCommand(command);
2251}
2252
Eric Laurente1715a42014-05-20 11:30:42 -07002253status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2254 const struct audio_port_config *config, int delayMs)
2255{
2256 sp<AudioCommand> command = new AudioCommand();
2257 command->mCommand = SET_AUDIOPORT_CONFIG;
2258 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2259 data->mConfig = *config;
2260 command->mParam = data;
2261 command->mWaitStatus = true;
2262 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2263 return sendCommand(command, delayMs);
2264}
2265
Jean-Michel Trivide801052015-04-14 19:10:14 -07002266void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002267 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002268{
2269 sp<AudioCommand> command = new AudioCommand();
2270 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2271 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2272 data->mRegId = regId;
2273 data->mState = state;
2274 command->mParam = data;
2275 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002276 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002277 sendCommand(command);
2278}
2279
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002280void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002281 int event,
2282 const record_client_info_t *clientInfo,
2283 const audio_config_base_t *clientConfig,
2284 std::vector<effect_descriptor_t> clientEffects,
2285 const audio_config_base_t *deviceConfig,
2286 std::vector<effect_descriptor_t> effects,
2287 audio_patch_handle_t patchHandle,
2288 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002289{
2290 sp<AudioCommand>command = new AudioCommand();
2291 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2292 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2293 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002294 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002295 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002296 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002297 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002298 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002299 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002300 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002301 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002302 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2303 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002304 sendCommand(command);
2305}
2306
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002307void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2308{
2309 sp<AudioCommand> command = new AudioCommand();
2310 command->mCommand = AUDIO_MODULES_UPDATE;
2311 sendCommand(command);
2312}
2313
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002314void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2315{
2316 sp<AudioCommand>command = new AudioCommand();
2317 command->mCommand = ROUTING_UPDATED;
2318 ALOGV("AudioCommandThread() adding routing update");
2319 sendCommand(command);
2320}
2321
Eric Laurent81dd0f52021-07-05 11:54:40 +02002322void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2323{
2324 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002325 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002326 ALOGV("AudioCommandThread() adding check spatializer");
2327 sendCommand(command);
2328}
2329
Eric Laurent15903592022-02-24 20:44:36 +01002330void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2331{
2332 sp<AudioCommand>command = new AudioCommand();
2333 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2334 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2335 sendCommand(command);
2336}
2337
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002338void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2339{
2340 sp<AudioCommand>command = new AudioCommand();
2341 command->mCommand = VOL_RANGE_INIT_REQUEST;
2342 ALOGV("AudioCommandThread() adding volume range init request");
2343 sendCommand(command);
2344}
2345
Eric Laurent0ede8922014-05-09 18:04:42 -07002346status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2347{
2348 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002349 audio_utils::lock_guard _l(mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002350 insertCommand_l(command, delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002351 mWaitWorkCV.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002352 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002353 audio_utils::unique_lock ul(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002354 while (command->mWaitStatus) {
2355 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002356 if (command->mCond.wait_for(
Andy Hung02ea2a02024-01-25 17:02:30 -08002357 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002358 command->mStatus = TIMED_OUT;
2359 command->mWaitStatus = false;
2360 }
2361 }
2362 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002363}
2364
Andy Hung79eacdb2023-11-30 19:34:24 -08002365// insertCommand_l() must be called with mMutex held
Eric Laurent0ede8922014-05-09 18:04:42 -07002366void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002368 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002369 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 command->mTime = systemTime() + milliseconds(delayMs);
2371
2372 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002373 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002374 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375 }
2376
2377 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002378 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002379 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2381 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002382
2383 // create audio patch or release audio patch commands are equivalent
2384 // with regard to filtering
2385 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2386 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2387 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2388 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2389 continue;
2390 }
2391 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392
2393 switch (command->mCommand) {
2394 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002395 ParametersData *data = (ParametersData *)command->mParam.get();
2396 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002398 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002399 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2401 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2402 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002403 String8 key;
2404 String8 value;
2405 param.getAt(j, key, value);
2406 for (size_t k = 0; k < param2.size(); k++) {
2407 String8 key2;
2408 String8 value2;
2409 param2.getAt(k, key2, value2);
2410 if (key2 == key) {
2411 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002412 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002413 break;
2414 }
2415 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416 }
2417 // if all keys have been filtered out, remove the command.
2418 // otherwise, update the key value pairs
2419 if (param2.size() == 0) {
2420 removedCommands.add(command2);
2421 } else {
2422 data2->mKeyValuePairs = param2.toString();
2423 }
Eric Laurent21e54562013-09-23 12:08:05 -07002424 command->mTime = command2->mTime;
2425 // force delayMs to non 0 so that code below does not request to wait for
2426 // command status as the command is now delayed
2427 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 } break;
2429
2430 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002431 VolumeData *data = (VolumeData *)command->mParam.get();
2432 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 if (data->mIO != data2->mIO) break;
2434 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002435 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002436 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002438 command->mTime = command2->mTime;
2439 // force delayMs to non 0 so that code below does not request to wait for
2440 // command status as the command is now delayed
2441 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002443
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002444 case SET_VOICE_VOLUME: {
2445 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2446 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2447 ALOGV("Filtering out voice volume command value %f replaced by %f",
2448 data2->mVolume, data->mVolume);
2449 removedCommands.add(command2);
2450 command->mTime = command2->mTime;
2451 // force delayMs to non 0 so that code below does not request to wait for
2452 // command status as the command is now delayed
2453 delayMs = 1;
2454 } break;
2455
Eric Laurente45b48a2014-09-04 16:40:57 -07002456 case CREATE_AUDIO_PATCH:
2457 case RELEASE_AUDIO_PATCH: {
2458 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002459 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002460 if (command->mCommand == CREATE_AUDIO_PATCH) {
2461 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002462 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002463 } else {
2464 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002465 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002466 }
2467 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002468 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002469 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2470 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002471 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002472 } else {
2473 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002474 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002475 }
2476 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002477 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2478 same output. */
2479 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2480 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2481 bool isOutputDiff = false;
2482 if (patch.num_sources == patch2.num_sources) {
2483 for (unsigned count = 0; count < patch.num_sources; count++) {
2484 if (patch.sources[count].id != patch2.sources[count].id) {
2485 isOutputDiff = true;
2486 break;
2487 }
2488 }
2489 if (isOutputDiff)
2490 break;
2491 }
2492 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002493 ALOGV("Filtering out %s audio patch command for handle %d",
2494 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2495 removedCommands.add(command2);
2496 command->mTime = command2->mTime;
2497 // force delayMs to non 0 so that code below does not request to wait for
2498 // command status as the command is now delayed
2499 delayMs = 1;
2500 } break;
2501
Jean-Michel Trivide801052015-04-14 19:10:14 -07002502 case DYN_POLICY_MIX_STATE_UPDATE: {
2503
2504 } break;
2505
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002506 case RECORDING_CONFIGURATION_UPDATE: {
2507
2508 } break;
2509
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002510 case ROUTING_UPDATED: {
2511
2512 } break;
2513
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002514 case VOL_RANGE_INIT_REQUEST: {
2515 // command may come from different requests, do not filter
2516 } break;
2517
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518 default:
2519 break;
2520 }
2521 }
2522
2523 // remove filtered commands
2524 for (size_t j = 0; j < removedCommands.size(); j++) {
2525 // removed commands always have time stamps greater than current command
2526 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002527 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002528 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 mAudioCommands.removeAt(k);
2530 break;
2531 }
2532 }
2533 }
2534 removedCommands.clear();
2535
Eric Laurentaa79bef2015-01-15 14:33:51 -08002536 // Disable wait for status if delay is not 0.
2537 // Except for create audio patch command because the returned patch handle
2538 // is needed by audio policy manager
2539 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002540 command->mWaitStatus = false;
2541 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002542
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002544 ALOGV("inserting command: %d at index %zd, num commands %zu",
2545 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 mAudioCommands.insertAt(command, i + 1);
2547}
2548
2549void AudioPolicyService::AudioCommandThread::exit()
2550{
Steve Block3856b092011-10-20 11:56:00 +01002551 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002553 audio_utils::lock_guard _l(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 requestExit();
Andy Hung79eacdb2023-11-30 19:34:24 -08002555 mWaitWorkCV.notify_one();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 }
Zach Janga754b4f2015-10-27 01:29:34 +00002557 // Note that we can call it from the thread loop if all other references have been released
2558 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 requestExitAndWait();
2560}
2561
2562void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2563{
2564 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2565 mCommand,
2566 (int)ns2s(mTime),
2567 (int)ns2ms(mTime)%1000,
2568 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002569 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570}
2571
Dima Zavinfce7a472011-04-19 22:30:36 -07002572/******* helpers for the service_ops callbacks defined below *********/
2573void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2574 const char *keyValuePairs,
2575 int delayMs)
2576{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002577 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002578 delayMs);
2579}
2580
2581int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2582 float volume,
2583 audio_io_handle_t output,
2584 int delayMs)
2585{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002586 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002587 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002588}
2589
Dima Zavinfce7a472011-04-19 22:30:36 -07002590int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2591{
2592 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2593}
2594
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002595void AudioPolicyService::setEffectSuspended(int effectId,
2596 audio_session_t sessionId,
2597 bool suspended)
2598{
2599 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2600}
2601
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002602Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002603{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002604 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002605 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002606}
2607
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002608
Dima Zavinfce7a472011-04-19 22:30:36 -07002609extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002610audio_module_handle_t aps_load_hw_module(void *service __unused,
2611 const char *name);
2612audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002613 audio_devices_t *pDevices,
2614 uint32_t *pSamplingRate,
2615 audio_format_t *pFormat,
2616 audio_channel_mask_t *pChannelMask,
2617 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002618 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002619
Eric Laurent2d388ec2014-03-07 13:25:54 -08002620audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002621 audio_module_handle_t module,
2622 audio_devices_t *pDevices,
2623 uint32_t *pSamplingRate,
2624 audio_format_t *pFormat,
2625 audio_channel_mask_t *pChannelMask,
2626 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002627 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002628 const audio_offload_info_t *offloadInfo);
2629audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002630 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002631 audio_io_handle_t output2);
2632int aps_close_output(void *service __unused, audio_io_handle_t output);
2633int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2634int aps_restore_output(void *service __unused, audio_io_handle_t output);
2635audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002636 audio_devices_t *pDevices,
2637 uint32_t *pSamplingRate,
2638 audio_format_t *pFormat,
2639 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002640 audio_in_acoustics_t acoustics __unused);
2641audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002642 audio_module_handle_t module,
2643 audio_devices_t *pDevices,
2644 uint32_t *pSamplingRate,
2645 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002646 audio_channel_mask_t *pChannelMask);
2647int aps_close_input(void *service __unused, audio_io_handle_t input);
2648int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002649int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002650 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002651 audio_io_handle_t dst_output);
2652char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2653 const char *keys);
2654void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2655 const char *kv_pairs, int delay_ms);
2656int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002657 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002658 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002659int aps_set_voice_volume(void *service, float volume, int delay_ms);
2660};
Dima Zavinfce7a472011-04-19 22:30:36 -07002661
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002662} // namespace android