blob: 7b7275ea99713dc1b8e9f89ba1883041a35910a7 [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
Atneya Nairdb6ef1e2024-09-16 20:26:30 +000064namespace {
65constexpr auto PERMISSION_GRANTED = permission::PermissionChecker::PERMISSION_GRANTED;
66}
67
Andy Hungc747c532022-03-07 21:41:14 -080068// Creates an association between Binder code to name for IAudioPolicyService.
69#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
70BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
71BINDER_METHOD_ENTRY(setDeviceConnectionState) \
72BINDER_METHOD_ENTRY(getDeviceConnectionState) \
73BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
74BINDER_METHOD_ENTRY(setPhoneState) \
75BINDER_METHOD_ENTRY(setForceUse) \
76BINDER_METHOD_ENTRY(getForceUse) \
77BINDER_METHOD_ENTRY(getOutput) \
78BINDER_METHOD_ENTRY(getOutputForAttr) \
79BINDER_METHOD_ENTRY(startOutput) \
80BINDER_METHOD_ENTRY(stopOutput) \
81BINDER_METHOD_ENTRY(releaseOutput) \
82BINDER_METHOD_ENTRY(getInputForAttr) \
83BINDER_METHOD_ENTRY(startInput) \
84BINDER_METHOD_ENTRY(stopInput) \
85BINDER_METHOD_ENTRY(releaseInput) \
Vlad Popa87e0e582024-05-20 18:49:20 -070086BINDER_METHOD_ENTRY(setDeviceAbsoluteVolumeEnabled) \
Andy Hungc747c532022-03-07 21:41:14 -080087BINDER_METHOD_ENTRY(initStreamVolume) \
88BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
89BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
90BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
91BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
92BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
93BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
94BINDER_METHOD_ENTRY(getStrategyForStream) \
95BINDER_METHOD_ENTRY(getDevicesForAttributes) \
96BINDER_METHOD_ENTRY(getOutputForEffect) \
97BINDER_METHOD_ENTRY(registerEffect) \
98BINDER_METHOD_ENTRY(unregisterEffect) \
99BINDER_METHOD_ENTRY(setEffectEnabled) \
100BINDER_METHOD_ENTRY(moveEffectsToIo) \
101BINDER_METHOD_ENTRY(isStreamActive) \
102BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
103BINDER_METHOD_ENTRY(isSourceActive) \
104BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
105BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
106BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
107BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
108BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
109BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
110BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
111BINDER_METHOD_ENTRY(getOffloadSupport) \
112BINDER_METHOD_ENTRY(isDirectOutputSupported) \
113BINDER_METHOD_ENTRY(listAudioPorts) \
114BINDER_METHOD_ENTRY(getAudioPort) \
115BINDER_METHOD_ENTRY(createAudioPatch) \
116BINDER_METHOD_ENTRY(releaseAudioPatch) \
117BINDER_METHOD_ENTRY(listAudioPatches) \
118BINDER_METHOD_ENTRY(setAudioPortConfig) \
119BINDER_METHOD_ENTRY(registerClient) \
120BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
121BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
122BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
123BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
124BINDER_METHOD_ENTRY(getPhoneState) \
125BINDER_METHOD_ENTRY(registerPolicyMixes) \
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +0200126BINDER_METHOD_ENTRY(updatePolicyMixes) \
Andy Hungc747c532022-03-07 21:41:14 -0800127BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
128BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
129BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
130BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
131BINDER_METHOD_ENTRY(startAudioSource) \
132BINDER_METHOD_ENTRY(stopAudioSource) \
133BINDER_METHOD_ENTRY(setMasterMono) \
134BINDER_METHOD_ENTRY(getMasterMono) \
135BINDER_METHOD_ENTRY(getStreamVolumeDB) \
136BINDER_METHOD_ENTRY(getSurroundFormats) \
137BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
138BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
139BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
140BINDER_METHOD_ENTRY(setAssistantServicesUids) \
141BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
142BINDER_METHOD_ENTRY(setA11yServicesUids) \
143BINDER_METHOD_ENTRY(setCurrentImeUid) \
144BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
145BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800146BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800147BINDER_METHOD_ENTRY(listAudioProductStrategies) \
148BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
149BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
150BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
151BINDER_METHOD_ENTRY(setRttEnabled) \
152BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
153BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
154BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000155BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800156BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
157BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
158BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
159BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
160BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
161BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
162BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
163BINDER_METHOD_ENTRY(getSpatializer) \
164BINDER_METHOD_ENTRY(canBeSpatialized) \
165BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000166BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
167BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
168BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
169BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
170BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100171BINDER_METHOD_ENTRY(getRegisteredPolicyMixes) \
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700172BINDER_METHOD_ENTRY(getPermissionController) \
Marvin Raminbdefaf02023-11-01 09:10:32 +0100173 \
Andy Hungc747c532022-03-07 21:41:14 -0800174// singleton for Binder Method Statistics for IAudioPolicyService
175static auto& getIAudioPolicyServiceStatistics() {
176 using Code = int;
177
178#pragma push_macro("BINDER_METHOD_ENTRY")
179#undef BINDER_METHOD_ENTRY
180#define BINDER_METHOD_ENTRY(ENTRY) \
181 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
182
183 static mediautils::MethodStatistics<Code> methodStatistics{
184 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
185 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
186 };
187#pragma pop_macro("BINDER_METHOD_ENTRY")
188
189 return methodStatistics;
190}
191
Mathias Agopian65ab4712010-07-14 17:59:35 -0700192// ----------------------------------------------------------------------------
193
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530194static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
195{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700196 AudioPolicyManager *apm = nullptr;
197 media::AudioPolicyConfig apmConfig;
198 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
199 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
François Gaffiead3dce92024-03-26 17:20:04 +0100200 ALOGD("%s loading APM engine %s", __func__, config->getEngineLibraryNameSuffix().c_str());
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700201 apm = new AudioPolicyManager(config,
202 loadApmEngineLibraryAndCreateEngine(
203 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
204 clientInterface);
205 } else {
206 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
207 apm = new AudioPolicyManager(config,
208 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
209 clientInterface);
210 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530211 status_t status = apm->initialize();
212 if (status != NO_ERROR) {
213 delete apm;
214 apm = nullptr;
215 }
216 return apm;
217}
218
219static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
220{
221 delete interface;
222}
223// ----------------------------------------------------------------------------
224
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700226 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700227 mAudioPolicyManager(NULL),
228 mAudioPolicyClient(NULL),
229 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530230 mCaptureStateNotifier(false),
231 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100232 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
Atneya Nair9f91a5e2024-05-09 16:25:05 -0700233 mUsecaseValidator(media::createUsecaseValidator()),
234 mPermissionController(sp<NativePermissionController>::make())
235{
Andy Hung225aef62022-12-06 16:33:20 -0800236 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Andy Hung58b01b12024-03-26 18:04:29 -0700237 setInheritRt(true);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530238}
239
240void AudioPolicyService::loadAudioPolicyManager()
241{
242 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
243 if (mLibraryHandle != nullptr) {
244 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
245 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
246 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
247 const char *lastError = dlerror();
248 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
249 __func__, lastError != nullptr ? lastError : "no error");
250
251 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
252 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
253 lastError = dlerror();
254 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
255 __func__, lastError != nullptr ? lastError : "no error");
256 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
257 unloadAudioPolicyManager();
258 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
259 }
260 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700261}
262
263void AudioPolicyService::onFirstRef()
264{
Andy Hungd47aca22022-03-15 11:50:51 -0700265 // Log an AudioPolicy "constructor" mediametrics event on first ref.
266 // This records the time it takes to load the audio modules and devices.
267 mediametrics::Defer defer([beginNs = systemTime()] {
268 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
269 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
270 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
271 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700272 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800273 audio_utils::lock_guard _l(mMutex);
Eric Laurent93575202011-01-18 18:39:02 -0800274
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700275 // start audio commands thread
276 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
277 // start output activity command thread
278 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700279
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700280 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530281
282 loadAudioPolicyManager();
283 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700284 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200285
bryant_liuba2b4392014-06-11 16:49:30 +0800286 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000287 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
Andy Hungd3595ed2023-12-19 15:34:46 -0800288 auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
289 auto uidPolicy = sp<UidPolicy>::make(this);
290 auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700291 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800292 audio_utils::lock_guard _l(mMutex);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700293 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000294 mUidPolicy = uidPolicy;
295 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700296 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000297 uidPolicy->registerSelf();
298 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200299
Eric Laurent81dd0f52021-07-05 11:54:40 +0200300 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200301 if (mAudioPolicyManager != nullptr) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800302 audio_utils::lock_guard _l(mMutex);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200303 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
304 AudioDeviceTypeAddrVector devices;
305 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
306 if (hasSpatializer) {
Andy Hung1040da52023-12-06 20:59:06 -0800307 // Unlock as Spatializer::create() will use the callback and acquire the
308 // AudioPolicyService_Mutex.
Andy Hung79eacdb2023-11-30 19:34:24 -0800309 mMutex.unlock();
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000310 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Andy Hung79eacdb2023-11-30 19:34:24 -0800311 mMutex.lock();
Eric Laurent52b0bd52021-09-27 15:25:40 +0200312 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700313 if (mSpatializer == nullptr) {
314 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
315 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
316 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
317 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200318 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200319 AudioSystem::audioPolicyReady();
Andy Hungb08b3752024-01-09 19:05:23 -0800320}
321
Atneya Nair87818d32024-05-23 10:59:30 -0700322const IPermissionProvider& AudioPolicyService::getPermissionProvider() const {
323 return *mPermissionController;
324}
325
Andy Hungb08b3752024-01-09 19:05:23 -0800326void AudioPolicyService::onAudioSystemReady() {
327 sp<AudioPolicyEffects> audioPolicyEffects;
328 {
329 audio_utils::lock_guard _l(mMutex);
330
331 audioPolicyEffects = mAudioPolicyEffects;
332 }
333 audioPolicyEffects->initDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700334}
335
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530336void AudioPolicyService::unloadAudioPolicyManager()
337{
338 ALOGV("%s ", __func__);
339 if (mLibraryHandle != nullptr) {
340 dlclose(mLibraryHandle);
341 }
342 mLibraryHandle = nullptr;
343 mCreateAudioPolicyManager = nullptr;
344 mDestroyAudioPolicyManager = nullptr;
345}
346
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347AudioPolicyService::~AudioPolicyService()
348{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700350 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700351
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530352 mDestroyAudioPolicyManager(mAudioPolicyManager);
353 unloadAudioPolicyManager();
354
Eric Laurentdce54a12014-03-10 12:19:46 -0700355 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700356
357 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800358 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800359
360 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800361 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000362
363 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800364 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700365}
366
367// A notification client is always registered by AudioSystem when the client process
368// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800369Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700370{
Eric Laurent12590252015-08-21 18:40:20 -0700371 if (client == 0) {
372 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800373 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700374 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800375 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700376
377 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800378 pid_t pid = IPCThreadState::self()->getCallingPid();
379 int64_t token = ((int64_t)uid<<32) | pid;
380
381 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700382 sp<NotificationClient> notificationClient = new NotificationClient(this,
383 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800384 uid,
385 pid);
386 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700387
luochaojiang908c7d72018-06-21 14:58:04 +0800388 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700389
Marco Nelissenf8880202014-11-14 07:58:25 -0800390 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700391 binder->linkToDeath(notificationClient);
392 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800393 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700394}
395
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800396Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700397{
Andy Hung79eacdb2023-11-30 19:34:24 -0800398 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurente8726fe2015-06-26 09:39:24 -0700399
400 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800401 pid_t pid = IPCThreadState::self()->getCallingPid();
402 int64_t token = ((int64_t)uid<<32) | pid;
403
404 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800405 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700406 }
luochaojiang908c7d72018-06-21 14:58:04 +0800407 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800408 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700409}
410
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800411Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100412{
Andy Hung79eacdb2023-11-30 19:34:24 -0800413 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100414
415 uid_t uid = IPCThreadState::self()->getCallingUid();
416 pid_t pid = IPCThreadState::self()->getCallingPid();
417 int64_t token = ((int64_t)uid<<32) | pid;
418
419 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800420 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100421 }
422 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800423 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100424}
425
Eric Laurentb52c1522014-05-20 11:27:36 -0700426// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800427void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700428{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000429 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800430 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800431 audio_utils::lock_guard _l(mNotificationClientsMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800432 int64_t token = ((int64_t)uid<<32) | pid;
433 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800434 for (size_t i = 0; i < mNotificationClients.size(); i++) {
435 if (mNotificationClients.valueAt(i)->uid() == uid) {
436 hasSameUid = true;
437 break;
438 }
439 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000440 }
441 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800442 audio_utils::lock_guard _l(mMutex);
luochaojiang908c7d72018-06-21 14:58:04 +0800443 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700444 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700445 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700446 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800447 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700448}
449
450void AudioPolicyService::onAudioPortListUpdate()
451{
452 mOutputCommandThread->updateAudioPortListCommand();
453}
454
455void AudioPolicyService::doOnAudioPortListUpdate()
456{
Andy Hung79eacdb2023-11-30 19:34:24 -0800457 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700458 for (size_t i = 0; i < mNotificationClients.size(); i++) {
459 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
460 }
461}
462
463void AudioPolicyService::onAudioPatchListUpdate()
464{
465 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466}
467
Eric Laurentb52c1522014-05-20 11:27:36 -0700468void AudioPolicyService::doOnAudioPatchListUpdate()
469{
Andy Hung79eacdb2023-11-30 19:34:24 -0800470 audio_utils::lock_guard _l(mNotificationClientsMutex);
Eric Laurentb52c1522014-05-20 11:27:36 -0700471 for (size_t i = 0; i < mNotificationClients.size(); i++) {
472 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
473 }
474}
475
François Gaffiecfe17322018-11-07 13:41:29 +0100476void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
477{
478 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
479}
480
481void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
482{
Andy Hung79eacdb2023-11-30 19:34:24 -0800483 audio_utils::lock_guard _l(mNotificationClientsMutex);
François Gaffiecfe17322018-11-07 13:41:29 +0100484 for (size_t i = 0; i < mNotificationClients.size(); i++) {
485 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
486 }
487}
488
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700489void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700490{
491 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000492 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700493 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
494}
495
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700496void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700497{
Andy Hung79eacdb2023-11-30 19:34:24 -0800498 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700499 for (size_t i = 0; i < mNotificationClients.size(); i++) {
500 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
501 }
502}
503
Eric Laurenta9f86652018-11-28 17:23:11 -0800504void AudioPolicyService::onRecordingConfigurationUpdate(
505 int event,
506 const record_client_info_t *clientInfo,
507 const audio_config_base_t *clientConfig,
508 std::vector<effect_descriptor_t> clientEffects,
509 const audio_config_base_t *deviceConfig,
510 std::vector<effect_descriptor_t> effects,
511 audio_patch_handle_t patchHandle,
512 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800513{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800514 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800515 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800516}
517
Eric Laurenta9f86652018-11-28 17:23:11 -0800518void AudioPolicyService::doOnRecordingConfigurationUpdate(
519 int event,
520 const record_client_info_t *clientInfo,
521 const audio_config_base_t *clientConfig,
522 std::vector<effect_descriptor_t> clientEffects,
523 const audio_config_base_t *deviceConfig,
524 std::vector<effect_descriptor_t> effects,
525 audio_patch_handle_t patchHandle,
526 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800527{
Andy Hung79eacdb2023-11-30 19:34:24 -0800528 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800529 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800530 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800531 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800532 }
533}
534
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700535void AudioPolicyService::onRoutingUpdated()
536{
537 mOutputCommandThread->routingChangedCommand();
538}
539
540void AudioPolicyService::doOnRoutingUpdated()
541{
Andy Hung79eacdb2023-11-30 19:34:24 -0800542 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700543 for (size_t i = 0; i < mNotificationClients.size(); i++) {
544 mNotificationClients.valueAt(i)->onRoutingUpdated();
545 }
546}
547
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000548void AudioPolicyService::onVolumeRangeInitRequest()
549{
550 mOutputCommandThread->volRangeInitReqCommand();
551}
552
553void AudioPolicyService::doOnVolumeRangeInitRequest()
554{
Andy Hung79eacdb2023-11-30 19:34:24 -0800555 audio_utils::lock_guard _l(mNotificationClientsMutex);
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000556 for (size_t i = 0; i < mNotificationClients.size(); i++) {
557 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
558 }
559}
560
Eric Laurent81dd0f52021-07-05 11:54:40 +0200561void AudioPolicyService::onCheckSpatializer()
562{
Andy Hung79eacdb2023-11-30 19:34:24 -0800563 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200564 onCheckSpatializer_l();
565}
566
567void AudioPolicyService::onCheckSpatializer_l()
568{
569 if (mSpatializer != nullptr) {
570 mOutputCommandThread->checkSpatializerCommand();
571 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200572}
573
574void AudioPolicyService::doOnCheckSpatializer()
575{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200576 ALOGV("%s mSpatializer %p level %d",
577 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200578
Eric Laurent39095982021-08-24 18:29:27 +0200579 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200580 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000581 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200582 audio_io_handle_t currentOutput = mSpatializer->getOutput();
583 audio_io_handle_t newOutput;
584 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
585 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200586
Andy Hung79eacdb2023-11-30 19:34:24 -0800587 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200588 status_t status =
589 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100590 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
591 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200592 if (status == NO_ERROR && currentOutput == newOutput) {
593 return;
594 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000595 std::vector<audio_channel_mask_t> activeTracksMasks =
596 getActiveTracksMasks_l(newOutput);
Andy Hung79eacdb2023-11-30 19:34:24 -0800597 mMutex.unlock();
Eric Laurent39095982021-08-24 18:29:27 +0200598 // It is OK to call detachOutput() is none is already attached.
599 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200600 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000601 status = mSpatializer->attachOutput(newOutput, activeTracksMasks);
Eric Laurent39095982021-08-24 18:29:27 +0200602 }
Andy Hung79eacdb2023-11-30 19:34:24 -0800603 mMutex.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200604 if (status != NO_ERROR) {
605 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
606 }
Shunkai Yao49bc61f2023-10-10 19:31:10 +0000607 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
608 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200609 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200610
Eric Laurent39095982021-08-24 18:29:27 +0200611 if (output != AUDIO_IO_HANDLE_NONE) {
Andy Hung79eacdb2023-11-30 19:34:24 -0800612 audio_utils::lock_guard _l(mMutex);
Eric Laurent39095982021-08-24 18:29:27 +0200613 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200614 }
615 }
616 }
617}
618
Eric Laurentb16eac52024-08-02 16:46:08 +0000619std::vector<audio_channel_mask_t> AudioPolicyService::getActiveTracksMasks_l(
Eric Laurent11094172022-04-05 18:27:42 +0200620 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000621 std::vector<audio_channel_mask_t> activeTrackMasks;
Eric Laurent15903592022-02-24 20:44:36 +0100622 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
623 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200624 if (client->io == output && client->active
625 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurentb16eac52024-08-02 16:46:08 +0000626 activeTrackMasks.push_back(client->channelMask);
Eric Laurent15903592022-02-24 20:44:36 +0100627 }
628 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000629 return activeTrackMasks;
Eric Laurent15903592022-02-24 20:44:36 +0100630}
631
632void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
633 if (mSpatializer == nullptr) {
634 return;
635 }
636 mOutputCommandThread->updateActiveSpatializerTracksCommand();
637}
638
639void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
640{
Eric Laurent21270b62022-07-04 15:11:29 +0200641 if (mSpatializer == nullptr) {
642 return;
643 }
644 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurentb16eac52024-08-02 16:46:08 +0000645 std::vector<audio_channel_mask_t> activeTracksMasks;
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200646 {
Andy Hung79eacdb2023-11-30 19:34:24 -0800647 audio_utils::lock_guard _l(mMutex);
Eric Laurentb16eac52024-08-02 16:46:08 +0000648 activeTracksMasks = getActiveTracksMasks_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100649 }
Eric Laurentb16eac52024-08-02 16:46:08 +0000650 mSpatializer->updateActiveTracks(activeTracksMasks);
Eric Laurent15903592022-02-24 20:44:36 +0100651}
652
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800653status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
654 audio_patch_handle_t *handle,
655 int delayMs)
656{
657 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
658}
659
660status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
661 int delayMs)
662{
663 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
664}
665
Eric Laurente1715a42014-05-20 11:30:42 -0700666status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
667 int delayMs)
668{
669 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
670}
671
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800672AudioPolicyService::NotificationClient::NotificationClient(
673 const sp<AudioPolicyService>& service,
674 const sp<media::IAudioPolicyServiceClient>& client,
675 uid_t uid,
676 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800677 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100678 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700679{
680}
681
682AudioPolicyService::NotificationClient::~NotificationClient()
683{
684}
685
686void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
687{
688 sp<NotificationClient> keep(this);
689 sp<AudioPolicyService> service = mService.promote();
690 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800691 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700692 }
693}
694
695void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
696{
Eric Laurente8726fe2015-06-26 09:39:24 -0700697 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700698 mAudioPolicyServiceClient->onAudioPortListUpdate();
699 }
700}
701
702void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
703{
Eric Laurente8726fe2015-06-26 09:39:24 -0700704 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700705 mAudioPolicyServiceClient->onAudioPatchListUpdate();
706 }
707}
Eric Laurent57dae992011-07-24 13:36:09 -0700708
Pattydd807582021-11-04 21:01:03 +0800709void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100710 int flags)
711{
712 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
713 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
714 }
715}
716
717
Jean-Michel Trivide801052015-04-14 19:10:14 -0700718void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700719 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700720{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700721 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800722 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
723 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800724 }
725}
726
727void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800728 int event,
729 const record_client_info_t *clientInfo,
730 const audio_config_base_t *clientConfig,
731 std::vector<effect_descriptor_t> clientEffects,
732 const audio_config_base_t *deviceConfig,
733 std::vector<effect_descriptor_t> effects,
734 audio_patch_handle_t patchHandle,
735 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800736{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700737 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800738 status_t status = [&]() -> status_t {
739 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
740 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
741 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700742 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700743 legacy2aidl_audio_config_base_t_AudioConfigBase(
744 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800745 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
746 convertContainer<std::vector<media::EffectDescriptor>>(
747 clientEffects,
748 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700749 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700750 legacy2aidl_audio_config_base_t_AudioConfigBase(
751 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800752 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
753 convertContainer<std::vector<media::EffectDescriptor>>(
754 effects,
755 legacy2aidl_effect_descriptor_t_EffectDescriptor));
756 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
757 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700758 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
759 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800760 return aidl_utils::statusTFromBinderStatus(
761 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
762 clientInfoAidl,
763 clientConfigAidl,
764 clientEffectsAidl,
765 deviceConfigAidl,
766 effectsAidl,
767 patchHandleAidl,
768 sourceAidl));
769 }();
770 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700771 }
772}
773
Eric Laurente8726fe2015-06-26 09:39:24 -0700774void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
775{
776 mAudioPortCallbacksEnabled = enabled;
777}
778
François Gaffiecfe17322018-11-07 13:41:29 +0100779void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
780{
781 mAudioVolumeGroupCallbacksEnabled = enabled;
782}
Eric Laurente8726fe2015-06-26 09:39:24 -0700783
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700784void AudioPolicyService::NotificationClient::onRoutingUpdated()
785{
786 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
787 mAudioPolicyServiceClient->onRoutingUpdated();
788 }
789}
790
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000791void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
792{
793 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
794 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
795 }
796}
797
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700799 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700800 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801}
802
Andy Hung79eacdb2023-11-30 19:34:24 -0800803static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
804 RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000805{
806 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807}
808
809status_t AudioPolicyService::dumpInternals(int fd)
810{
811 const size_t SIZE = 256;
812 char buffer[SIZE];
813 String8 result;
814
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000815 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800816 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000817 std::stringstream msg;
818 size_t i = 0;
819 for (auto usage : mSupportedSystemUsages) {
820 if (i++ != 0) msg << ", ";
821 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
822 msg << strUsage;
823 } else {
824 msg << usage << " (unknown)";
825 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800826 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000827 if (i == 0) {
828 msg << "None";
829 }
830 msg << std::endl;
831 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800832
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000833 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800834
835 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return NO_ERROR;
837}
838
Eric Laurente8c8b432018-10-17 10:08:02 -0700839void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800840{
Andy Hung79eacdb2023-11-30 19:34:24 -0800841 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -0700842 updateUidStates_l();
843}
844
845void AudioPolicyService::updateUidStates_l()
846{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800847// Go over all active clients and allow capture (does not force silence) in the
848// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800849// The client is in the active assistant list
850// AND is TOP
851// AND an accessibility service is TOP
852// AND source is either VOICE_RECOGNITION OR HOTWORD
853// OR there is no active privacy sensitive capture or call
854// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
855// AND source is VOICE_RECOGNITION OR HOTWORD
856// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800857// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700858// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800859// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800860// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800861// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
862// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800863// OR The client is an accessibility service
864// AND Is on TOP
865// AND the source is VOICE_RECOGNITION or HOTWORD
866// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700867// AND there is no active privacy sensitive capture or call
868// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800869// AND is on TOP
870// AND the source is VOICE_RECOGNITION or HOTWORD
871// OR the client source is virtual (remote submix, call audio TX or RX...)
872// OR the client source is HOTWORD
873// AND is on TOP
874// OR all active clients are using HOTWORD source
875// AND no call is active
876// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
877// OR the client is the current InputMethodService
878// AND a RTT call is active AND the source is VOICE_RECOGNITION
Shunkai Yao7c868ca2024-05-07 01:08:11 +0000879// OR The client is an active communication owner
880// AND is on TOP or latest started
Evan Severson1f700cd2021-02-10 13:10:37 -0800881// OR Any client
882// AND The assistant is not on TOP
883// AND is on TOP or latest started
884// AND there is no active privacy sensitive capture or call
885// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800886
Eric Laurent4e947da2019-10-17 15:24:06 -0700887
Eric Laurent4eb58f12018-12-07 16:41:02 -0800888 sp<AudioRecordClient> topActive;
889 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800890 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700891 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800892 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700893
Eric Laurenta46bedb2018-12-07 18:01:26 -0800894 nsecs_t topStartNs = 0;
895 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800896 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800897 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800898 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800899 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
900 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800901 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800902 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700903 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800904 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
905 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700906 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700907 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700908 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800909
Michael Groovercfd28302018-12-11 19:16:46 -0800910 // if Sensor Privacy is enabled then all recordings should be silenced.
911 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
912 silenceAllRecordings_l();
913 return;
914 }
915
Eric Laurente8c8b432018-10-17 10:08:02 -0700916 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
917 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000918 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
919 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800920 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700921 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800922 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700923
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700924 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700925 // clients which app is in IDLE state are not eligible for top active or
926 // latest active
927 if (appState == APP_STATE_IDLE) {
928 continue;
929 }
930
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700931 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700932 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800933 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700934 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700935 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800936 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800937 bool isPrivacySensitive =
938 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700939
Eric Laurentc21d5692020-02-25 10:24:36 -0800940 if (appState == APP_STATE_TOP) {
941 if (isPrivacySensitive) {
942 if (current->startTimeNs > topSensitiveStartNs) {
943 topSensitiveActive = current;
944 topSensitiveStartNs = current->startTimeNs;
945 }
946 } else {
947 if (current->startTimeNs > topStartNs) {
948 topActive = current;
949 topStartNs = current->startTimeNs;
950 }
951 }
952 if (isAssistant) {
953 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800954 if (isActiveAssistant) {
955 useActiveAssistantList = true;
956 } else if (!useActiveAssistantList) {
957 if (current->startTimeNs > latestAssistantStartNs) {
958 latestActiveAssistant = current;
959 latestAssistantStartNs = current->startTimeNs;
960 }
961 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800962 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800963 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800964 // Clients capturing for HOTWORD are not considered
965 // for latest active to avoid masking regular clients started before
966 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
967 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
968 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700969 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
970 // is marked latest sensitive active even if another app qualifies.
971 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700972 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700973 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700974 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000975 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700976 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700977 latestSensitiveActiveOrComm = current;
978 latestSensitiveStartNs = current->startTimeNs;
979 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800980 }
981 isSensitiveActive = true;
982 } else {
983 if (current->startTimeNs > latestStartNs) {
984 latestActive = current;
985 latestStartNs = current->startTimeNs;
986 }
987 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800988 }
989 }
François Gaffiedb1a4412023-10-10 17:32:33 +0000990 if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
991 !isVirtualSource(current->attributes.source)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700992 onlyHotwordActive = false;
993 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100994 if (currentUid == mPhoneStateOwnerUid &&
995 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700996 isPhoneStateOwnerActive = true;
997 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800998 }
999
Eric Laurent1ff16a72019-03-14 18:35:04 -07001000 // if no active client with UI on Top, consider latest active as top
1001 if (topActive == nullptr) {
1002 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -08001003 topStartNs = latestStartNs;
1004 }
1005 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -07001006 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -08001007 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -07001008 } else if (latestSensitiveActiveOrComm != nullptr) {
1009 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
1010 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001011 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +00001012 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001013 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -07001014 topSensitiveActive = latestSensitiveActiveOrComm;
1015 topSensitiveStartNs = latestSensitiveStartNs;
1016 }
Eric Laurentc21d5692020-02-25 10:24:36 -08001017 }
1018
1019 // If both privacy sensitive and regular capture are active:
1020 // if the regular capture is privileged
1021 // allow concurrency
1022 // else
1023 // favor the privacy sensitive case
1024 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001025 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001026 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001027 }
1028
1029 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1030 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001031 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001032 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001033 if (!current->active) {
1034 continue;
1035 }
1036
Eric Laurent4eb58f12018-12-07 16:41:02 -08001037 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001038 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001039 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001040 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001041 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001042 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1043 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001044
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001045 // TODO: b/339112720
1046 // Refine this logic when we have the correct phone state owner UID. The current issue is
1047 // when a VOIP APP use Telecom API to manage calls, the mPhoneStateOwnerUid is AID_SYSTEM
1048 // instead of the actual VOIP APP UID, so isPhoneStateOwnerActive here is not accurate.
1049 const bool canCaptureIfInCallOrCommunication = [&](const auto& recordClient) REQUIRES(
1050 mMutex) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001051 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001052 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001053 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001054 bool canCaptureCommunication = recordClient->canCaptureOutput
1055 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001056 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001057 return !(isInCall && !canCaptureCall)
1058 && !(isInCommunication && !canCaptureCommunication);
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001059 }(current);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001060
1061 // By default allow capture if:
1062 // The assistant is not on TOP
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001063 // AND is on TOP or latest started
1064 // AND there is no active privacy sensitive capture or call
Eric Laurent1ff16a72019-03-14 18:35:04 -07001065 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001066 // The assistant is on TOP
1067 // AND is ongoing communication owner
1068 // AND is on TOP or latest started
1069 const bool allowSensitiveCapture =
Eric Laurent4ab18412022-11-07 16:25:32 +01001070 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001071 bool allowCapture = false;
1072 if (!isAssistantOnTop) {
1073 allowCapture = (isTopOrLatestActive || isTopOrLatestSensitive) &&
1074 allowSensitiveCapture && canCaptureIfInCallOrCommunication;
1075 } else {
1076 allowCapture = isInCommunication && isTopOrLatestSensitive &&
1077 canCaptureIfInCallOrCommunication;
1078 }
Eric Laurent2dc962b2019-03-01 08:25:25 -08001079
Eric Laurented726cc2021-07-01 14:26:41 +02001080 if (!current->hasOp()) {
1081 // Never allow capture if app op is denied
1082 allowCapture = false;
1083 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001084 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1085 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001086 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001087 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001088 // Active assistant list is not being used
1089 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001090 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001091 // OR there is no active privacy sensitive capture or call
1092 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1093 // AND is latest TOP assistant AND
1094 // uses VOICE_RECOGNITION OR uses HOTWORD
1095 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001096 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001097 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001098 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001099 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001100 } else if (allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001101 && canCaptureIfInCallOrCommunication) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001102 if (isTopOrLatestAssistant
1103 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1104 || source == AUDIO_SOURCE_HOTWORD)) {
1105 allowCapture = true;
1106 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1107 allowCapture = true;
1108 }
1109 }
1110 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1111 // For assistant on active list and on top allow capture if:
1112 // An accessibility service is on TOP
1113 // AND the source is VOICE_RECOGNITION or HOTWORD
1114 // OR there is no active privacy sensitive capture or call
1115 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1116 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1117 if (isA11yOnTop) {
1118 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1119 allowCapture = true;
1120 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001121 } else if (allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001122 && canCaptureIfInCallOrCommunication) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001123 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1124 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001125 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001126 }
1127 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001128 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001129 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001130 // The assistant is not on TOP
1131 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001132 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001133 // OR
1134 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1135 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001136 && allowSensitiveCapture
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001137 && canCaptureIfInCallOrCommunication) {
Eric Laurent47670c92019-08-28 16:59:05 -07001138 allowCapture = true;
1139 }
Eric Laurent589171c2019-07-25 18:04:29 -07001140 if (isA11yOnTop) {
1141 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1142 allowCapture = true;
1143 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001144 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001145 } else if (source == AUDIO_SOURCE_HOTWORD) {
1146 // For HOTWORD source allow capture when not on TOP if:
1147 // All active clients are using HOTWORD source
1148 // AND no call is active
1149 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001150 if (onlyHotwordActive
Shunkai Yao7c868ca2024-05-07 01:08:11 +00001151 && canCaptureIfInCallOrCommunication) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001152 allowCapture = true;
1153 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001154 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001155 // For current InputMethodService allow capture if:
1156 // A RTT call is active AND the source is VOICE_RECOGNITION
1157 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1158 allowCapture = true;
1159 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001160 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001161 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001162 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001163 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001164 }
1165}
1166
Michael Groovercfd28302018-12-11 19:16:46 -08001167void AudioPolicyService::silenceAllRecordings_l() {
1168 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1169 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001170 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001171 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001172 }
Michael Groovercfd28302018-12-11 19:16:46 -08001173 }
1174}
1175
Eric Laurente8c8b432018-10-17 10:08:02 -07001176/* static */
1177app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001178
1179 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001180 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001181 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1182 // include persistent services
1183 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001184 }
1185 return APP_STATE_FOREGROUND;
1186}
1187
Eric Laurent4eb58f12018-12-07 16:41:02 -08001188/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001189bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001190{
1191 switch (source) {
1192 case AUDIO_SOURCE_VOICE_UPLINK:
1193 case AUDIO_SOURCE_VOICE_DOWNLINK:
1194 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001195 case AUDIO_SOURCE_REMOTE_SUBMIX:
1196 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001197 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001198 return true;
1199 default:
1200 break;
1201 }
1202 return false;
1203}
1204
Eric Laurent8c7ef892021-06-10 13:32:16 +02001205void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001206{
1207 AutoCallerClear acc;
1208
1209 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001210 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001211 }
1212 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1213 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001214 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001215 if (client->silenced != silenced) {
1216 if (client->active) {
1217 if (silenced) {
Marvin Raminb03b49f2024-04-04 16:25:31 +02001218 finishRecording(client->attributionSource, client->virtualDeviceId,
1219 client->attributes.source);
Eric Laurent8c7ef892021-06-10 13:32:16 +02001220 } else {
1221 std::stringstream msg;
1222 msg << "Audio recording un-silenced on session " << client->session;
Atneya Nairdb6ef1e2024-09-16 20:26:30 +00001223 if (startRecording(client->attributionSource, client->virtualDeviceId,
1224 String16(msg.str().c_str()), client->attributes.source)
1225 != PERMISSION_GRANTED) {
1226 return;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001227 }
1228 }
1229 }
1230 af->setRecordSilenced(client->portId, silenced);
1231 client->silenced = silenced;
1232 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001233 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001234}
1235
Glenn Kasten0f11b512014-01-31 16:18:54 -08001236status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Andy Hung79eacdb2023-11-30 19:34:24 -08001237NO_THREAD_SAFETY_ANALYSIS // update for trylock.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238{
Glenn Kasten44deb052012-02-05 18:09:08 -08001239 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 dumpPermissionDenial(fd);
1241 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001242 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243 if (!locked) {
1244 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001245 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 }
1247
1248 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001249
1250 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001251 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001252 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 mAudioCommandThread->dump(fd);
1254 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001256 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001257 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001258 if (mOutputCommandThread != 0) {
1259 mOutputCommandThread->dump(fd);
1260 }
1261
Eric Laurentdce54a12014-03-10 12:19:46 -07001262 if (mAudioPolicyManager) {
1263 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001264 } else {
1265 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001266 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001267 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268
Kevin Rocard8be94972019-02-22 13:26:25 -08001269 mPackageManager.dump(fd);
1270
Andy Hung79eacdb2023-11-30 19:34:24 -08001271 dumpReleaseLock(mMutex, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001272
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001273 if (mSpatializer != nullptr) {
1274 std::string dumpString = mSpatializer->toString(1 /* level */);
1275 write(fd, dumpString.c_str(), dumpString.size());
1276 } else {
1277 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1278 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1279 }
1280
Andy Hungc747c532022-03-07 21:41:14 -08001281 {
1282 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1283 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1284 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 }
1287 return NO_ERROR;
1288}
1289
1290status_t AudioPolicyService::dumpPermissionDenial(int fd)
1291{
1292 const size_t SIZE = 256;
1293 char buffer[SIZE];
1294 String8 result;
1295 snprintf(buffer, SIZE, "Permission Denial: "
1296 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1297 IPCThreadState::self()->getCallingPid(),
1298 IPCThreadState::self()->getCallingUid());
1299 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001300 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301 return NO_ERROR;
1302}
1303
1304status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001305 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001306 // make sure transactions reserved to AudioFlinger do not come from other processes
1307 switch (code) {
1308 case TRANSACTION_startOutput:
1309 case TRANSACTION_stopOutput:
1310 case TRANSACTION_releaseOutput:
1311 case TRANSACTION_getInputForAttr:
1312 case TRANSACTION_startInput:
1313 case TRANSACTION_stopInput:
1314 case TRANSACTION_releaseInput:
1315 case TRANSACTION_getOutputForEffect:
1316 case TRANSACTION_registerEffect:
1317 case TRANSACTION_unregisterEffect:
1318 case TRANSACTION_setEffectEnabled:
1319 case TRANSACTION_getStrategyForStream:
1320 case TRANSACTION_getOutputForAttr:
1321 case TRANSACTION_moveEffectsToIo:
1322 ALOGW("%s: transaction %d received from PID %d",
1323 __func__, code, IPCThreadState::self()->getCallingPid());
1324 return INVALID_OPERATION;
1325 default:
1326 break;
1327 }
1328
1329 // make sure the following transactions come from system components
1330 switch (code) {
1331 case TRANSACTION_setDeviceConnectionState:
1332 case TRANSACTION_handleDeviceConfigChange:
1333 case TRANSACTION_setPhoneState:
1334//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1335// case TRANSACTION_setForceUse:
Vlad Popa87e0e582024-05-20 18:49:20 -07001336 case TRANSACTION_setDeviceAbsoluteVolumeEnabled:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001337 case TRANSACTION_initStreamVolume:
1338 case TRANSACTION_setStreamVolumeIndex:
1339 case TRANSACTION_setVolumeIndexForAttributes:
1340 case TRANSACTION_getStreamVolumeIndex:
1341 case TRANSACTION_getVolumeIndexForAttributes:
1342 case TRANSACTION_getMinVolumeIndexForAttributes:
1343 case TRANSACTION_getMaxVolumeIndexForAttributes:
1344 case TRANSACTION_isStreamActive:
1345 case TRANSACTION_isStreamActiveRemotely:
1346 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001347 case TRANSACTION_registerPolicyMixes:
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02001348 case TRANSACTION_updatePolicyMixes:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001349 case TRANSACTION_setMasterMono:
1350 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001351 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001352 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001353 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001354 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001355 case TRANSACTION_setA11yServicesUids:
1356 case TRANSACTION_setUidDeviceAffinities:
1357 case TRANSACTION_removeUidDeviceAffinities:
1358 case TRANSACTION_setUserIdDeviceAffinities:
1359 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001360 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001361 case TRANSACTION_listAudioVolumeGroups:
1362 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1363 case TRANSACTION_acquireSoundTriggerSession:
1364 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001365 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001366 case TRANSACTION_setRttEnabled:
1367 case TRANSACTION_isCallScreenModeSupported:
1368 case TRANSACTION_setDevicesRoleForStrategy:
1369 case TRANSACTION_setSupportedSystemUsages:
1370 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001371 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001372 case TRANSACTION_getDevicesForRoleAndStrategy:
1373 case TRANSACTION_getDevicesForAttributes:
1374 case TRANSACTION_setAllowedCapturePolicy:
1375 case TRANSACTION_onNewAudioModulesAvailable:
1376 case TRANSACTION_setCurrentImeUid:
1377 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1378 case TRANSACTION_setDevicesRoleForCapturePreset:
1379 case TRANSACTION_addDevicesRoleForCapturePreset:
1380 case TRANSACTION_removeDevicesRoleForCapturePreset:
1381 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001382 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001383 case TRANSACTION_getSpatializer:
1384 case TRANSACTION_setPreferredMixerAttributes:
Marvin Raminbdefaf02023-11-01 09:10:32 +01001385 case TRANSACTION_clearPreferredMixerAttributes:
1386 case TRANSACTION_getRegisteredPolicyMixes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001387 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1388 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1389 __func__, code, IPCThreadState::self()->getCallingPid(),
1390 IPCThreadState::self()->getCallingUid());
1391 return INVALID_OPERATION;
1392 }
1393 } break;
1394 default:
1395 break;
1396 }
1397
Atneya Nair9f91a5e2024-05-09 16:25:05 -07001398 switch (code) {
1399 case TRANSACTION_getPermissionController: {
1400 if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1401 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1402 __func__, code, IPCThreadState::self()->getCallingPid(),
1403 IPCThreadState::self()->getCallingUid());
1404 return INVALID_OPERATION;
1405 }
1406 }
1407 }
1408
Andy Hungc747c532022-03-07 21:41:14 -08001409 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1410 mediautils::TimeCheck check(
1411 std::string("IAudioPolicyService::").append(methodName),
1412 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1413 if (timeout) {
1414 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1415 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1416 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1417 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1418 .record();
1419 } else {
1420 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1421 }
Andy Hung7cd77742024-08-06 15:17:16 -07001422 }, mediautils::TimeCheck::getDefaultTimeoutDuration(),
1423 mediautils::TimeCheck::getDefaultSecondChanceDuration(),
Atneya Nairc5b34362024-08-27 17:31:38 -07001424 !property_get_bool("audio.timecheck.disabled", false) /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001425
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001426 switch (code) {
1427 case SHELL_COMMAND_TRANSACTION: {
1428 int in = data.readFileDescriptor();
1429 int out = data.readFileDescriptor();
1430 int err = data.readFileDescriptor();
1431 int argc = data.readInt32();
1432 Vector<String16> args;
1433 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1434 args.add(data.readString16());
1435 }
1436 sp<IBinder> unusedCallback;
1437 sp<IResultReceiver> resultReceiver;
1438 status_t status;
1439 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1440 return status;
1441 }
1442 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1443 return status;
1444 }
1445 status = shellCommand(in, out, err, args);
1446 if (resultReceiver != nullptr) {
1447 resultReceiver->send(status);
1448 }
1449 return NO_ERROR;
1450 }
1451 }
1452
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1454}
1455
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001456// ------------------- Shell command implementation -------------------
1457
1458// NOTE: This is a remote API - make sure all args are validated
1459status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1460 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1461 return PERMISSION_DENIED;
1462 }
1463 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1464 return BAD_VALUE;
1465 }
Atneya Nair56a436a2024-04-03 11:11:58 -07001466 if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
Eric Laurent269acb42021-04-23 16:53:22 +02001467 purgePermissionCache();
1468 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001469 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001470 return BAD_VALUE;
1471}
1472
Eric Laurent0d13fea2022-11-04 17:12:08 +01001473status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1474 const audio_config_base_t& config,
1475 const audio_output_flags_t flags) {
1476 return mUsecaseValidator->registerStream(output, config, flags);
1477}
1478
1479status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1480 return mUsecaseValidator->unregisterStream(output);
1481}
1482
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001483// ----------- AudioPolicyService::UidPolicy implementation ----------
1484
1485void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001486 status_t res = mAm.linkToDeath(this);
1487 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001488 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001489 | ActivityManager::UID_OBSERVER_ACTIVE
1490 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001491 ActivityManager::PROCESS_STATE_UNKNOWN,
1492 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001493 if (!res) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001494 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001495 mObserverRegistered = true;
1496 } else {
1497 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001498
Steven Moreland2f348142019-07-02 15:59:07 -07001499 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001500 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001501}
1502
1503void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001504 mAm.unlinkToDeath(this);
1505 mAm.unregisterUidObserver(this);
Andy Hung79eacdb2023-11-30 19:34:24 -08001506 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001507 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001508}
1509
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001510void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001511 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001512 mCachedUids.clear();
1513 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001514}
1515
Eric Laurente8c8b432018-10-17 10:08:02 -07001516void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001517 bool needToReregister = false;
1518 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001519 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001520 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001521 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001522 if (needToReregister) {
1523 // Looks like ActivityManager has died previously, attempt to re-register.
1524 registerSelf();
1525 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001526}
1527
1528bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1529 if (isServiceUid(uid)) return true;
1530 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001531 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001532 audio_utils::lock_guard _l(mMutex);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001533 // In an absense of the ActivityManager, assume everything to be active.
1534 if (!mObserverRegistered) return true;
1535 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001536 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001537 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001538 }
1539 }
1540 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001541 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001542 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001543 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001544 mCachedUids.insert(std::pair<uid_t,
1545 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1546 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001547 }
1548 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001549}
1550
Eric Laurente8c8b432018-10-17 10:08:02 -07001551int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1552 if (isServiceUid(uid)) {
1553 return ActivityManager::PROCESS_STATE_TOP;
1554 }
1555 checkRegistered();
1556 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001557 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001558 // In an absense of the ActivityManager, assume everything to be active.
1559 if (!mObserverRegistered) {
1560 return ActivityManager::PROCESS_STATE_TOP;
1561 }
1562 auto cacheIter = mCachedUids.find(uid);
1563 if (cacheIter != mCachedUids.end()) {
1564 if (cacheIter->second.first) {
1565 return cacheIter->second.second;
1566 } else {
1567 return ActivityManager::PROCESS_STATE_UNKNOWN;
1568 }
1569 }
1570 }
1571 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001572 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001573 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1574 if (active) {
1575 state = am.getUidProcessState(uid, String16("audioserver"));
1576 }
1577 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001578 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001579 mCachedUids.insert(std::pair<uid_t,
1580 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1581 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001582
Eric Laurente8c8b432018-10-17 10:08:02 -07001583 return state;
1584}
1585
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001586void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001587 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001588}
1589
1590void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001591 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001592}
1593
1594void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001595 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001596}
1597
Eric Laurente8c8b432018-10-17 10:08:02 -07001598void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1599 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001600 int64_t procStateSeq __unused,
1601 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001602 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1603 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001604 }
1605}
1606
Austin Borgerdddb7552023-03-30 17:53:01 -07001607void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001608}
1609
Eric Laurente8c8b432018-10-17 10:08:02 -07001610void AudioPolicyService::UidPolicy::notifyService() {
1611 sp<AudioPolicyService> service = mService.promote();
1612 if (service != nullptr) {
1613 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001614 }
1615}
1616
Eric Laurente8c8b432018-10-17 10:08:02 -07001617void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1618 std::pair<bool, int>> *uids,
1619 uid_t uid,
1620 bool active,
1621 int state,
1622 bool insert) {
1623 if (isServiceUid(uid)) {
1624 return;
1625 }
1626 bool wasActive = isUidActive(uid);
1627 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001628 {
Andy Hung79eacdb2023-11-30 19:34:24 -08001629 audio_utils::lock_guard _l(mMutex);
Eric Laurente8c8b432018-10-17 10:08:02 -07001630 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001631 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001632 if (wasActive != isUidActive(uid) || state != previousState) {
1633 notifyService();
1634 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001635}
1636
Eric Laurente8c8b432018-10-17 10:08:02 -07001637void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1638 std::pair<bool, int>> *uids,
1639 uid_t uid,
1640 bool active,
1641 int state,
1642 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001643 auto it = uids->find(uid);
1644 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001645 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001646 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1647 it->second.first = active;
1648 }
1649 if (it->second.first) {
1650 it->second.second = state;
1651 } else {
1652 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1653 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001654 } else {
1655 uids->erase(it);
1656 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001657 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1658 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1659 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001660 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001661}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662
Eric Laurent4eb58f12018-12-07 16:41:02 -08001663bool AudioPolicyService::UidPolicy::isA11yOnTop() {
Andy Hung79eacdb2023-11-30 19:34:24 -08001664 audio_utils::lock_guard _l(mMutex);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001665 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001666 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001667 continue;
1668 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001669 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1670 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001671 return true;
1672 }
1673 }
1674 return false;
1675}
1676
Eric Laurentb78763e2018-10-17 10:08:02 -07001677bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1678{
1679 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1680 return it != mA11yUids.end();
1681}
1682
Oscar Azucena829d90d2022-01-28 17:17:56 -08001683void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1684 mAssistantUids.clear();
1685 mAssistantUids = uids;
1686}
1687
1688bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1689{
1690 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1691 return it != mAssistantUids.end();
1692}
1693
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001694void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1695 mActiveAssistantUids = activeUids;
1696}
1697
1698bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1699{
1700 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1701 mActiveAssistantUids.end(), uid);
1702 return it != mActiveAssistantUids.end();
1703}
1704
Oscar Azucena829d90d2022-01-28 17:17:56 -08001705void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1706 const size_t SIZE = 256;
1707 char buffer[SIZE];
1708 String8 result;
1709 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1710 snprintf(buffer, SIZE, "\t%s: \n", title);
1711 result.append(buffer);
1712 int counter = 0;
1713 if (uids.empty()) {
1714 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1715 result.append(buffer);
1716 return;
1717 }
1718 for (const auto &uid : uids) {
1719 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1720 result.append(buffer);
1721 }
1722 };
1723
1724 snprintf(buffer, SIZE, "UID Policy:\n");
1725 result.append(buffer);
1726 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1727 result.append(buffer);
1728
1729 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001730 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001731
1732 appendUidsToResult("Accessibility UIDs", mA11yUids);
1733
1734 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1735 result.append(buffer);
1736
1737 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1738 result.append(buffer);
1739
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001740 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001741}
1742
Michael Groovercfd28302018-12-11 19:16:46 -08001743// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1744void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1745 SensorPrivacyManager spm;
1746 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1747 spm.addSensorPrivacyListener(this);
1748}
1749
1750void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1751 SensorPrivacyManager spm;
1752 spm.removeSensorPrivacyListener(this);
1753}
1754
1755bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1756 return mSensorPrivacyEnabled;
1757}
1758
Evan Seversond8dc6832022-01-27 10:47:03 -08001759binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1760 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001761 mSensorPrivacyEnabled = enabled;
1762 sp<AudioPolicyService> service = mService.promote();
1763 if (service != nullptr) {
1764 service->updateUidStates();
1765 }
1766 return binder::Status::ok();
1767}
1768
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1770
Eric Laurentbfb1b832013-01-07 09:53:42 -08001771AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1772 const wp<AudioPolicyService>& service)
1773 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775}
1776
1777
1778AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1779{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001780 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001781 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782 }
1783 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784}
1785
1786void AudioPolicyService::AudioCommandThread::onFirstRef()
1787{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001788 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789}
1790
1791bool AudioPolicyService::AudioCommandThread::threadLoop()
1792{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001793 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794
Andy Hung79eacdb2023-11-30 19:34:24 -08001795 audio_utils::unique_lock ul(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 while (!exitPending())
1797 {
Eric Laurent59a89232014-06-08 14:14:17 -07001798 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001799 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001800 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 nsecs_t curTime = systemTime();
1802 // commands are sorted by increasing time stamp: execute them from index 0 and up
1803 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001804 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001806 if (mAudioCommands.isEmpty()) {
1807 ++numTimesBecameEmpty;
1808 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001809 mLastCommand = command;
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02001810 status_t createAudioPatchStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811
1812 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001814 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001815 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001816 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001817 ul.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001818 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1819 data->mVolume,
1820 data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001821 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 }break;
Andy Hung6b137d12024-08-27 22:35:17 +00001823 case SET_PORTS_VOLUME: {
1824 VolumePortsData *data = (VolumePortsData *)command->mParam.get();
1825 ALOGV("AudioCommandThread() processing set volume Ports %s volume %f, \
1826 output %d", data->dumpPorts().c_str(), data->mVolume, data->mIO);
1827 ul.unlock();
1828 command->mStatus = AudioSystem::setPortsVolume(data->mPorts,
1829 data->mVolume,
1830 data->mIO);
1831 ul.lock();
1832 } break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001834 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001835 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001836 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hung79eacdb2023-11-30 19:34:24 -08001837 ul.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001838 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hung79eacdb2023-11-30 19:34:24 -08001839 ul.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001840 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001842 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001843 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001844 data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001845 ul.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hung79eacdb2023-11-30 19:34:24 -08001847 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001849 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001850 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001851 ALOGV("AudioCommandThread() processing stop output portId %d",
1852 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001853 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001854 if (svc == 0) {
1855 break;
1856 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001857 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001858 svc->doStopOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001859 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001860 }break;
1861 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001862 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001863 ALOGV("AudioCommandThread() processing release output portId %d",
1864 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001865 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001866 if (svc == 0) {
1867 break;
1868 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001869 ul.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001870 svc->doReleaseOutput(data->mPortId);
Andy Hung79eacdb2023-11-30 19:34:24 -08001871 ul.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001872 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001873 case CREATE_AUDIO_PATCH: {
1874 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1875 ALOGV("AudioCommandThread() processing create audio patch");
1876 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1877 if (af == 0) {
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02001878 createAudioPatchStatus = PERMISSION_DENIED;
Eric Laurent951f4552014-05-20 10:48:17 -07001879 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001880 ul.unlock();
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02001881 createAudioPatchStatus = af->createAudioPatch(&data->mPatch,
1882 &data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001883 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001884 }
1885 } break;
1886 case RELEASE_AUDIO_PATCH: {
1887 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1888 ALOGV("AudioCommandThread() processing release audio patch");
1889 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1890 if (af == 0) {
1891 command->mStatus = PERMISSION_DENIED;
1892 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001893 ul.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001894 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hung79eacdb2023-11-30 19:34:24 -08001895 ul.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001896 }
1897 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001898 case UPDATE_AUDIOPORT_LIST: {
1899 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001900 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001901 if (svc == 0) {
1902 break;
1903 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001904 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001905 svc->doOnAudioPortListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001906 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001907 }break;
1908 case UPDATE_AUDIOPATCH_LIST: {
1909 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001910 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001911 if (svc == 0) {
1912 break;
1913 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001914 ul.unlock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001915 svc->doOnAudioPatchListUpdate();
Andy Hung79eacdb2023-11-30 19:34:24 -08001916 ul.lock();
Eric Laurentb52c1522014-05-20 11:27:36 -07001917 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001918 case CHANGED_AUDIOVOLUMEGROUP: {
1919 AudioVolumeGroupData *data =
1920 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1921 ALOGV("AudioCommandThread() processing update audio volume group");
1922 svc = mService.promote();
1923 if (svc == 0) {
1924 break;
1925 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001926 ul.unlock();
François Gaffiecfe17322018-11-07 13:41:29 +01001927 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
Andy Hung79eacdb2023-11-30 19:34:24 -08001928 ul.lock();
François Gaffiecfe17322018-11-07 13:41:29 +01001929 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001930 case SET_AUDIOPORT_CONFIG: {
1931 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1932 ALOGV("AudioCommandThread() processing set port config");
1933 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1934 if (af == 0) {
1935 command->mStatus = PERMISSION_DENIED;
1936 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08001937 ul.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001938 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hung79eacdb2023-11-30 19:34:24 -08001939 ul.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001940 }
1941 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001942 case DYN_POLICY_MIX_STATE_UPDATE: {
1943 DynPolicyMixStateUpdateData *data =
1944 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001945 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001946 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07001947 svc = mService.promote();
1948 if (svc == 0) {
1949 break;
1950 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001951 ul.unlock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001952 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
Andy Hung79eacdb2023-11-30 19:34:24 -08001953 ul.lock();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001954 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001955 case RECORDING_CONFIGURATION_UPDATE: {
1956 RecordingConfigurationUpdateData *data =
1957 (RecordingConfigurationUpdateData *)command->mParam.get();
1958 ALOGV("AudioCommandThread() processing recording configuration update");
1959 svc = mService.promote();
1960 if (svc == 0) {
1961 break;
1962 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001963 ul.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001964 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001965 &data->mClientConfig, data->mClientEffects,
1966 &data->mDeviceConfig, data->mEffects,
1967 data->mPatchHandle, data->mSource);
Andy Hung79eacdb2023-11-30 19:34:24 -08001968 ul.lock();
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001969 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001970 case SET_EFFECT_SUSPENDED: {
1971 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1972 ALOGV("AudioCommandThread() processing set effect suspended");
1973 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1974 if (af != 0) {
Andy Hung79eacdb2023-11-30 19:34:24 -08001975 ul.unlock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001976 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
Andy Hung79eacdb2023-11-30 19:34:24 -08001977 ul.lock();
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001978 }
1979 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001980 case AUDIO_MODULES_UPDATE: {
1981 ALOGV("AudioCommandThread() processing audio modules update");
1982 svc = mService.promote();
1983 if (svc == 0) {
1984 break;
1985 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001986 ul.unlock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001987 svc->doOnNewAudioModulesAvailable();
Andy Hung79eacdb2023-11-30 19:34:24 -08001988 ul.lock();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001989 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001990 case ROUTING_UPDATED: {
1991 ALOGV("AudioCommandThread() processing routing update");
1992 svc = mService.promote();
1993 if (svc == 0) {
1994 break;
1995 }
Andy Hung79eacdb2023-11-30 19:34:24 -08001996 ul.unlock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001997 svc->doOnRoutingUpdated();
Andy Hung79eacdb2023-11-30 19:34:24 -08001998 ul.lock();
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001999 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002000
Eric Laurented726cc2021-07-01 14:26:41 +02002001 case UPDATE_UID_STATES: {
2002 ALOGV("AudioCommandThread() processing updateUID states");
2003 svc = mService.promote();
2004 if (svc == 0) {
2005 break;
2006 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002007 ul.unlock();
Eric Laurented726cc2021-07-01 14:26:41 +02002008 svc->updateUidStates();
Andy Hung79eacdb2023-11-30 19:34:24 -08002009 ul.lock();
Eric Laurented726cc2021-07-01 14:26:41 +02002010 } break;
2011
Eric Laurent15903592022-02-24 20:44:36 +01002012 case CHECK_SPATIALIZER_OUTPUT: {
2013 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002014 svc = mService.promote();
2015 if (svc == 0) {
2016 break;
2017 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002018 ul.unlock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002019 svc->doOnCheckSpatializer();
Andy Hung79eacdb2023-11-30 19:34:24 -08002020 ul.lock();
Eric Laurent81dd0f52021-07-05 11:54:40 +02002021 } break;
2022
Eric Laurent15903592022-02-24 20:44:36 +01002023 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2024 ALOGV("AudioCommandThread() processing update spatializer tracks");
2025 svc = mService.promote();
2026 if (svc == 0) {
2027 break;
2028 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002029 ul.unlock();
Eric Laurent15903592022-02-24 20:44:36 +01002030 svc->doOnUpdateActiveSpatializerTracks();
Andy Hung79eacdb2023-11-30 19:34:24 -08002031 ul.lock();
Eric Laurent15903592022-02-24 20:44:36 +01002032 } break;
2033
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002034 case VOL_RANGE_INIT_REQUEST: {
2035 ALOGV("AudioCommandThread() processing volume range init request");
2036 svc = mService.promote();
2037 if (svc == 0) {
2038 break;
2039 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002040 ul.unlock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002041 svc->doOnVolumeRangeInitRequest();
Andy Hung79eacdb2023-11-30 19:34:24 -08002042 ul.lock();
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002043 } break;
2044
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002046 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002048 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002049 audio_utils::lock_guard _l(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002050 if (command->mWaitStatus) {
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02002051 if (command->mCommand == CREATE_AUDIO_PATCH) {
2052 command->mStatus = createAudioPatchStatus;
2053 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002054 command->mWaitStatus = false;
Andy Hung79eacdb2023-11-30 19:34:24 -08002055 command->mCond.notify_one();
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02002056 } else if (command->mCommand == CREATE_AUDIO_PATCH &&
2057 command->mStatus == TIMED_OUT &&
2058 createAudioPatchStatus == NO_ERROR) {
2059 // Because of special handling in insertCommand_l() the CREATE_AUDIO_PATCH
2060 // command wait status can be only false in case timeout (see TIMED_OUT)
2061 // happened.
2062 CreateAudioPatchData *createData =
2063 (CreateAudioPatchData *)command->mParam.get();
2064 ALOGW("AudioCommandThread() no caller awaiting for handle(%d) after \
2065 processing create audio patch, going to release it",
2066 createData->mHandle);
2067 sp<AudioCommand> releaseCommand = new AudioCommand();
2068 releaseCommand->mCommand = RELEASE_AUDIO_PATCH;
2069 ReleaseAudioPatchData *releaseData = new ReleaseAudioPatchData();
2070 releaseData->mHandle = createData->mHandle;
2071 releaseCommand->mParam = releaseData;
2072 insertCommand_l(releaseCommand, 0);
Eric Laurent0ede8922014-05-09 18:04:42 -07002073 }
2074 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002075 waitTime = -1;
Andy Hung79eacdb2023-11-30 19:34:24 -08002076 // release ul before releasing strong reference on the service as
Zach Janga754b4f2015-10-27 01:29:34 +00002077 // AudioPolicyService destructor calls AudioCommandThread::exit() which
Andy Hung79eacdb2023-11-30 19:34:24 -08002078 // acquires ul.
2079 ul.unlock();
Zach Janga754b4f2015-10-27 01:29:34 +00002080 svc.clear();
Andy Hung79eacdb2023-11-30 19:34:24 -08002081 ul.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 } else {
2083 waitTime = mAudioCommands[0]->mTime - curTime;
2084 break;
2085 }
2086 }
Zach Janga754b4f2015-10-27 01:29:34 +00002087
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002088 // release delayed commands wake lock as many times as we made the queue is
2089 // empty during popping.
2090 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002091 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002092 }
2093
2094 // At this stage we have either an empty command queue or the first command in the queue
2095 // has a finite delay. So unless we are exiting it is safe to wait.
2096 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002097 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002098 if (waitTime == -1) {
Andy Hung79eacdb2023-11-30 19:34:24 -08002099 mWaitWorkCV.wait(ul);
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002100 } else {
Andy Hung79eacdb2023-11-30 19:34:24 -08002101 // discard return value.
2102 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002103 }
Eric Laurent59a89232014-06-08 14:14:17 -07002104 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002106 // release delayed commands wake lock before quitting
2107 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002108 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002109 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 return false;
2111}
2112
2113status_t AudioPolicyService::AudioCommandThread::dump(int fd)
Andy Hung79eacdb2023-11-30 19:34:24 -08002114NO_THREAD_SAFETY_ANALYSIS // trylock
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115{
2116 const size_t SIZE = 256;
2117 char buffer[SIZE];
2118 String8 result;
2119
Andy Hung79eacdb2023-11-30 19:34:24 -08002120 const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 if (!locked) {
2122 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002123 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 }
2125
2126 snprintf(buffer, SIZE, "- Commands:\n");
2127 result = String8(buffer);
2128 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002129 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 mAudioCommands[i]->dump(buffer, SIZE);
2131 result.append(buffer);
2132 }
2133 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002134 if (mLastCommand != 0) {
2135 mLastCommand->dump(buffer, SIZE);
2136 result.append(buffer);
2137 } else {
2138 result.append(" none\n");
2139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002141 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142
Andy Hung79eacdb2023-11-30 19:34:24 -08002143 dumpReleaseLock(mMutex, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144
2145 return NO_ERROR;
2146}
2147
Glenn Kastenfff6d712012-01-12 16:38:12 -08002148status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002149 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002150 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002151 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152{
Eric Laurent0ede8922014-05-09 18:04:42 -07002153 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002154 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002155 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156 data->mStream = stream;
2157 data->mVolume = volume;
2158 data->mIO = output;
2159 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002160 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002161 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002162 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002163 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164}
2165
Andy Hung6b137d12024-08-27 22:35:17 +00002166status_t AudioPolicyService::AudioCommandThread::volumePortsCommand(
2167 const std::vector<audio_port_handle_t> &ports, float volume, audio_io_handle_t output,
2168 int delayMs)
2169{
2170 sp<AudioCommand> command = new AudioCommand();
2171 command->mCommand = SET_PORTS_VOLUME;
2172 sp<VolumePortsData> data = new VolumePortsData();
2173 data->mPorts = ports;
2174 data->mVolume = volume;
2175 data->mIO = output;
2176 command->mParam = data;
2177 command->mWaitStatus = true;
2178 ALOGV("AudioCommandThread() adding set volume ports %s, volume %f, output %d",
2179 data->dumpPorts().c_str(), volume, output);
2180 return sendCommand(command, delayMs);
2181}
2182
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002183status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002184 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002185 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186{
Eric Laurent0ede8922014-05-09 18:04:42 -07002187 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002189 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002191 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002193 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002194 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002195 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002196 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197}
2198
2199status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2200{
Eric Laurent0ede8922014-05-09 18:04:42 -07002201 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002203 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 data->mVolume = volume;
2205 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002206 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002207 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002208 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209}
2210
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002211void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2212 audio_session_t sessionId,
2213 bool suspended)
2214{
2215 sp<AudioCommand> command = new AudioCommand();
2216 command->mCommand = SET_EFFECT_SUSPENDED;
2217 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2218 data->mEffectId = effectId;
2219 data->mSessionId = sessionId;
2220 data->mSuspended = suspended;
2221 command->mParam = data;
2222 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2223 effectId, sessionId, suspended);
2224 sendCommand(command);
2225}
2226
2227
Eric Laurentd7fe0862018-07-14 16:48:01 -07002228void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002229{
Eric Laurent0ede8922014-05-09 18:04:42 -07002230 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002231 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002232 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002233 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002234 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002235 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002236 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002237}
2238
Eric Laurentd7fe0862018-07-14 16:48:01 -07002239void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240{
Eric Laurent0ede8922014-05-09 18:04:42 -07002241 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002242 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002243 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002244 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002245 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002246 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002247 sendCommand(command);
2248}
2249
Eric Laurent951f4552014-05-20 10:48:17 -07002250status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2251 const struct audio_patch *patch,
2252 audio_patch_handle_t *handle,
2253 int delayMs)
2254{
2255 status_t status = NO_ERROR;
2256
2257 sp<AudioCommand> command = new AudioCommand();
2258 command->mCommand = CREATE_AUDIO_PATCH;
2259 CreateAudioPatchData *data = new CreateAudioPatchData();
2260 data->mPatch = *patch;
2261 data->mHandle = *handle;
2262 command->mParam = data;
2263 command->mWaitStatus = true;
2264 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2265 status = sendCommand(command, delayMs);
2266 if (status == NO_ERROR) {
2267 *handle = data->mHandle;
2268 }
2269 return status;
2270}
2271
2272status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2273 int delayMs)
2274{
2275 sp<AudioCommand> command = new AudioCommand();
2276 command->mCommand = RELEASE_AUDIO_PATCH;
2277 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2278 data->mHandle = handle;
2279 command->mParam = data;
2280 command->mWaitStatus = true;
2281 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2282 return sendCommand(command, delayMs);
2283}
2284
Eric Laurentb52c1522014-05-20 11:27:36 -07002285void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2286{
2287 sp<AudioCommand> command = new AudioCommand();
2288 command->mCommand = UPDATE_AUDIOPORT_LIST;
2289 ALOGV("AudioCommandThread() adding update audio port list");
2290 sendCommand(command);
2291}
2292
Eric Laurented726cc2021-07-01 14:26:41 +02002293void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2294{
2295 sp<AudioCommand> command = new AudioCommand();
2296 command->mCommand = UPDATE_UID_STATES;
2297 ALOGV("AudioCommandThread() adding update UID states");
2298 sendCommand(command);
2299}
2300
Eric Laurentb52c1522014-05-20 11:27:36 -07002301void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2302{
2303 sp<AudioCommand>command = new AudioCommand();
2304 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2305 ALOGV("AudioCommandThread() adding update audio patch list");
2306 sendCommand(command);
2307}
2308
François Gaffiecfe17322018-11-07 13:41:29 +01002309void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2310 int flags)
2311{
2312 sp<AudioCommand>command = new AudioCommand();
2313 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2314 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2315 data->mGroup = group;
2316 data->mFlags = flags;
2317 command->mParam = data;
2318 ALOGV("AudioCommandThread() adding audio volume group changed");
2319 sendCommand(command);
2320}
2321
Eric Laurente1715a42014-05-20 11:30:42 -07002322status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2323 const struct audio_port_config *config, int delayMs)
2324{
2325 sp<AudioCommand> command = new AudioCommand();
2326 command->mCommand = SET_AUDIOPORT_CONFIG;
2327 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2328 data->mConfig = *config;
2329 command->mParam = data;
2330 command->mWaitStatus = true;
2331 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2332 return sendCommand(command, delayMs);
2333}
2334
Jean-Michel Trivide801052015-04-14 19:10:14 -07002335void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002336 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002337{
2338 sp<AudioCommand> command = new AudioCommand();
2339 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2340 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2341 data->mRegId = regId;
2342 data->mState = state;
2343 command->mParam = data;
2344 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002345 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002346 sendCommand(command);
2347}
2348
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002349void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002350 int event,
2351 const record_client_info_t *clientInfo,
2352 const audio_config_base_t *clientConfig,
2353 std::vector<effect_descriptor_t> clientEffects,
2354 const audio_config_base_t *deviceConfig,
2355 std::vector<effect_descriptor_t> effects,
2356 audio_patch_handle_t patchHandle,
2357 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002358{
2359 sp<AudioCommand>command = new AudioCommand();
2360 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2361 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2362 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002363 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002364 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002365 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002366 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002367 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002368 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002369 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002370 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002371 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2372 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002373 sendCommand(command);
2374}
2375
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002376void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2377{
2378 sp<AudioCommand> command = new AudioCommand();
2379 command->mCommand = AUDIO_MODULES_UPDATE;
2380 sendCommand(command);
2381}
2382
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002383void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2384{
2385 sp<AudioCommand>command = new AudioCommand();
2386 command->mCommand = ROUTING_UPDATED;
2387 ALOGV("AudioCommandThread() adding routing update");
2388 sendCommand(command);
2389}
2390
Eric Laurent81dd0f52021-07-05 11:54:40 +02002391void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2392{
2393 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002394 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002395 ALOGV("AudioCommandThread() adding check spatializer");
2396 sendCommand(command);
2397}
2398
Eric Laurent15903592022-02-24 20:44:36 +01002399void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2400{
2401 sp<AudioCommand>command = new AudioCommand();
2402 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2403 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2404 sendCommand(command);
2405}
2406
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002407void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2408{
2409 sp<AudioCommand>command = new AudioCommand();
2410 command->mCommand = VOL_RANGE_INIT_REQUEST;
2411 ALOGV("AudioCommandThread() adding volume range init request");
2412 sendCommand(command);
2413}
2414
Eric Laurent0ede8922014-05-09 18:04:42 -07002415status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2416{
2417 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002418 audio_utils::lock_guard _l(mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002419 insertCommand_l(command, delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002420 mWaitWorkCV.notify_one();
Eric Laurent0ede8922014-05-09 18:04:42 -07002421 }
Andy Hung79eacdb2023-11-30 19:34:24 -08002422 audio_utils::unique_lock ul(command->mMutex);
Eric Laurent0ede8922014-05-09 18:04:42 -07002423 while (command->mWaitStatus) {
2424 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
Andy Hung79eacdb2023-11-30 19:34:24 -08002425 if (command->mCond.wait_for(
Andy Hung02ea2a02024-01-25 17:02:30 -08002426 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002427 command->mStatus = TIMED_OUT;
2428 command->mWaitStatus = false;
2429 }
2430 }
2431 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002432}
2433
Andy Hung79eacdb2023-11-30 19:34:24 -08002434// insertCommand_l() must be called with mMutex held
Eric Laurent0ede8922014-05-09 18:04:42 -07002435void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002437 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002438 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 command->mTime = systemTime() + milliseconds(delayMs);
2440
2441 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002442 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002443 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 }
2445
2446 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002447 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002448 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2450 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002451
2452 // create audio patch or release audio patch commands are equivalent
2453 // with regard to filtering
2454 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2455 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2456 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2457 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2458 continue;
2459 }
2460 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461
2462 switch (command->mCommand) {
2463 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002464 ParametersData *data = (ParametersData *)command->mParam.get();
2465 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002467 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002468 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2470 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2471 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002472 String8 key;
2473 String8 value;
2474 param.getAt(j, key, value);
2475 for (size_t k = 0; k < param2.size(); k++) {
2476 String8 key2;
2477 String8 value2;
2478 param2.getAt(k, key2, value2);
2479 if (key2 == key) {
2480 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002481 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002482 break;
2483 }
2484 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 }
2486 // if all keys have been filtered out, remove the command.
2487 // otherwise, update the key value pairs
2488 if (param2.size() == 0) {
2489 removedCommands.add(command2);
2490 } else {
2491 data2->mKeyValuePairs = param2.toString();
2492 }
Eric Laurent21e54562013-09-23 12:08:05 -07002493 command->mTime = command2->mTime;
2494 // force delayMs to non 0 so that code below does not request to wait for
2495 // command status as the command is now delayed
2496 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497 } break;
2498
2499 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002500 VolumeData *data = (VolumeData *)command->mParam.get();
2501 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 if (data->mIO != data2->mIO) break;
2503 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002504 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002505 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002507 command->mTime = command2->mTime;
2508 // force delayMs to non 0 so that code below does not request to wait for
2509 // command status as the command is now delayed
2510 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002512
Andy Hung6b137d12024-08-27 22:35:17 +00002513 case SET_PORTS_VOLUME: {
2514 VolumePortsData *data = (VolumePortsData *)command->mParam.get();
2515 VolumePortsData *data2 = (VolumePortsData *)command2->mParam.get();
2516 if (data->mIO != data2->mIO) break;
2517 // Can remove command only if port ids list is the same, otherwise, remove from
2518 // command 2 all port whose volume will be replaced with command 1 volume.
2519 std::vector<audio_port_handle_t> portsOnlyInCommand2{};
2520 std::copy_if(data2->mPorts.begin(), data2->mPorts.end(),
2521 std::back_inserter(portsOnlyInCommand2), [&](const auto &portId) {
2522 return std::find(data->mPorts.begin(), data->mPorts.end(), portId) ==
2523 data->mPorts.end();
2524 });
2525 if (!portsOnlyInCommand2.empty()) {
2526 data2->mPorts = portsOnlyInCommand2;
2527 break;
2528 }
2529 ALOGV("Filtering out volume command on output %d for ports %s",
2530 data->mIO, data->dumpPorts().c_str());
2531 removedCommands.add(command2);
2532 command->mTime = command2->mTime;
2533 // force delayMs to non 0 so that code below does not request to wait for
2534 // command status as the command is now delayed
2535 delayMs = 1;
2536 } break;
2537
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002538 case SET_VOICE_VOLUME: {
2539 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2540 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2541 ALOGV("Filtering out voice volume command value %f replaced by %f",
2542 data2->mVolume, data->mVolume);
2543 removedCommands.add(command2);
2544 command->mTime = command2->mTime;
2545 // force delayMs to non 0 so that code below does not request to wait for
2546 // command status as the command is now delayed
2547 delayMs = 1;
2548 } break;
2549
Eric Laurente45b48a2014-09-04 16:40:57 -07002550 case CREATE_AUDIO_PATCH:
2551 case RELEASE_AUDIO_PATCH: {
2552 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002553 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002554 if (command->mCommand == CREATE_AUDIO_PATCH) {
2555 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002556 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002557 } else {
2558 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002559 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002560 }
2561 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002562 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002563 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2564 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002565 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002566 } else {
2567 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002568 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002569 }
2570 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002571 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2572 same output. */
2573 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2574 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2575 bool isOutputDiff = false;
2576 if (patch.num_sources == patch2.num_sources) {
2577 for (unsigned count = 0; count < patch.num_sources; count++) {
2578 if (patch.sources[count].id != patch2.sources[count].id) {
2579 isOutputDiff = true;
2580 break;
2581 }
2582 }
2583 if (isOutputDiff)
2584 break;
2585 }
2586 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002587 ALOGV("Filtering out %s audio patch command for handle %d",
2588 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2589 removedCommands.add(command2);
2590 command->mTime = command2->mTime;
2591 // force delayMs to non 0 so that code below does not request to wait for
2592 // command status as the command is now delayed
2593 delayMs = 1;
2594 } break;
2595
Jean-Michel Trivide801052015-04-14 19:10:14 -07002596 case DYN_POLICY_MIX_STATE_UPDATE: {
2597
2598 } break;
2599
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002600 case RECORDING_CONFIGURATION_UPDATE: {
2601
2602 } break;
2603
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002604 case ROUTING_UPDATED: {
2605
2606 } break;
2607
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002608 case VOL_RANGE_INIT_REQUEST: {
2609 // command may come from different requests, do not filter
2610 } break;
2611
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612 default:
2613 break;
2614 }
2615 }
2616
2617 // remove filtered commands
2618 for (size_t j = 0; j < removedCommands.size(); j++) {
2619 // removed commands always have time stamps greater than current command
2620 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002621 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002622 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 mAudioCommands.removeAt(k);
2624 break;
2625 }
2626 }
2627 }
2628 removedCommands.clear();
2629
Eric Laurentaa79bef2015-01-15 14:33:51 -08002630 // Disable wait for status if delay is not 0.
2631 // Except for create audio patch command because the returned patch handle
Dariusz Budnerf8a27c32024-07-10 18:13:15 +02002632 // is needed by audio policy manager. Audio patch created after timeout
2633 // (see TIMED_OUT) will be released from threadLoop().
Eric Laurentaa79bef2015-01-15 14:33:51 -08002634 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002635 command->mWaitStatus = false;
2636 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002637
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002639 ALOGV("inserting command: %d at index %zd, num commands %zu",
2640 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 mAudioCommands.insertAt(command, i + 1);
2642}
2643
2644void AudioPolicyService::AudioCommandThread::exit()
2645{
Steve Block3856b092011-10-20 11:56:00 +01002646 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 {
Andy Hung79eacdb2023-11-30 19:34:24 -08002648 audio_utils::lock_guard _l(mMutex);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 requestExit();
Andy Hung79eacdb2023-11-30 19:34:24 -08002650 mWaitWorkCV.notify_one();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 }
Zach Janga754b4f2015-10-27 01:29:34 +00002652 // Note that we can call it from the thread loop if all other references have been released
2653 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 requestExitAndWait();
2655}
2656
2657void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2658{
2659 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2660 mCommand,
2661 (int)ns2s(mTime),
2662 (int)ns2ms(mTime)%1000,
2663 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002664 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665}
2666
Dima Zavinfce7a472011-04-19 22:30:36 -07002667/******* helpers for the service_ops callbacks defined below *********/
2668void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2669 const char *keyValuePairs,
2670 int delayMs)
2671{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002672 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002673 delayMs);
2674}
2675
2676int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2677 float volume,
2678 audio_io_handle_t output,
2679 int delayMs)
2680{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002681 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002682 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002683}
2684
Andy Hung6b137d12024-08-27 22:35:17 +00002685int AudioPolicyService::setPortsVolume(const std::vector<audio_port_handle_t> &ports, float volume,
2686 audio_io_handle_t output, int delayMs)
2687{
2688 return (int)mAudioCommandThread->volumePortsCommand(ports, volume, output, delayMs);
2689}
2690
Dima Zavinfce7a472011-04-19 22:30:36 -07002691int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2692{
2693 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2694}
2695
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002696void AudioPolicyService::setEffectSuspended(int effectId,
2697 audio_session_t sessionId,
2698 bool suspended)
2699{
2700 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2701}
2702
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002703Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002704{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002705 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002706 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002707}
2708
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002709
Dima Zavinfce7a472011-04-19 22:30:36 -07002710extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002711audio_module_handle_t aps_load_hw_module(void *service __unused,
2712 const char *name);
2713audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002714 audio_devices_t *pDevices,
2715 uint32_t *pSamplingRate,
2716 audio_format_t *pFormat,
2717 audio_channel_mask_t *pChannelMask,
2718 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002719 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002720
Eric Laurent2d388ec2014-03-07 13:25:54 -08002721audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002722 audio_module_handle_t module,
2723 audio_devices_t *pDevices,
2724 uint32_t *pSamplingRate,
2725 audio_format_t *pFormat,
2726 audio_channel_mask_t *pChannelMask,
2727 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002728 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002729 const audio_offload_info_t *offloadInfo);
2730audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002731 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002732 audio_io_handle_t output2);
2733int aps_close_output(void *service __unused, audio_io_handle_t output);
2734int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2735int aps_restore_output(void *service __unused, audio_io_handle_t output);
2736audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002737 audio_devices_t *pDevices,
2738 uint32_t *pSamplingRate,
2739 audio_format_t *pFormat,
2740 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002741 audio_in_acoustics_t acoustics __unused);
2742audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002743 audio_module_handle_t module,
2744 audio_devices_t *pDevices,
2745 uint32_t *pSamplingRate,
2746 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002747 audio_channel_mask_t *pChannelMask);
2748int aps_close_input(void *service __unused, audio_io_handle_t input);
2749int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002750int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002751 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002752 audio_io_handle_t dst_output);
2753char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2754 const char *keys);
2755void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2756 const char *kv_pairs, int delay_ms);
2757int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002758 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002759 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002760int aps_set_voice_volume(void *service, float volume, int delay_ms);
2761};
Dima Zavinfce7a472011-04-19 22:30:36 -07002762
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002763} // namespace android