blob: f2dd2bfa625e8d9fa2099873fe9a023c5408563d [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioPolicyService"
18//#define LOG_NDEBUG 0
19
Glenn Kasten153b9fe2013-07-15 11:23:36 -070020#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070021#undef __STRICT_ANSI__
22#define __STDINT_LIMITS
23#define __STDC_LIMIT_MACROS
24#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053026#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070027
28#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <binder/IServiceManager.h>
30#include <utils/Log.h>
31#include <cutils/properties.h>
32#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080033#include <binder/PermissionController.h>
34#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
37#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080039#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070040#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080041#include <media/AudioParameter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070042#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080043#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080044#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <system/audio_policy.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;
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Glenn Kasten8dad0e32012-01-09 08:41:22 -080053static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
54static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053055static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mikhail Naganov959e2d02019-03-28 11:08:19 -070057static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Eric Laurent0ede8922014-05-09 18:04:42 -070059static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010060
Svet Ganovf4ddfef2018-01-16 07:37:58 -080061static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
64
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053065static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
66{
67 AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
68 status_t status = apm->initialize();
69 if (status != NO_ERROR) {
70 delete apm;
71 apm = nullptr;
72 }
73 return apm;
74}
75
76static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
77{
78 delete interface;
79}
80// ----------------------------------------------------------------------------
81
Mathias Agopian65ab4712010-07-14 17:59:35 -070082AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070083 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070084 mAudioPolicyManager(NULL),
85 mAudioPolicyClient(NULL),
86 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053087 mCaptureStateNotifier(false),
88 mCreateAudioPolicyManager(createAudioPolicyManager),
89 mDestroyAudioPolicyManager(destroyAudioPolicyManager) {
90}
91
92void AudioPolicyService::loadAudioPolicyManager()
93{
94 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
95 if (mLibraryHandle != nullptr) {
96 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
97 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
98 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
99 const char *lastError = dlerror();
100 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
101 __func__, lastError != nullptr ? lastError : "no error");
102
103 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
104 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
105 lastError = dlerror();
106 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
107 __func__, lastError != nullptr ? lastError : "no error");
108 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
109 unloadAudioPolicyManager();
110 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
111 }
112 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700113}
114
115void AudioPolicyService::onFirstRef()
116{
Andy Hungd47aca22022-03-15 11:50:51 -0700117 // Log an AudioPolicy "constructor" mediametrics event on first ref.
118 // This records the time it takes to load the audio modules and devices.
119 mediametrics::Defer defer([beginNs = systemTime()] {
120 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
121 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
122 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
123 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700124 {
125 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800126
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700127 // start audio commands thread
128 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
129 // start output activity command thread
130 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700131
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700132 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530133
134 loadAudioPolicyManager();
135 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700136 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200137
bryant_liuba2b4392014-06-11 16:49:30 +0800138 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000139 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
140 sp<UidPolicy> uidPolicy = new UidPolicy(this);
141 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700142 {
143 Mutex::Autolock _l(mLock);
144 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000145 mUidPolicy = uidPolicy;
146 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700147 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000148 uidPolicy->registerSelf();
149 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200150
Eric Laurent81dd0f52021-07-05 11:54:40 +0200151 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200152 if (mAudioPolicyManager != nullptr) {
153 Mutex::Autolock _l(mLock);
154 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
155 AudioDeviceTypeAddrVector devices;
156 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
157 if (hasSpatializer) {
158 mSpatializer = Spatializer::create(this);
159 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200160 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200161 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700162}
163
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530164void AudioPolicyService::unloadAudioPolicyManager()
165{
166 ALOGV("%s ", __func__);
167 if (mLibraryHandle != nullptr) {
168 dlclose(mLibraryHandle);
169 }
170 mLibraryHandle = nullptr;
171 mCreateAudioPolicyManager = nullptr;
172 mDestroyAudioPolicyManager = nullptr;
173}
174
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175AudioPolicyService::~AudioPolicyService()
176{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700178 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700179
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530180 mDestroyAudioPolicyManager(mAudioPolicyManager);
181 unloadAudioPolicyManager();
182
Eric Laurentdce54a12014-03-10 12:19:46 -0700183 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700184
185 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800186 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800187
188 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800189 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000190
191 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800192 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700193}
194
195// A notification client is always registered by AudioSystem when the client process
196// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800197Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700198{
Eric Laurent12590252015-08-21 18:40:20 -0700199 if (client == 0) {
200 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800201 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700202 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800203 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700204
205 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800206 pid_t pid = IPCThreadState::self()->getCallingPid();
207 int64_t token = ((int64_t)uid<<32) | pid;
208
209 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700210 sp<NotificationClient> notificationClient = new NotificationClient(this,
211 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800212 uid,
213 pid);
214 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700215
luochaojiang908c7d72018-06-21 14:58:04 +0800216 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700217
Marco Nelissenf8880202014-11-14 07:58:25 -0800218 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700219 binder->linkToDeath(notificationClient);
220 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800221 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700222}
223
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800224Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700225{
226 Mutex::Autolock _l(mNotificationClientsLock);
227
228 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800229 pid_t pid = IPCThreadState::self()->getCallingPid();
230 int64_t token = ((int64_t)uid<<32) | pid;
231
232 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800233 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700234 }
luochaojiang908c7d72018-06-21 14:58:04 +0800235 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800236 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700237}
238
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800239Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100240{
241 Mutex::Autolock _l(mNotificationClientsLock);
242
243 uid_t uid = IPCThreadState::self()->getCallingUid();
244 pid_t pid = IPCThreadState::self()->getCallingPid();
245 int64_t token = ((int64_t)uid<<32) | pid;
246
247 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800248 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100249 }
250 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800251 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100252}
253
Eric Laurentb52c1522014-05-20 11:27:36 -0700254// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800255void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700256{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000257 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800258 {
259 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800260 int64_t token = ((int64_t)uid<<32) | pid;
261 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800262 for (size_t i = 0; i < mNotificationClients.size(); i++) {
263 if (mNotificationClients.valueAt(i)->uid() == uid) {
264 hasSameUid = true;
265 break;
266 }
267 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000268 }
269 {
270 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800271 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700272 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700273 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700274 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800275 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700276}
277
278void AudioPolicyService::onAudioPortListUpdate()
279{
280 mOutputCommandThread->updateAudioPortListCommand();
281}
282
283void AudioPolicyService::doOnAudioPortListUpdate()
284{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800285 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700286 for (size_t i = 0; i < mNotificationClients.size(); i++) {
287 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
288 }
289}
290
291void AudioPolicyService::onAudioPatchListUpdate()
292{
293 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294}
295
Eric Laurentb52c1522014-05-20 11:27:36 -0700296void AudioPolicyService::doOnAudioPatchListUpdate()
297{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800298 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700299 for (size_t i = 0; i < mNotificationClients.size(); i++) {
300 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
301 }
302}
303
François Gaffiecfe17322018-11-07 13:41:29 +0100304void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
305{
306 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
307}
308
309void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
310{
311 Mutex::Autolock _l(mNotificationClientsLock);
312 for (size_t i = 0; i < mNotificationClients.size(); i++) {
313 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
314 }
315}
316
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700317void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700318{
319 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
320 regId.string(), state);
321 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
322}
323
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700324void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700325{
326 Mutex::Autolock _l(mNotificationClientsLock);
327 for (size_t i = 0; i < mNotificationClients.size(); i++) {
328 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
329 }
330}
331
Eric Laurenta9f86652018-11-28 17:23:11 -0800332void AudioPolicyService::onRecordingConfigurationUpdate(
333 int event,
334 const record_client_info_t *clientInfo,
335 const audio_config_base_t *clientConfig,
336 std::vector<effect_descriptor_t> clientEffects,
337 const audio_config_base_t *deviceConfig,
338 std::vector<effect_descriptor_t> effects,
339 audio_patch_handle_t patchHandle,
340 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800341{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800342 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800343 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800344}
345
Eric Laurenta9f86652018-11-28 17:23:11 -0800346void AudioPolicyService::doOnRecordingConfigurationUpdate(
347 int event,
348 const record_client_info_t *clientInfo,
349 const audio_config_base_t *clientConfig,
350 std::vector<effect_descriptor_t> clientEffects,
351 const audio_config_base_t *deviceConfig,
352 std::vector<effect_descriptor_t> effects,
353 audio_patch_handle_t patchHandle,
354 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800355{
356 Mutex::Autolock _l(mNotificationClientsLock);
357 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800358 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800359 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800360 }
361}
362
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700363void AudioPolicyService::onRoutingUpdated()
364{
365 mOutputCommandThread->routingChangedCommand();
366}
367
368void AudioPolicyService::doOnRoutingUpdated()
369{
370 Mutex::Autolock _l(mNotificationClientsLock);
371 for (size_t i = 0; i < mNotificationClients.size(); i++) {
372 mNotificationClients.valueAt(i)->onRoutingUpdated();
373 }
374}
375
Eric Laurent81dd0f52021-07-05 11:54:40 +0200376void AudioPolicyService::onCheckSpatializer()
377{
378 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200379 onCheckSpatializer_l();
380}
381
382void AudioPolicyService::onCheckSpatializer_l()
383{
384 if (mSpatializer != nullptr) {
385 mOutputCommandThread->checkSpatializerCommand();
386 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200387}
388
389void AudioPolicyService::doOnCheckSpatializer()
390{
Eric Laurent39095982021-08-24 18:29:27 +0200391 Mutex::Autolock _l(mLock);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200392
Eric Laurent39095982021-08-24 18:29:27 +0200393 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200394 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200395 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
396 audio_io_handle_t currentOutput = mSpatializer->getOutput();
397 audio_io_handle_t newOutput;
398 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
399 audio_config_base_t config = mSpatializer->getAudioInConfig();
400 status_t status =
401 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100402 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
403 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200404 if (status == NO_ERROR && currentOutput == newOutput) {
405 return;
406 }
Eric Laurent15903592022-02-24 20:44:36 +0100407 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Eric Laurent39095982021-08-24 18:29:27 +0200408 mLock.unlock();
409 // It is OK to call detachOutput() is none is already attached.
410 mSpatializer->detachOutput();
411 if (status != NO_ERROR || newOutput == AUDIO_IO_HANDLE_NONE) {
Eric Laurent81dd0f52021-07-05 11:54:40 +0200412 mLock.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200413 return;
414 }
Eric Laurent15903592022-02-24 20:44:36 +0100415 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200416 mLock.lock();
417 if (status != NO_ERROR) {
418 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
419 }
420 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
421 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
422 mLock.unlock();
423 audio_io_handle_t output = mSpatializer->detachOutput();
424 mLock.lock();
425 if (output != AUDIO_IO_HANDLE_NONE) {
426 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200427 }
428 }
429 }
430}
431
Eric Laurent15903592022-02-24 20:44:36 +0100432size_t AudioPolicyService::countActiveClientsOnOutput_l(audio_io_handle_t output) REQUIRES(mLock) {
433 size_t count = 0;
434 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
435 auto client = mAudioPlaybackClients.valueAt(i);
436 if (client->io == output && client->active) {
437 count++;
438 }
439 }
440 return count;
441}
442
443void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
444 if (mSpatializer == nullptr) {
445 return;
446 }
447 mOutputCommandThread->updateActiveSpatializerTracksCommand();
448}
449
450void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
451{
452 Mutex::Autolock _l(mLock);
453 if (mSpatializer == nullptr) {
454 return;
455 }
456 mSpatializer->updateActiveTracks(countActiveClientsOnOutput_l(mSpatializer->getOutput()));
457}
458
459
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800460status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
461 audio_patch_handle_t *handle,
462 int delayMs)
463{
464 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
465}
466
467status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
468 int delayMs)
469{
470 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
471}
472
Eric Laurente1715a42014-05-20 11:30:42 -0700473status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
474 int delayMs)
475{
476 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
477}
478
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800479AudioPolicyService::NotificationClient::NotificationClient(
480 const sp<AudioPolicyService>& service,
481 const sp<media::IAudioPolicyServiceClient>& client,
482 uid_t uid,
483 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800484 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100485 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700486{
487}
488
489AudioPolicyService::NotificationClient::~NotificationClient()
490{
491}
492
493void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
494{
495 sp<NotificationClient> keep(this);
496 sp<AudioPolicyService> service = mService.promote();
497 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800498 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700499 }
500}
501
502void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
503{
Eric Laurente8726fe2015-06-26 09:39:24 -0700504 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700505 mAudioPolicyServiceClient->onAudioPortListUpdate();
506 }
507}
508
509void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
510{
Eric Laurente8726fe2015-06-26 09:39:24 -0700511 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700512 mAudioPolicyServiceClient->onAudioPatchListUpdate();
513 }
514}
Eric Laurent57dae992011-07-24 13:36:09 -0700515
Pattydd807582021-11-04 21:01:03 +0800516void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100517 int flags)
518{
519 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
520 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
521 }
522}
523
524
Jean-Michel Trivide801052015-04-14 19:10:14 -0700525void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700526 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700527{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700528 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800529 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
530 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800531 }
532}
533
534void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800535 int event,
536 const record_client_info_t *clientInfo,
537 const audio_config_base_t *clientConfig,
538 std::vector<effect_descriptor_t> clientEffects,
539 const audio_config_base_t *deviceConfig,
540 std::vector<effect_descriptor_t> effects,
541 audio_patch_handle_t patchHandle,
542 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800543{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700544 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800545 status_t status = [&]() -> status_t {
546 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
547 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
548 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700549 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700550 legacy2aidl_audio_config_base_t_AudioConfigBase(
551 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800552 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
553 convertContainer<std::vector<media::EffectDescriptor>>(
554 clientEffects,
555 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700556 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700557 legacy2aidl_audio_config_base_t_AudioConfigBase(
558 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800559 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
560 convertContainer<std::vector<media::EffectDescriptor>>(
561 effects,
562 legacy2aidl_effect_descriptor_t_EffectDescriptor));
563 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
564 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700565 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
566 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800567 return aidl_utils::statusTFromBinderStatus(
568 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
569 clientInfoAidl,
570 clientConfigAidl,
571 clientEffectsAidl,
572 deviceConfigAidl,
573 effectsAidl,
574 patchHandleAidl,
575 sourceAidl));
576 }();
577 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700578 }
579}
580
Eric Laurente8726fe2015-06-26 09:39:24 -0700581void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
582{
583 mAudioPortCallbacksEnabled = enabled;
584}
585
François Gaffiecfe17322018-11-07 13:41:29 +0100586void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
587{
588 mAudioVolumeGroupCallbacksEnabled = enabled;
589}
Eric Laurente8726fe2015-06-26 09:39:24 -0700590
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700591void AudioPolicyService::NotificationClient::onRoutingUpdated()
592{
593 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
594 mAudioPolicyServiceClient->onRoutingUpdated();
595 }
596}
597
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700599 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700600 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601}
602
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000603static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000605 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
606}
607
608static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
609{
610 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611}
612
613status_t AudioPolicyService::dumpInternals(int fd)
614{
615 const size_t SIZE = 256;
616 char buffer[SIZE];
617 String8 result;
618
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000619 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800620 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000621 std::stringstream msg;
622 size_t i = 0;
623 for (auto usage : mSupportedSystemUsages) {
624 if (i++ != 0) msg << ", ";
625 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
626 msg << strUsage;
627 } else {
628 msg << usage << " (unknown)";
629 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800630 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000631 if (i == 0) {
632 msg << "None";
633 }
634 msg << std::endl;
635 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800636
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800638
639 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 return NO_ERROR;
641}
642
Eric Laurente8c8b432018-10-17 10:08:02 -0700643void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800644{
Eric Laurente8c8b432018-10-17 10:08:02 -0700645 Mutex::Autolock _l(mLock);
646 updateUidStates_l();
647}
648
649void AudioPolicyService::updateUidStates_l()
650{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800651// Go over all active clients and allow capture (does not force silence) in the
652// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800653// The client is in the active assistant list
654// AND is TOP
655// AND an accessibility service is TOP
656// AND source is either VOICE_RECOGNITION OR HOTWORD
657// OR there is no active privacy sensitive capture or call
658// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
659// AND source is VOICE_RECOGNITION OR HOTWORD
660// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800661// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700662// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800663// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800664// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800665// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
666// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800667// OR The client is an accessibility service
668// AND Is on TOP
669// AND the source is VOICE_RECOGNITION or HOTWORD
670// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700671// AND there is no active privacy sensitive capture or call
672// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800673// AND is on TOP
674// AND the source is VOICE_RECOGNITION or HOTWORD
675// OR the client source is virtual (remote submix, call audio TX or RX...)
676// OR the client source is HOTWORD
677// AND is on TOP
678// OR all active clients are using HOTWORD source
679// AND no call is active
680// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
681// OR the client is the current InputMethodService
682// AND a RTT call is active AND the source is VOICE_RECOGNITION
683// OR Any client
684// AND The assistant is not on TOP
685// AND is on TOP or latest started
686// AND there is no active privacy sensitive capture or call
687// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800688
Eric Laurent4e947da2019-10-17 15:24:06 -0700689
Eric Laurent4eb58f12018-12-07 16:41:02 -0800690 sp<AudioRecordClient> topActive;
691 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800692 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700693 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800694 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700695
Eric Laurenta46bedb2018-12-07 18:01:26 -0800696 nsecs_t topStartNs = 0;
697 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800698 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800699 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800700 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800701 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
702 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800703 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800704 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700705 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800706 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
707 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700708 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700709 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700710 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800711
Michael Groovercfd28302018-12-11 19:16:46 -0800712 // if Sensor Privacy is enabled then all recordings should be silenced.
713 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
714 silenceAllRecordings_l();
715 return;
716 }
717
Eric Laurente8c8b432018-10-17 10:08:02 -0700718 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
719 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000720 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
721 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800722 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700723 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800724 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700725
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700726 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700727 // clients which app is in IDLE state are not eligible for top active or
728 // latest active
729 if (appState == APP_STATE_IDLE) {
730 continue;
731 }
732
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700733 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700734 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800735 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700736 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700737 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800738 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800739 bool isPrivacySensitive =
740 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700741
Eric Laurentc21d5692020-02-25 10:24:36 -0800742 if (appState == APP_STATE_TOP) {
743 if (isPrivacySensitive) {
744 if (current->startTimeNs > topSensitiveStartNs) {
745 topSensitiveActive = current;
746 topSensitiveStartNs = current->startTimeNs;
747 }
748 } else {
749 if (current->startTimeNs > topStartNs) {
750 topActive = current;
751 topStartNs = current->startTimeNs;
752 }
753 }
754 if (isAssistant) {
755 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800756 if (isActiveAssistant) {
757 useActiveAssistantList = true;
758 } else if (!useActiveAssistantList) {
759 if (current->startTimeNs > latestAssistantStartNs) {
760 latestActiveAssistant = current;
761 latestAssistantStartNs = current->startTimeNs;
762 }
763 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800764 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800765 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800766 // Clients capturing for HOTWORD are not considered
767 // for latest active to avoid masking regular clients started before
768 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
769 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
770 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700771 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
772 // is marked latest sensitive active even if another app qualifies.
773 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700774 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700775 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700776 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000777 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700778 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700779 latestSensitiveActiveOrComm = current;
780 latestSensitiveStartNs = current->startTimeNs;
781 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800782 }
783 isSensitiveActive = true;
784 } else {
785 if (current->startTimeNs > latestStartNs) {
786 latestActive = current;
787 latestStartNs = current->startTimeNs;
788 }
789 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800790 }
791 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700792 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
793 onlyHotwordActive = false;
794 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100795 if (currentUid == mPhoneStateOwnerUid &&
796 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700797 isPhoneStateOwnerActive = true;
798 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800799 }
800
Eric Laurent1ff16a72019-03-14 18:35:04 -0700801 // if no active client with UI on Top, consider latest active as top
802 if (topActive == nullptr) {
803 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800804 topStartNs = latestStartNs;
805 }
806 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700807 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800808 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700809 } else if (latestSensitiveActiveOrComm != nullptr) {
810 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
811 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700812 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000813 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700814 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700815 topSensitiveActive = latestSensitiveActiveOrComm;
816 topSensitiveStartNs = latestSensitiveStartNs;
817 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800818 }
819
820 // If both privacy sensitive and regular capture are active:
821 // if the regular capture is privileged
822 // allow concurrency
823 // else
824 // favor the privacy sensitive case
825 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700826 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800827 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800828 }
829
830 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
831 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700832 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000833 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700834 if (!current->active) {
835 continue;
836 }
837
Eric Laurent4eb58f12018-12-07 16:41:02 -0800838 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700839 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000840 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700841 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000842 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800843 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
844 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800845
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000846 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700847 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000848 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700849 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700850 bool canCaptureCommunication = recordClient->canCaptureOutput
851 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700852 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700853 return !(isInCall && !canCaptureCall)
854 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800855 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700856
857 // By default allow capture if:
858 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700859 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700860 // AND there is no active privacy sensitive capture or call
861 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
862 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800863 && (isTopOrLatestActive || isTopOrLatestSensitive)
864 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700865 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800866 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800867
Eric Laurented726cc2021-07-01 14:26:41 +0200868 if (!current->hasOp()) {
869 // Never allow capture if app op is denied
870 allowCapture = false;
871 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700872 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
873 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800874 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700875 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800876 // Active assistant list is not being used
877 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700878 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800879 // OR there is no active privacy sensitive capture or call
880 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
881 // AND is latest TOP assistant AND
882 // uses VOICE_RECOGNITION OR uses HOTWORD
883 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -0700884 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800885 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700886 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800887 }
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800888 } else if (!(isSensitiveActive && !current->canCaptureOutput)
889 && canCaptureIfInCallOrCommunication(current)) {
890 if (isTopOrLatestAssistant
891 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
892 || source == AUDIO_SOURCE_HOTWORD)) {
893 allowCapture = true;
894 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
895 allowCapture = true;
896 }
897 }
898 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
899 // For assistant on active list and on top allow capture if:
900 // An accessibility service is on TOP
901 // AND the source is VOICE_RECOGNITION or HOTWORD
902 // OR there is no active privacy sensitive capture or call
903 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
904 // AND uses VOICE_RECOGNITION OR uses HOTWORD
905 if (isA11yOnTop) {
906 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
907 allowCapture = true;
908 }
909 } else if (!(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800910 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800911 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
912 {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700913 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800914 }
915 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700916 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700917 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700918 // The assistant is not on TOP
919 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700920 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700921 // OR
922 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
923 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700924 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800925 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700926 allowCapture = true;
927 }
Eric Laurent589171c2019-07-25 18:04:29 -0700928 if (isA11yOnTop) {
929 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
930 allowCapture = true;
931 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800932 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700933 } else if (source == AUDIO_SOURCE_HOTWORD) {
934 // For HOTWORD source allow capture when not on TOP if:
935 // All active clients are using HOTWORD source
936 // AND no call is active
937 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800938 if (onlyHotwordActive
939 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700940 allowCapture = true;
941 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700942 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700943 // For current InputMethodService allow capture if:
944 // A RTT call is active AND the source is VOICE_RECOGNITION
945 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
946 allowCapture = true;
947 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800948 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200949 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700950 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700951 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700952 }
953}
954
Michael Groovercfd28302018-12-11 19:16:46 -0800955void AudioPolicyService::silenceAllRecordings_l() {
956 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
957 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700958 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200959 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700960 }
Michael Groovercfd28302018-12-11 19:16:46 -0800961 }
962}
963
Eric Laurente8c8b432018-10-17 10:08:02 -0700964/* static */
965app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700966
967 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700968 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700969 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
970 // include persistent services
971 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700972 }
973 return APP_STATE_FOREGROUND;
974}
975
Eric Laurent4eb58f12018-12-07 16:41:02 -0800976/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800977bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800978{
979 switch (source) {
980 case AUDIO_SOURCE_VOICE_UPLINK:
981 case AUDIO_SOURCE_VOICE_DOWNLINK:
982 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800983 case AUDIO_SOURCE_REMOTE_SUBMIX:
984 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700985 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800986 return true;
987 default:
988 break;
989 }
990 return false;
991}
992
Eric Laurented726cc2021-07-01 14:26:41 +0200993/* static */
994bool AudioPolicyService::isAppOpSource(audio_source_t source)
995{
996 switch (source) {
997 case AUDIO_SOURCE_FM_TUNER:
998 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +0200999 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +02001000 return false;
1001 default:
1002 break;
1003 }
1004 return true;
1005}
1006
Eric Laurent8c7ef892021-06-10 13:32:16 +02001007void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001008{
1009 AutoCallerClear acc;
1010
1011 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001012 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001013 }
1014 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1015 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001016 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001017 if (client->silenced != silenced) {
1018 if (client->active) {
1019 if (silenced) {
1020 finishRecording(client->attributionSource, client->attributes.source);
1021 } else {
1022 std::stringstream msg;
1023 msg << "Audio recording un-silenced on session " << client->session;
1024 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1025 client->attributes.source)) {
1026 silenced = true;
1027 }
1028 }
1029 }
1030 af->setRecordSilenced(client->portId, silenced);
1031 client->silenced = silenced;
1032 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001033 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001034}
1035
Glenn Kasten0f11b512014-01-31 16:18:54 -08001036status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037{
Glenn Kasten44deb052012-02-05 18:09:08 -08001038 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039 dumpPermissionDenial(fd);
1040 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001041 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 if (!locked) {
1043 String8 result(kDeadlockedString);
1044 write(fd, result.string(), result.size());
1045 }
1046
1047 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001048
1049 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
1050 write(fd, actPtr.string(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001051 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052 mAudioCommandThread->dump(fd);
1053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001055 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
1056 write(fd, octPtr.string(), octPtr.size());
1057 if (mOutputCommandThread != 0) {
1058 mOutputCommandThread->dump(fd);
1059 }
1060
Eric Laurentdce54a12014-03-10 12:19:46 -07001061 if (mAudioPolicyManager) {
1062 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001063 } else {
1064 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
1065 write(fd, apmPtr.string(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001066 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067
Kevin Rocard8be94972019-02-22 13:26:25 -08001068 mPackageManager.dump(fd);
1069
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001070 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071 }
1072 return NO_ERROR;
1073}
1074
1075status_t AudioPolicyService::dumpPermissionDenial(int fd)
1076{
1077 const size_t SIZE = 256;
1078 char buffer[SIZE];
1079 String8 result;
1080 snprintf(buffer, SIZE, "Permission Denial: "
1081 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1082 IPCThreadState::self()->getCallingPid(),
1083 IPCThreadState::self()->getCallingUid());
1084 result.append(buffer);
1085 write(fd, result.string(), result.size());
1086 return NO_ERROR;
1087}
1088
1089status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001090 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001091 // make sure transactions reserved to AudioFlinger do not come from other processes
1092 switch (code) {
1093 case TRANSACTION_startOutput:
1094 case TRANSACTION_stopOutput:
1095 case TRANSACTION_releaseOutput:
1096 case TRANSACTION_getInputForAttr:
1097 case TRANSACTION_startInput:
1098 case TRANSACTION_stopInput:
1099 case TRANSACTION_releaseInput:
1100 case TRANSACTION_getOutputForEffect:
1101 case TRANSACTION_registerEffect:
1102 case TRANSACTION_unregisterEffect:
1103 case TRANSACTION_setEffectEnabled:
1104 case TRANSACTION_getStrategyForStream:
1105 case TRANSACTION_getOutputForAttr:
1106 case TRANSACTION_moveEffectsToIo:
1107 ALOGW("%s: transaction %d received from PID %d",
1108 __func__, code, IPCThreadState::self()->getCallingPid());
1109 return INVALID_OPERATION;
1110 default:
1111 break;
1112 }
1113
1114 // make sure the following transactions come from system components
1115 switch (code) {
1116 case TRANSACTION_setDeviceConnectionState:
1117 case TRANSACTION_handleDeviceConfigChange:
1118 case TRANSACTION_setPhoneState:
1119//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1120// case TRANSACTION_setForceUse:
1121 case TRANSACTION_initStreamVolume:
1122 case TRANSACTION_setStreamVolumeIndex:
1123 case TRANSACTION_setVolumeIndexForAttributes:
1124 case TRANSACTION_getStreamVolumeIndex:
1125 case TRANSACTION_getVolumeIndexForAttributes:
1126 case TRANSACTION_getMinVolumeIndexForAttributes:
1127 case TRANSACTION_getMaxVolumeIndexForAttributes:
1128 case TRANSACTION_isStreamActive:
1129 case TRANSACTION_isStreamActiveRemotely:
1130 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001131 case TRANSACTION_registerPolicyMixes:
1132 case TRANSACTION_setMasterMono:
1133 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001134 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001135 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001136 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001137 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001138 case TRANSACTION_setA11yServicesUids:
1139 case TRANSACTION_setUidDeviceAffinities:
1140 case TRANSACTION_removeUidDeviceAffinities:
1141 case TRANSACTION_setUserIdDeviceAffinities:
1142 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001143 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001144 case TRANSACTION_listAudioVolumeGroups:
1145 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1146 case TRANSACTION_acquireSoundTriggerSession:
1147 case TRANSACTION_releaseSoundTriggerSession:
1148 case TRANSACTION_setRttEnabled:
1149 case TRANSACTION_isCallScreenModeSupported:
1150 case TRANSACTION_setDevicesRoleForStrategy:
1151 case TRANSACTION_setSupportedSystemUsages:
1152 case TRANSACTION_removeDevicesRoleForStrategy:
1153 case TRANSACTION_getDevicesForRoleAndStrategy:
1154 case TRANSACTION_getDevicesForAttributes:
1155 case TRANSACTION_setAllowedCapturePolicy:
1156 case TRANSACTION_onNewAudioModulesAvailable:
1157 case TRANSACTION_setCurrentImeUid:
1158 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1159 case TRANSACTION_setDevicesRoleForCapturePreset:
1160 case TRANSACTION_addDevicesRoleForCapturePreset:
1161 case TRANSACTION_removeDevicesRoleForCapturePreset:
1162 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001163 case TRANSACTION_getDevicesForRoleAndCapturePreset:
1164 case TRANSACTION_getSpatializer: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001165 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1166 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1167 __func__, code, IPCThreadState::self()->getCallingPid(),
1168 IPCThreadState::self()->getCallingUid());
1169 return INVALID_OPERATION;
1170 }
1171 } break;
1172 default:
1173 break;
1174 }
1175
1176 std::string tag("IAudioPolicyService command " + std::to_string(code));
Andy Hung5c6d68a2022-03-09 21:54:59 -08001177 mediautils::TimeCheck check(tag.c_str());
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001178
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001179 switch (code) {
1180 case SHELL_COMMAND_TRANSACTION: {
1181 int in = data.readFileDescriptor();
1182 int out = data.readFileDescriptor();
1183 int err = data.readFileDescriptor();
1184 int argc = data.readInt32();
1185 Vector<String16> args;
1186 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1187 args.add(data.readString16());
1188 }
1189 sp<IBinder> unusedCallback;
1190 sp<IResultReceiver> resultReceiver;
1191 status_t status;
1192 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1193 return status;
1194 }
1195 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1196 return status;
1197 }
1198 status = shellCommand(in, out, err, args);
1199 if (resultReceiver != nullptr) {
1200 resultReceiver->send(status);
1201 }
1202 return NO_ERROR;
1203 }
1204 }
1205
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1207}
1208
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001209// ------------------- Shell command implementation -------------------
1210
1211// NOTE: This is a remote API - make sure all args are validated
1212status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1213 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1214 return PERMISSION_DENIED;
1215 }
1216 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1217 return BAD_VALUE;
1218 }
jovanakbe066e12019-09-02 11:54:39 -07001219 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001220 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001221 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001222 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001223 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001224 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001225 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1226 purgePermissionCache();
1227 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001228 } else if (args.size() == 1 && args[0] == String16("help")) {
1229 printHelp(out);
1230 return NO_ERROR;
1231 }
1232 printHelp(err);
1233 return BAD_VALUE;
1234}
1235
jovanakbe066e12019-09-02 11:54:39 -07001236static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1237 if (userId < 0) {
1238 ALOGE("Invalid user: %d", userId);
1239 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001240 return BAD_VALUE;
1241 }
jovanakbe066e12019-09-02 11:54:39 -07001242
1243 PermissionController pc;
1244 uid = pc.getPackageUid(packageName, 0);
1245 if (uid <= 0) {
1246 ALOGE("Unknown package: '%s'", String8(packageName).string());
1247 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1248 return BAD_VALUE;
1249 }
1250
1251 uid = multiuser_get_uid(userId, uid);
1252 return NO_ERROR;
1253}
1254
1255status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1256 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1257 if (!(args.size() == 3 || args.size() == 5)) {
1258 printHelp(err);
1259 return BAD_VALUE;
1260 }
1261
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001262 bool active = false;
1263 if (args[2] == String16("active")) {
1264 active = true;
1265 } else if ((args[2] != String16("idle"))) {
1266 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1267 return BAD_VALUE;
1268 }
jovanakbe066e12019-09-02 11:54:39 -07001269
1270 int userId = 0;
1271 if (args.size() >= 5 && args[3] == String16("--user")) {
1272 userId = atoi(String8(args[4]));
1273 }
1274
1275 uid_t uid;
1276 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1277 return BAD_VALUE;
1278 }
1279
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001280 sp<UidPolicy> uidPolicy;
1281 {
1282 Mutex::Autolock _l(mLock);
1283 uidPolicy = mUidPolicy;
1284 }
1285 if (uidPolicy) {
1286 uidPolicy->addOverrideUid(uid, active);
1287 return NO_ERROR;
1288 }
1289 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001290}
1291
1292status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001293 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1294 if (!(args.size() == 2 || args.size() == 4)) {
1295 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001296 return BAD_VALUE;
1297 }
jovanakbe066e12019-09-02 11:54:39 -07001298
1299 int userId = 0;
1300 if (args.size() >= 4 && args[2] == String16("--user")) {
1301 userId = atoi(String8(args[3]));
1302 }
1303
1304 uid_t uid;
1305 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1306 return BAD_VALUE;
1307 }
1308
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001309 sp<UidPolicy> uidPolicy;
1310 {
1311 Mutex::Autolock _l(mLock);
1312 uidPolicy = mUidPolicy;
1313 }
1314 if (uidPolicy) {
1315 uidPolicy->removeOverrideUid(uid);
1316 return NO_ERROR;
1317 }
1318 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001319}
1320
1321status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001322 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1323 if (!(args.size() == 2 || args.size() == 4)) {
1324 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001325 return BAD_VALUE;
1326 }
jovanakbe066e12019-09-02 11:54:39 -07001327
1328 int userId = 0;
1329 if (args.size() >= 4 && args[2] == String16("--user")) {
1330 userId = atoi(String8(args[3]));
1331 }
1332
1333 uid_t uid;
1334 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1335 return BAD_VALUE;
1336 }
1337
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001338 sp<UidPolicy> uidPolicy;
1339 {
1340 Mutex::Autolock _l(mLock);
1341 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001342 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001343 if (uidPolicy) {
1344 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1345 }
1346 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001347}
1348
1349status_t AudioPolicyService::printHelp(int out) {
1350 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001351 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1352 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1353 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001354 " help print this message\n");
1355}
1356
1357// ----------- AudioPolicyService::UidPolicy implementation ----------
1358
1359void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001360 status_t res = mAm.linkToDeath(this);
1361 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001362 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001363 | ActivityManager::UID_OBSERVER_ACTIVE
1364 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001365 ActivityManager::PROCESS_STATE_UNKNOWN,
1366 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001367 if (!res) {
1368 Mutex::Autolock _l(mLock);
1369 mObserverRegistered = true;
1370 } else {
1371 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001372
Steven Moreland2f348142019-07-02 15:59:07 -07001373 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001374 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001375}
1376
1377void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001378 mAm.unlinkToDeath(this);
1379 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001380 Mutex::Autolock _l(mLock);
1381 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001382}
1383
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001384void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1385 Mutex::Autolock _l(mLock);
1386 mCachedUids.clear();
1387 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001388}
1389
Eric Laurente8c8b432018-10-17 10:08:02 -07001390void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001391 bool needToReregister = false;
1392 {
1393 Mutex::Autolock _l(mLock);
1394 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001395 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001396 if (needToReregister) {
1397 // Looks like ActivityManager has died previously, attempt to re-register.
1398 registerSelf();
1399 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001400}
1401
1402bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1403 if (isServiceUid(uid)) return true;
1404 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001405 {
1406 Mutex::Autolock _l(mLock);
1407 auto overrideIter = mOverrideUids.find(uid);
1408 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001409 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001410 }
1411 // In an absense of the ActivityManager, assume everything to be active.
1412 if (!mObserverRegistered) return true;
1413 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001414 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001415 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001416 }
1417 }
1418 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001419 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001420 {
1421 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001422 mCachedUids.insert(std::pair<uid_t,
1423 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1424 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001425 }
1426 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001427}
1428
Eric Laurente8c8b432018-10-17 10:08:02 -07001429int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1430 if (isServiceUid(uid)) {
1431 return ActivityManager::PROCESS_STATE_TOP;
1432 }
1433 checkRegistered();
1434 {
1435 Mutex::Autolock _l(mLock);
1436 auto overrideIter = mOverrideUids.find(uid);
1437 if (overrideIter != mOverrideUids.end()) {
1438 if (overrideIter->second.first) {
1439 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1440 return overrideIter->second.second;
1441 } else {
1442 auto cacheIter = mCachedUids.find(uid);
1443 if (cacheIter != mCachedUids.end()) {
1444 return cacheIter->second.second;
1445 }
1446 }
1447 }
1448 return ActivityManager::PROCESS_STATE_UNKNOWN;
1449 }
1450 // In an absense of the ActivityManager, assume everything to be active.
1451 if (!mObserverRegistered) {
1452 return ActivityManager::PROCESS_STATE_TOP;
1453 }
1454 auto cacheIter = mCachedUids.find(uid);
1455 if (cacheIter != mCachedUids.end()) {
1456 if (cacheIter->second.first) {
1457 return cacheIter->second.second;
1458 } else {
1459 return ActivityManager::PROCESS_STATE_UNKNOWN;
1460 }
1461 }
1462 }
1463 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001464 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001465 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1466 if (active) {
1467 state = am.getUidProcessState(uid, String16("audioserver"));
1468 }
1469 {
1470 Mutex::Autolock _l(mLock);
1471 mCachedUids.insert(std::pair<uid_t,
1472 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1473 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001474
Eric Laurente8c8b432018-10-17 10:08:02 -07001475 return state;
1476}
1477
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001478void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001479 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001480}
1481
1482void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001483 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001484}
1485
1486void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001487 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001488}
1489
Eric Laurente8c8b432018-10-17 10:08:02 -07001490void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1491 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001492 int64_t procStateSeq __unused,
1493 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001494 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1495 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001496 }
1497}
1498
1499void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001500 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1501}
1502
1503void AudioPolicyService::UidPolicy::notifyService() {
1504 sp<AudioPolicyService> service = mService.promote();
1505 if (service != nullptr) {
1506 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001507 }
1508}
1509
Eric Laurente8c8b432018-10-17 10:08:02 -07001510void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1511 std::pair<bool, int>> *uids,
1512 uid_t uid,
1513 bool active,
1514 int state,
1515 bool insert) {
1516 if (isServiceUid(uid)) {
1517 return;
1518 }
1519 bool wasActive = isUidActive(uid);
1520 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001521 {
1522 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001523 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001524 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001525 if (wasActive != isUidActive(uid) || state != previousState) {
1526 notifyService();
1527 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001528}
1529
Eric Laurente8c8b432018-10-17 10:08:02 -07001530void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1531 std::pair<bool, int>> *uids,
1532 uid_t uid,
1533 bool active,
1534 int state,
1535 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001536 auto it = uids->find(uid);
1537 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001538 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001539 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1540 it->second.first = active;
1541 }
1542 if (it->second.first) {
1543 it->second.second = state;
1544 } else {
1545 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1546 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001547 } else {
1548 uids->erase(it);
1549 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001550 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1551 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1552 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001553 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001554}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555
Eric Laurent4eb58f12018-12-07 16:41:02 -08001556bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1557 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001558 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001559 continue;
1560 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001561 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1562 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001563 return true;
1564 }
1565 }
1566 return false;
1567}
1568
Eric Laurentb78763e2018-10-17 10:08:02 -07001569bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1570{
1571 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1572 return it != mA11yUids.end();
1573}
1574
Oscar Azucena829d90d2022-01-28 17:17:56 -08001575void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1576 mAssistantUids.clear();
1577 mAssistantUids = uids;
1578}
1579
1580bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1581{
1582 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1583 return it != mAssistantUids.end();
1584}
1585
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001586void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1587 mActiveAssistantUids = activeUids;
1588}
1589
1590bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1591{
1592 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1593 mActiveAssistantUids.end(), uid);
1594 return it != mActiveAssistantUids.end();
1595}
1596
Oscar Azucena829d90d2022-01-28 17:17:56 -08001597void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1598 const size_t SIZE = 256;
1599 char buffer[SIZE];
1600 String8 result;
1601 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1602 snprintf(buffer, SIZE, "\t%s: \n", title);
1603 result.append(buffer);
1604 int counter = 0;
1605 if (uids.empty()) {
1606 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1607 result.append(buffer);
1608 return;
1609 }
1610 for (const auto &uid : uids) {
1611 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1612 result.append(buffer);
1613 }
1614 };
1615
1616 snprintf(buffer, SIZE, "UID Policy:\n");
1617 result.append(buffer);
1618 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1619 result.append(buffer);
1620
1621 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001622 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001623
1624 appendUidsToResult("Accessibility UIDs", mA11yUids);
1625
1626 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1627 result.append(buffer);
1628
1629 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1630 result.append(buffer);
1631
1632 write(fd, result.string(), result.size());
1633}
1634
Michael Groovercfd28302018-12-11 19:16:46 -08001635// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1636void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1637 SensorPrivacyManager spm;
1638 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1639 spm.addSensorPrivacyListener(this);
1640}
1641
1642void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1643 SensorPrivacyManager spm;
1644 spm.removeSensorPrivacyListener(this);
1645}
1646
1647bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1648 return mSensorPrivacyEnabled;
1649}
1650
Evan Seversond8dc6832022-01-27 10:47:03 -08001651binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1652 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001653 mSensorPrivacyEnabled = enabled;
1654 sp<AudioPolicyService> service = mService.promote();
1655 if (service != nullptr) {
1656 service->updateUidStates();
1657 }
1658 return binder::Status::ok();
1659}
1660
Eric Laurented726cc2021-07-01 14:26:41 +02001661// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1662
1663// static
1664sp<AudioPolicyService::OpRecordAudioMonitor>
1665AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1666 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1667 wp<AudioCommandThread> commandThread)
1668{
Eric Laurent987ce102021-07-05 12:11:51 +02001669 if (isAudioServerOrRootUid(attributionSource.uid)) {
1670 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001671 attributionSource.toString().c_str());
1672 return nullptr;
1673 }
1674
1675 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1676 ALOGD("not monitoring app op for uid %d and source %d",
1677 attributionSource.uid, attr.source);
1678 return nullptr;
1679 }
1680
1681 if (!attributionSource.packageName.has_value()
1682 || attributionSource.packageName.value().size() == 0) {
1683 return nullptr;
1684 }
1685 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1686}
1687
1688AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1689 const AttributionSourceState& attributionSource, int32_t appOp,
1690 wp<AudioCommandThread> commandThread) :
1691 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1692 mCommandThread(commandThread)
1693{
1694}
1695
1696AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1697{
1698 if (mOpCallback != 0) {
1699 mAppOpsManager.stopWatchingMode(mOpCallback);
1700 }
1701 mOpCallback.clear();
1702}
1703
1704void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1705{
1706 checkOp();
1707 mOpCallback = new RecordAudioOpCallback(this);
1708 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1709 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1710 // since it controls the mic permission for legacy apps.
1711 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1712 mAttributionSource.packageName.value_or(""))),
1713 mOpCallback);
1714}
1715
1716bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1717 return mHasOp.load();
1718}
1719
1720// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1721// is updated in AppOp callback and in onFirstRef()
1722// Note this method is never called (and never to be) for audio server / root track
1723// due to the UID in createIfNeeded(). As a result for those record track, it's:
1724// - not called from constructor,
1725// - not called from RecordAudioOpCallback because the callback is not installed in this case
1726void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1727{
1728 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1729 // since it controls the mic permission for legacy apps.
1730 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1731 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1732 mAttributionSource.packageName.value_or(""))));
1733 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1734 // verbose logging only log when appOp changed
1735 ALOGI_IF(hasIt != mHasOp.load(),
1736 "App op %d missing, %ssilencing record %s",
1737 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1738 mHasOp.store(hasIt);
1739
1740 if (updateUidStates) {
1741 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1742 if (commandThread != nullptr) {
1743 commandThread->updateUidStatesCommand();
1744 }
1745 }
1746}
1747
1748AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1749 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1750{ }
1751
1752void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1753 const String16& packageName __unused) {
1754 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1755 if (monitor != NULL) {
1756 if (op != monitor->getOp()) {
1757 return;
1758 }
1759 monitor->checkOp(true);
1760 }
1761}
1762
1763
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1765
Eric Laurentbfb1b832013-01-07 09:53:42 -08001766AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1767 const wp<AudioPolicyService>& service)
1768 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770}
1771
1772
1773AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1774{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001775 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 release_wake_lock(mName.string());
1777 }
1778 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779}
1780
1781void AudioPolicyService::AudioCommandThread::onFirstRef()
1782{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001783 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784}
1785
1786bool AudioPolicyService::AudioCommandThread::threadLoop()
1787{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001788 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789
1790 mLock.lock();
1791 while (!exitPending())
1792 {
Eric Laurent59a89232014-06-08 14:14:17 -07001793 sp<AudioPolicyService> svc;
1794 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 nsecs_t curTime = systemTime();
1796 // commands are sorted by increasing time stamp: execute them from index 0 and up
1797 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001798 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001800 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801
1802 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001804 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001805 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001806 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001807 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001808 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1809 data->mVolume,
1810 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001811 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812 }break;
1813 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001814 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001815 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1816 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001817 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001818 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001819 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001820 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001822 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001823 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001824 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001825 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001827 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001829 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001830 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001831 ALOGV("AudioCommandThread() processing stop output portId %d",
1832 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001833 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001834 if (svc == 0) {
1835 break;
1836 }
1837 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001838 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001839 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001840 }break;
1841 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001842 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001843 ALOGV("AudioCommandThread() processing release output portId %d",
1844 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001845 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001846 if (svc == 0) {
1847 break;
1848 }
1849 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001850 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001851 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001852 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001853 case CREATE_AUDIO_PATCH: {
1854 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1855 ALOGV("AudioCommandThread() processing create audio patch");
1856 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1857 if (af == 0) {
1858 command->mStatus = PERMISSION_DENIED;
1859 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001860 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001861 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001862 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001863 }
1864 } break;
1865 case RELEASE_AUDIO_PATCH: {
1866 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1867 ALOGV("AudioCommandThread() processing release audio patch");
1868 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1869 if (af == 0) {
1870 command->mStatus = PERMISSION_DENIED;
1871 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001872 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001873 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001874 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001875 }
1876 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001877 case UPDATE_AUDIOPORT_LIST: {
1878 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001879 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001880 if (svc == 0) {
1881 break;
1882 }
1883 mLock.unlock();
1884 svc->doOnAudioPortListUpdate();
1885 mLock.lock();
1886 }break;
1887 case UPDATE_AUDIOPATCH_LIST: {
1888 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001889 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001890 if (svc == 0) {
1891 break;
1892 }
1893 mLock.unlock();
1894 svc->doOnAudioPatchListUpdate();
1895 mLock.lock();
1896 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001897 case CHANGED_AUDIOVOLUMEGROUP: {
1898 AudioVolumeGroupData *data =
1899 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1900 ALOGV("AudioCommandThread() processing update audio volume group");
1901 svc = mService.promote();
1902 if (svc == 0) {
1903 break;
1904 }
1905 mLock.unlock();
1906 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1907 mLock.lock();
1908 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001909 case SET_AUDIOPORT_CONFIG: {
1910 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1911 ALOGV("AudioCommandThread() processing set port config");
1912 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1913 if (af == 0) {
1914 command->mStatus = PERMISSION_DENIED;
1915 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001916 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001917 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001918 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001919 }
1920 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001921 case DYN_POLICY_MIX_STATE_UPDATE: {
1922 DynPolicyMixStateUpdateData *data =
1923 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001924 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1925 data->mRegId.string(), data->mState);
1926 svc = mService.promote();
1927 if (svc == 0) {
1928 break;
1929 }
1930 mLock.unlock();
1931 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1932 mLock.lock();
1933 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001934 case RECORDING_CONFIGURATION_UPDATE: {
1935 RecordingConfigurationUpdateData *data =
1936 (RecordingConfigurationUpdateData *)command->mParam.get();
1937 ALOGV("AudioCommandThread() processing recording configuration update");
1938 svc = mService.promote();
1939 if (svc == 0) {
1940 break;
1941 }
1942 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001943 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001944 &data->mClientConfig, data->mClientEffects,
1945 &data->mDeviceConfig, data->mEffects,
1946 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001947 mLock.lock();
1948 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001949 case SET_EFFECT_SUSPENDED: {
1950 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1951 ALOGV("AudioCommandThread() processing set effect suspended");
1952 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1953 if (af != 0) {
1954 mLock.unlock();
1955 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1956 mLock.lock();
1957 }
1958 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001959 case AUDIO_MODULES_UPDATE: {
1960 ALOGV("AudioCommandThread() processing audio modules update");
1961 svc = mService.promote();
1962 if (svc == 0) {
1963 break;
1964 }
1965 mLock.unlock();
1966 svc->doOnNewAudioModulesAvailable();
1967 mLock.lock();
1968 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001969 case ROUTING_UPDATED: {
1970 ALOGV("AudioCommandThread() processing routing update");
1971 svc = mService.promote();
1972 if (svc == 0) {
1973 break;
1974 }
1975 mLock.unlock();
1976 svc->doOnRoutingUpdated();
1977 mLock.lock();
1978 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001979
Eric Laurented726cc2021-07-01 14:26:41 +02001980 case UPDATE_UID_STATES: {
1981 ALOGV("AudioCommandThread() processing updateUID states");
1982 svc = mService.promote();
1983 if (svc == 0) {
1984 break;
1985 }
1986 mLock.unlock();
1987 svc->updateUidStates();
1988 mLock.lock();
1989 } break;
1990
Eric Laurent15903592022-02-24 20:44:36 +01001991 case CHECK_SPATIALIZER_OUTPUT: {
1992 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02001993 svc = mService.promote();
1994 if (svc == 0) {
1995 break;
1996 }
1997 mLock.unlock();
1998 svc->doOnCheckSpatializer();
1999 mLock.lock();
2000 } break;
2001
Eric Laurent15903592022-02-24 20:44:36 +01002002 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2003 ALOGV("AudioCommandThread() processing update spatializer tracks");
2004 svc = mService.promote();
2005 if (svc == 0) {
2006 break;
2007 }
2008 mLock.unlock();
2009 svc->doOnUpdateActiveSpatializerTracks();
2010 mLock.lock();
2011 } break;
2012
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002014 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002016 {
2017 Mutex::Autolock _l(command->mLock);
2018 if (command->mWaitStatus) {
2019 command->mWaitStatus = false;
2020 command->mCond.signal();
2021 }
2022 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002023 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00002024 // release mLock before releasing strong reference on the service as
2025 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2026 // acquires mLock.
2027 mLock.unlock();
2028 svc.clear();
2029 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 } else {
2031 waitTime = mAudioCommands[0]->mTime - curTime;
2032 break;
2033 }
2034 }
Zach Janga754b4f2015-10-27 01:29:34 +00002035
2036 // release delayed commands wake lock if the queue is empty
2037 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002038 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00002039 }
2040
2041 // At this stage we have either an empty command queue or the first command in the queue
2042 // has a finite delay. So unless we are exiting it is safe to wait.
2043 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002044 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002045 if (waitTime == -1) {
2046 mWaitWorkCV.wait(mLock);
2047 } else {
2048 mWaitWorkCV.waitRelative(mLock, waitTime);
2049 }
Eric Laurent59a89232014-06-08 14:14:17 -07002050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002052 // release delayed commands wake lock before quitting
2053 if (!mAudioCommands.isEmpty()) {
2054 release_wake_lock(mName.string());
2055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 mLock.unlock();
2057 return false;
2058}
2059
2060status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2061{
2062 const size_t SIZE = 256;
2063 char buffer[SIZE];
2064 String8 result;
2065
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002066 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 if (!locked) {
2068 String8 result2(kCmdDeadlockedString);
2069 write(fd, result2.string(), result2.size());
2070 }
2071
2072 snprintf(buffer, SIZE, "- Commands:\n");
2073 result = String8(buffer);
2074 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002075 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 mAudioCommands[i]->dump(buffer, SIZE);
2077 result.append(buffer);
2078 }
2079 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002080 if (mLastCommand != 0) {
2081 mLastCommand->dump(buffer, SIZE);
2082 result.append(buffer);
2083 } else {
2084 result.append(" none\n");
2085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086
2087 write(fd, result.string(), result.size());
2088
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002089 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090
2091 return NO_ERROR;
2092}
2093
Glenn Kastenfff6d712012-01-12 16:38:12 -08002094status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002095 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002096 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002097 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098{
Eric Laurent0ede8922014-05-09 18:04:42 -07002099 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002101 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 data->mStream = stream;
2103 data->mVolume = volume;
2104 data->mIO = output;
2105 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002106 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002107 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002108 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002109 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110}
2111
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002112status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002113 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002114 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115{
Eric Laurent0ede8922014-05-09 18:04:42 -07002116 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002118 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002120 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002122 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002123 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002124 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002125 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126}
2127
2128status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2129{
Eric Laurent0ede8922014-05-09 18:04:42 -07002130 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002132 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133 data->mVolume = volume;
2134 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002135 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002136 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002137 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138}
2139
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002140void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2141 audio_session_t sessionId,
2142 bool suspended)
2143{
2144 sp<AudioCommand> command = new AudioCommand();
2145 command->mCommand = SET_EFFECT_SUSPENDED;
2146 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2147 data->mEffectId = effectId;
2148 data->mSessionId = sessionId;
2149 data->mSuspended = suspended;
2150 command->mParam = data;
2151 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2152 effectId, sessionId, suspended);
2153 sendCommand(command);
2154}
2155
2156
Eric Laurentd7fe0862018-07-14 16:48:01 -07002157void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158{
Eric Laurent0ede8922014-05-09 18:04:42 -07002159 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002160 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002161 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002162 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002163 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002164 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002165 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166}
2167
Eric Laurentd7fe0862018-07-14 16:48:01 -07002168void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169{
Eric Laurent0ede8922014-05-09 18:04:42 -07002170 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002172 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002173 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002174 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002175 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002176 sendCommand(command);
2177}
2178
Eric Laurent951f4552014-05-20 10:48:17 -07002179status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2180 const struct audio_patch *patch,
2181 audio_patch_handle_t *handle,
2182 int delayMs)
2183{
2184 status_t status = NO_ERROR;
2185
2186 sp<AudioCommand> command = new AudioCommand();
2187 command->mCommand = CREATE_AUDIO_PATCH;
2188 CreateAudioPatchData *data = new CreateAudioPatchData();
2189 data->mPatch = *patch;
2190 data->mHandle = *handle;
2191 command->mParam = data;
2192 command->mWaitStatus = true;
2193 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2194 status = sendCommand(command, delayMs);
2195 if (status == NO_ERROR) {
2196 *handle = data->mHandle;
2197 }
2198 return status;
2199}
2200
2201status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2202 int delayMs)
2203{
2204 sp<AudioCommand> command = new AudioCommand();
2205 command->mCommand = RELEASE_AUDIO_PATCH;
2206 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2207 data->mHandle = handle;
2208 command->mParam = data;
2209 command->mWaitStatus = true;
2210 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2211 return sendCommand(command, delayMs);
2212}
2213
Eric Laurentb52c1522014-05-20 11:27:36 -07002214void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2215{
2216 sp<AudioCommand> command = new AudioCommand();
2217 command->mCommand = UPDATE_AUDIOPORT_LIST;
2218 ALOGV("AudioCommandThread() adding update audio port list");
2219 sendCommand(command);
2220}
2221
Eric Laurented726cc2021-07-01 14:26:41 +02002222void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2223{
2224 sp<AudioCommand> command = new AudioCommand();
2225 command->mCommand = UPDATE_UID_STATES;
2226 ALOGV("AudioCommandThread() adding update UID states");
2227 sendCommand(command);
2228}
2229
Eric Laurentb52c1522014-05-20 11:27:36 -07002230void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2231{
2232 sp<AudioCommand>command = new AudioCommand();
2233 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2234 ALOGV("AudioCommandThread() adding update audio patch list");
2235 sendCommand(command);
2236}
2237
François Gaffiecfe17322018-11-07 13:41:29 +01002238void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2239 int flags)
2240{
2241 sp<AudioCommand>command = new AudioCommand();
2242 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2243 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2244 data->mGroup = group;
2245 data->mFlags = flags;
2246 command->mParam = data;
2247 ALOGV("AudioCommandThread() adding audio volume group changed");
2248 sendCommand(command);
2249}
2250
Eric Laurente1715a42014-05-20 11:30:42 -07002251status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2252 const struct audio_port_config *config, int delayMs)
2253{
2254 sp<AudioCommand> command = new AudioCommand();
2255 command->mCommand = SET_AUDIOPORT_CONFIG;
2256 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2257 data->mConfig = *config;
2258 command->mParam = data;
2259 command->mWaitStatus = true;
2260 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2261 return sendCommand(command, delayMs);
2262}
2263
Jean-Michel Trivide801052015-04-14 19:10:14 -07002264void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002265 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002266{
2267 sp<AudioCommand> command = new AudioCommand();
2268 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2269 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2270 data->mRegId = regId;
2271 data->mState = state;
2272 command->mParam = data;
2273 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2274 regId.string(), state);
2275 sendCommand(command);
2276}
2277
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002278void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002279 int event,
2280 const record_client_info_t *clientInfo,
2281 const audio_config_base_t *clientConfig,
2282 std::vector<effect_descriptor_t> clientEffects,
2283 const audio_config_base_t *deviceConfig,
2284 std::vector<effect_descriptor_t> effects,
2285 audio_patch_handle_t patchHandle,
2286 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002287{
2288 sp<AudioCommand>command = new AudioCommand();
2289 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2290 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2291 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002292 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002293 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002294 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002295 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002296 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002297 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002298 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002299 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002300 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2301 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002302 sendCommand(command);
2303}
2304
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002305void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2306{
2307 sp<AudioCommand> command = new AudioCommand();
2308 command->mCommand = AUDIO_MODULES_UPDATE;
2309 sendCommand(command);
2310}
2311
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002312void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2313{
2314 sp<AudioCommand>command = new AudioCommand();
2315 command->mCommand = ROUTING_UPDATED;
2316 ALOGV("AudioCommandThread() adding routing update");
2317 sendCommand(command);
2318}
2319
Eric Laurent81dd0f52021-07-05 11:54:40 +02002320void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2321{
2322 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002323 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002324 ALOGV("AudioCommandThread() adding check spatializer");
2325 sendCommand(command);
2326}
2327
Eric Laurent15903592022-02-24 20:44:36 +01002328void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2329{
2330 sp<AudioCommand>command = new AudioCommand();
2331 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2332 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2333 sendCommand(command);
2334}
2335
Eric Laurent0ede8922014-05-09 18:04:42 -07002336status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2337{
2338 {
2339 Mutex::Autolock _l(mLock);
2340 insertCommand_l(command, delayMs);
2341 mWaitWorkCV.signal();
2342 }
2343 Mutex::Autolock _l(command->mLock);
2344 while (command->mWaitStatus) {
2345 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2346 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2347 command->mStatus = TIMED_OUT;
2348 command->mWaitStatus = false;
2349 }
2350 }
2351 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352}
2353
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002355void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002357 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002358 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 command->mTime = systemTime() + milliseconds(delayMs);
2360
2361 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002362 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2364 }
2365
2366 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002367 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002368 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2370 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002371
2372 // create audio patch or release audio patch commands are equivalent
2373 // with regard to filtering
2374 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2375 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2376 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2377 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2378 continue;
2379 }
2380 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381
2382 switch (command->mCommand) {
2383 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002384 ParametersData *data = (ParametersData *)command->mParam.get();
2385 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002387 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002388 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002389 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2390 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2391 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002392 String8 key;
2393 String8 value;
2394 param.getAt(j, key, value);
2395 for (size_t k = 0; k < param2.size(); k++) {
2396 String8 key2;
2397 String8 value2;
2398 param2.getAt(k, key2, value2);
2399 if (key2 == key) {
2400 param2.remove(key2);
2401 ALOGV("Filtering out parameter %s", key2.string());
2402 break;
2403 }
2404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 }
2406 // if all keys have been filtered out, remove the command.
2407 // otherwise, update the key value pairs
2408 if (param2.size() == 0) {
2409 removedCommands.add(command2);
2410 } else {
2411 data2->mKeyValuePairs = param2.toString();
2412 }
Eric Laurent21e54562013-09-23 12:08:05 -07002413 command->mTime = command2->mTime;
2414 // force delayMs to non 0 so that code below does not request to wait for
2415 // command status as the command is now delayed
2416 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 } break;
2418
2419 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002420 VolumeData *data = (VolumeData *)command->mParam.get();
2421 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 if (data->mIO != data2->mIO) break;
2423 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002424 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002425 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002427 command->mTime = command2->mTime;
2428 // force delayMs to non 0 so that code below does not request to wait for
2429 // command status as the command is now delayed
2430 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002432
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002433 case SET_VOICE_VOLUME: {
2434 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2435 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2436 ALOGV("Filtering out voice volume command value %f replaced by %f",
2437 data2->mVolume, data->mVolume);
2438 removedCommands.add(command2);
2439 command->mTime = command2->mTime;
2440 // force delayMs to non 0 so that code below does not request to wait for
2441 // command status as the command is now delayed
2442 delayMs = 1;
2443 } break;
2444
Eric Laurente45b48a2014-09-04 16:40:57 -07002445 case CREATE_AUDIO_PATCH:
2446 case RELEASE_AUDIO_PATCH: {
2447 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002448 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002449 if (command->mCommand == CREATE_AUDIO_PATCH) {
2450 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002451 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002452 } else {
2453 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002454 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002455 }
2456 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002457 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002458 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2459 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002460 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002461 } else {
2462 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002463 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002464 }
2465 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002466 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2467 same output. */
2468 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2469 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2470 bool isOutputDiff = false;
2471 if (patch.num_sources == patch2.num_sources) {
2472 for (unsigned count = 0; count < patch.num_sources; count++) {
2473 if (patch.sources[count].id != patch2.sources[count].id) {
2474 isOutputDiff = true;
2475 break;
2476 }
2477 }
2478 if (isOutputDiff)
2479 break;
2480 }
2481 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002482 ALOGV("Filtering out %s audio patch command for handle %d",
2483 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2484 removedCommands.add(command2);
2485 command->mTime = command2->mTime;
2486 // force delayMs to non 0 so that code below does not request to wait for
2487 // command status as the command is now delayed
2488 delayMs = 1;
2489 } break;
2490
Jean-Michel Trivide801052015-04-14 19:10:14 -07002491 case DYN_POLICY_MIX_STATE_UPDATE: {
2492
2493 } break;
2494
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002495 case RECORDING_CONFIGURATION_UPDATE: {
2496
2497 } break;
2498
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002499 case ROUTING_UPDATED: {
2500
2501 } break;
2502
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 default:
2504 break;
2505 }
2506 }
2507
2508 // remove filtered commands
2509 for (size_t j = 0; j < removedCommands.size(); j++) {
2510 // removed commands always have time stamps greater than current command
2511 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002512 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002513 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 mAudioCommands.removeAt(k);
2515 break;
2516 }
2517 }
2518 }
2519 removedCommands.clear();
2520
Eric Laurentaa79bef2015-01-15 14:33:51 -08002521 // Disable wait for status if delay is not 0.
2522 // Except for create audio patch command because the returned patch handle
2523 // is needed by audio policy manager
2524 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002525 command->mWaitStatus = false;
2526 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002529 ALOGV("inserting command: %d at index %zd, num commands %zu",
2530 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 mAudioCommands.insertAt(command, i + 1);
2532}
2533
2534void AudioPolicyService::AudioCommandThread::exit()
2535{
Steve Block3856b092011-10-20 11:56:00 +01002536 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 {
2538 AutoMutex _l(mLock);
2539 requestExit();
2540 mWaitWorkCV.signal();
2541 }
Zach Janga754b4f2015-10-27 01:29:34 +00002542 // Note that we can call it from the thread loop if all other references have been released
2543 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 requestExitAndWait();
2545}
2546
2547void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2548{
2549 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2550 mCommand,
2551 (int)ns2s(mTime),
2552 (int)ns2ms(mTime)%1000,
2553 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002554 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555}
2556
Dima Zavinfce7a472011-04-19 22:30:36 -07002557/******* helpers for the service_ops callbacks defined below *********/
2558void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2559 const char *keyValuePairs,
2560 int delayMs)
2561{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002562 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002563 delayMs);
2564}
2565
2566int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2567 float volume,
2568 audio_io_handle_t output,
2569 int delayMs)
2570{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002571 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002572 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002573}
2574
Dima Zavinfce7a472011-04-19 22:30:36 -07002575int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2576{
2577 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2578}
2579
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002580void AudioPolicyService::setEffectSuspended(int effectId,
2581 audio_session_t sessionId,
2582 bool suspended)
2583{
2584 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2585}
2586
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002587Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002588{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002589 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002590 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002591}
2592
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002593
Dima Zavinfce7a472011-04-19 22:30:36 -07002594extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002595audio_module_handle_t aps_load_hw_module(void *service __unused,
2596 const char *name);
2597audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002598 audio_devices_t *pDevices,
2599 uint32_t *pSamplingRate,
2600 audio_format_t *pFormat,
2601 audio_channel_mask_t *pChannelMask,
2602 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002603 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002604
Eric Laurent2d388ec2014-03-07 13:25:54 -08002605audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002606 audio_module_handle_t module,
2607 audio_devices_t *pDevices,
2608 uint32_t *pSamplingRate,
2609 audio_format_t *pFormat,
2610 audio_channel_mask_t *pChannelMask,
2611 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002612 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002613 const audio_offload_info_t *offloadInfo);
2614audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002615 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002616 audio_io_handle_t output2);
2617int aps_close_output(void *service __unused, audio_io_handle_t output);
2618int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2619int aps_restore_output(void *service __unused, audio_io_handle_t output);
2620audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002621 audio_devices_t *pDevices,
2622 uint32_t *pSamplingRate,
2623 audio_format_t *pFormat,
2624 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002625 audio_in_acoustics_t acoustics __unused);
2626audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002627 audio_module_handle_t module,
2628 audio_devices_t *pDevices,
2629 uint32_t *pSamplingRate,
2630 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002631 audio_channel_mask_t *pChannelMask);
2632int aps_close_input(void *service __unused, audio_io_handle_t input);
2633int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002634int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002635 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002636 audio_io_handle_t dst_output);
2637char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2638 const char *keys);
2639void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2640 const char *kv_pairs, int delay_ms);
2641int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002642 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002643 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002644int aps_set_voice_volume(void *service, float volume, int delay_ms);
2645};
Dima Zavinfce7a472011-04-19 22:30:36 -07002646
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002647} // namespace android