blob: 3ee2aa3ee95729bbf6928702a75a12994280e182 [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{
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700117 {
118 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800119
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700120 // start audio commands thread
121 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
122 // start output activity command thread
123 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700124
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700125 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530126
127 loadAudioPolicyManager();
128 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700129 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200130
bryant_liuba2b4392014-06-11 16:49:30 +0800131 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000132 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
133 sp<UidPolicy> uidPolicy = new UidPolicy(this);
134 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700135 {
136 Mutex::Autolock _l(mLock);
137 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000138 mUidPolicy = uidPolicy;
139 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700140 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000141 uidPolicy->registerSelf();
142 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200143
Eric Laurent81dd0f52021-07-05 11:54:40 +0200144 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200145 if (mAudioPolicyManager != nullptr) {
146 Mutex::Autolock _l(mLock);
147 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
148 AudioDeviceTypeAddrVector devices;
149 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
150 if (hasSpatializer) {
151 mSpatializer = Spatializer::create(this);
152 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200153 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200154 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155}
156
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530157void AudioPolicyService::unloadAudioPolicyManager()
158{
159 ALOGV("%s ", __func__);
160 if (mLibraryHandle != nullptr) {
161 dlclose(mLibraryHandle);
162 }
163 mLibraryHandle = nullptr;
164 mCreateAudioPolicyManager = nullptr;
165 mDestroyAudioPolicyManager = nullptr;
166}
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168AudioPolicyService::~AudioPolicyService()
169{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700171 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700172
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530173 mDestroyAudioPolicyManager(mAudioPolicyManager);
174 unloadAudioPolicyManager();
175
Eric Laurentdce54a12014-03-10 12:19:46 -0700176 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700177
178 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800179 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800180
181 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800182 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000183
184 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800185 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700186}
187
188// A notification client is always registered by AudioSystem when the client process
189// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800190Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700191{
Eric Laurent12590252015-08-21 18:40:20 -0700192 if (client == 0) {
193 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800194 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700195 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800196 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700197
198 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800199 pid_t pid = IPCThreadState::self()->getCallingPid();
200 int64_t token = ((int64_t)uid<<32) | pid;
201
202 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700203 sp<NotificationClient> notificationClient = new NotificationClient(this,
204 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800205 uid,
206 pid);
207 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700208
luochaojiang908c7d72018-06-21 14:58:04 +0800209 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700210
Marco Nelissenf8880202014-11-14 07:58:25 -0800211 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700212 binder->linkToDeath(notificationClient);
213 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800214 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700215}
216
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800217Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700218{
219 Mutex::Autolock _l(mNotificationClientsLock);
220
221 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800222 pid_t pid = IPCThreadState::self()->getCallingPid();
223 int64_t token = ((int64_t)uid<<32) | pid;
224
225 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800226 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700227 }
luochaojiang908c7d72018-06-21 14:58:04 +0800228 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800229 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700230}
231
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800232Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100233{
234 Mutex::Autolock _l(mNotificationClientsLock);
235
236 uid_t uid = IPCThreadState::self()->getCallingUid();
237 pid_t pid = IPCThreadState::self()->getCallingPid();
238 int64_t token = ((int64_t)uid<<32) | pid;
239
240 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800241 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100242 }
243 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800244 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100245}
246
Eric Laurentb52c1522014-05-20 11:27:36 -0700247// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800248void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700249{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000250 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800251 {
252 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800253 int64_t token = ((int64_t)uid<<32) | pid;
254 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800255 for (size_t i = 0; i < mNotificationClients.size(); i++) {
256 if (mNotificationClients.valueAt(i)->uid() == uid) {
257 hasSameUid = true;
258 break;
259 }
260 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000261 }
262 {
263 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800264 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700265 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700266 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700267 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800268 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700269}
270
271void AudioPolicyService::onAudioPortListUpdate()
272{
273 mOutputCommandThread->updateAudioPortListCommand();
274}
275
276void AudioPolicyService::doOnAudioPortListUpdate()
277{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800278 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700279 for (size_t i = 0; i < mNotificationClients.size(); i++) {
280 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
281 }
282}
283
284void AudioPolicyService::onAudioPatchListUpdate()
285{
286 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287}
288
Eric Laurentb52c1522014-05-20 11:27:36 -0700289void AudioPolicyService::doOnAudioPatchListUpdate()
290{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800291 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700292 for (size_t i = 0; i < mNotificationClients.size(); i++) {
293 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
294 }
295}
296
François Gaffiecfe17322018-11-07 13:41:29 +0100297void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
298{
299 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
300}
301
302void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
303{
304 Mutex::Autolock _l(mNotificationClientsLock);
305 for (size_t i = 0; i < mNotificationClients.size(); i++) {
306 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
307 }
308}
309
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700310void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700311{
312 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
313 regId.string(), state);
314 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
315}
316
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700317void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700318{
319 Mutex::Autolock _l(mNotificationClientsLock);
320 for (size_t i = 0; i < mNotificationClients.size(); i++) {
321 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
322 }
323}
324
Eric Laurenta9f86652018-11-28 17:23:11 -0800325void AudioPolicyService::onRecordingConfigurationUpdate(
326 int event,
327 const record_client_info_t *clientInfo,
328 const audio_config_base_t *clientConfig,
329 std::vector<effect_descriptor_t> clientEffects,
330 const audio_config_base_t *deviceConfig,
331 std::vector<effect_descriptor_t> effects,
332 audio_patch_handle_t patchHandle,
333 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800334{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800335 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800336 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800337}
338
Eric Laurenta9f86652018-11-28 17:23:11 -0800339void AudioPolicyService::doOnRecordingConfigurationUpdate(
340 int event,
341 const record_client_info_t *clientInfo,
342 const audio_config_base_t *clientConfig,
343 std::vector<effect_descriptor_t> clientEffects,
344 const audio_config_base_t *deviceConfig,
345 std::vector<effect_descriptor_t> effects,
346 audio_patch_handle_t patchHandle,
347 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800348{
349 Mutex::Autolock _l(mNotificationClientsLock);
350 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800351 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800352 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800353 }
354}
355
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700356void AudioPolicyService::onRoutingUpdated()
357{
358 mOutputCommandThread->routingChangedCommand();
359}
360
361void AudioPolicyService::doOnRoutingUpdated()
362{
363 Mutex::Autolock _l(mNotificationClientsLock);
364 for (size_t i = 0; i < mNotificationClients.size(); i++) {
365 mNotificationClients.valueAt(i)->onRoutingUpdated();
366 }
367}
368
Eric Laurent81dd0f52021-07-05 11:54:40 +0200369void AudioPolicyService::onCheckSpatializer()
370{
371 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200372 onCheckSpatializer_l();
373}
374
375void AudioPolicyService::onCheckSpatializer_l()
376{
377 if (mSpatializer != nullptr) {
378 mOutputCommandThread->checkSpatializerCommand();
379 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200380}
381
382void AudioPolicyService::doOnCheckSpatializer()
383{
Eric Laurent39095982021-08-24 18:29:27 +0200384 Mutex::Autolock _l(mLock);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200385
Eric Laurent39095982021-08-24 18:29:27 +0200386 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200387 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200388 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
389 audio_io_handle_t currentOutput = mSpatializer->getOutput();
390 audio_io_handle_t newOutput;
391 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
392 audio_config_base_t config = mSpatializer->getAudioInConfig();
393 status_t status =
394 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100395 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
396 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200397 if (status == NO_ERROR && currentOutput == newOutput) {
398 return;
399 }
Eric Laurent15903592022-02-24 20:44:36 +0100400 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Eric Laurent39095982021-08-24 18:29:27 +0200401 mLock.unlock();
402 // It is OK to call detachOutput() is none is already attached.
403 mSpatializer->detachOutput();
404 if (status != NO_ERROR || newOutput == AUDIO_IO_HANDLE_NONE) {
Eric Laurent81dd0f52021-07-05 11:54:40 +0200405 mLock.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200406 return;
407 }
Eric Laurent15903592022-02-24 20:44:36 +0100408 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200409 mLock.lock();
410 if (status != NO_ERROR) {
411 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
412 }
413 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
414 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
415 mLock.unlock();
416 audio_io_handle_t output = mSpatializer->detachOutput();
417 mLock.lock();
418 if (output != AUDIO_IO_HANDLE_NONE) {
419 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200420 }
421 }
422 }
423}
424
Eric Laurent15903592022-02-24 20:44:36 +0100425size_t AudioPolicyService::countActiveClientsOnOutput_l(audio_io_handle_t output) REQUIRES(mLock) {
426 size_t count = 0;
427 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
428 auto client = mAudioPlaybackClients.valueAt(i);
429 if (client->io == output && client->active) {
430 count++;
431 }
432 }
433 return count;
434}
435
436void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
437 if (mSpatializer == nullptr) {
438 return;
439 }
440 mOutputCommandThread->updateActiveSpatializerTracksCommand();
441}
442
443void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
444{
445 Mutex::Autolock _l(mLock);
446 if (mSpatializer == nullptr) {
447 return;
448 }
449 mSpatializer->updateActiveTracks(countActiveClientsOnOutput_l(mSpatializer->getOutput()));
450}
451
452
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800453status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
454 audio_patch_handle_t *handle,
455 int delayMs)
456{
457 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
458}
459
460status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
461 int delayMs)
462{
463 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
464}
465
Eric Laurente1715a42014-05-20 11:30:42 -0700466status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
467 int delayMs)
468{
469 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
470}
471
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800472AudioPolicyService::NotificationClient::NotificationClient(
473 const sp<AudioPolicyService>& service,
474 const sp<media::IAudioPolicyServiceClient>& client,
475 uid_t uid,
476 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800477 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100478 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700479{
480}
481
482AudioPolicyService::NotificationClient::~NotificationClient()
483{
484}
485
486void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
487{
488 sp<NotificationClient> keep(this);
489 sp<AudioPolicyService> service = mService.promote();
490 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800491 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700492 }
493}
494
495void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
496{
Eric Laurente8726fe2015-06-26 09:39:24 -0700497 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700498 mAudioPolicyServiceClient->onAudioPortListUpdate();
499 }
500}
501
502void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
503{
Eric Laurente8726fe2015-06-26 09:39:24 -0700504 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700505 mAudioPolicyServiceClient->onAudioPatchListUpdate();
506 }
507}
Eric Laurent57dae992011-07-24 13:36:09 -0700508
Pattydd807582021-11-04 21:01:03 +0800509void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100510 int flags)
511{
512 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
513 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
514 }
515}
516
517
Jean-Michel Trivide801052015-04-14 19:10:14 -0700518void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700519 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700520{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700521 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800522 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
523 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800524 }
525}
526
527void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800528 int event,
529 const record_client_info_t *clientInfo,
530 const audio_config_base_t *clientConfig,
531 std::vector<effect_descriptor_t> clientEffects,
532 const audio_config_base_t *deviceConfig,
533 std::vector<effect_descriptor_t> effects,
534 audio_patch_handle_t patchHandle,
535 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800536{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700537 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800538 status_t status = [&]() -> status_t {
539 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
540 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
541 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700542 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700543 legacy2aidl_audio_config_base_t_AudioConfigBase(
544 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800545 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
546 convertContainer<std::vector<media::EffectDescriptor>>(
547 clientEffects,
548 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700549 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700550 legacy2aidl_audio_config_base_t_AudioConfigBase(
551 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800552 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
553 convertContainer<std::vector<media::EffectDescriptor>>(
554 effects,
555 legacy2aidl_effect_descriptor_t_EffectDescriptor));
556 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
557 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700558 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
559 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800560 return aidl_utils::statusTFromBinderStatus(
561 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
562 clientInfoAidl,
563 clientConfigAidl,
564 clientEffectsAidl,
565 deviceConfigAidl,
566 effectsAidl,
567 patchHandleAidl,
568 sourceAidl));
569 }();
570 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700571 }
572}
573
Eric Laurente8726fe2015-06-26 09:39:24 -0700574void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
575{
576 mAudioPortCallbacksEnabled = enabled;
577}
578
François Gaffiecfe17322018-11-07 13:41:29 +0100579void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
580{
581 mAudioVolumeGroupCallbacksEnabled = enabled;
582}
Eric Laurente8726fe2015-06-26 09:39:24 -0700583
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700584void AudioPolicyService::NotificationClient::onRoutingUpdated()
585{
586 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
587 mAudioPolicyServiceClient->onRoutingUpdated();
588 }
589}
590
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700592 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700593 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594}
595
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000596static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000598 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
599}
600
601static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
602{
603 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604}
605
606status_t AudioPolicyService::dumpInternals(int fd)
607{
608 const size_t SIZE = 256;
609 char buffer[SIZE];
610 String8 result;
611
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000612 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800613 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000614 std::stringstream msg;
615 size_t i = 0;
616 for (auto usage : mSupportedSystemUsages) {
617 if (i++ != 0) msg << ", ";
618 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
619 msg << strUsage;
620 } else {
621 msg << usage << " (unknown)";
622 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800623 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000624 if (i == 0) {
625 msg << "None";
626 }
627 msg << std::endl;
628 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800629
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800631
632 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633 return NO_ERROR;
634}
635
Eric Laurente8c8b432018-10-17 10:08:02 -0700636void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800637{
Eric Laurente8c8b432018-10-17 10:08:02 -0700638 Mutex::Autolock _l(mLock);
639 updateUidStates_l();
640}
641
642void AudioPolicyService::updateUidStates_l()
643{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800644// Go over all active clients and allow capture (does not force silence) in the
645// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800646// The client is in the active assistant list
647// AND is TOP
648// AND an accessibility service is TOP
649// AND source is either VOICE_RECOGNITION OR HOTWORD
650// OR there is no active privacy sensitive capture or call
651// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
652// AND source is VOICE_RECOGNITION OR HOTWORD
653// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800654// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700655// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800656// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800657// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800658// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
659// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800660// OR The client is an accessibility service
661// AND Is on TOP
662// AND the source is VOICE_RECOGNITION or HOTWORD
663// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700664// AND there is no active privacy sensitive capture or call
665// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800666// AND is on TOP
667// AND the source is VOICE_RECOGNITION or HOTWORD
668// OR the client source is virtual (remote submix, call audio TX or RX...)
669// OR the client source is HOTWORD
670// AND is on TOP
671// OR all active clients are using HOTWORD source
672// AND no call is active
673// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
674// OR the client is the current InputMethodService
675// AND a RTT call is active AND the source is VOICE_RECOGNITION
676// OR Any client
677// AND The assistant is not on TOP
678// AND is on TOP or latest started
679// AND there is no active privacy sensitive capture or call
680// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800681
Eric Laurent4e947da2019-10-17 15:24:06 -0700682
Eric Laurent4eb58f12018-12-07 16:41:02 -0800683 sp<AudioRecordClient> topActive;
684 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800685 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700686 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800687 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700688
Eric Laurenta46bedb2018-12-07 18:01:26 -0800689 nsecs_t topStartNs = 0;
690 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800691 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800692 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800693 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800694 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
695 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800696 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800697 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700698 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800699 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
700 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700701 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700702 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700703 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800704
Michael Groovercfd28302018-12-11 19:16:46 -0800705 // if Sensor Privacy is enabled then all recordings should be silenced.
706 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
707 silenceAllRecordings_l();
708 return;
709 }
710
Eric Laurente8c8b432018-10-17 10:08:02 -0700711 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
712 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000713 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
714 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800715 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700716 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800717 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700718
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700719 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700720 // clients which app is in IDLE state are not eligible for top active or
721 // latest active
722 if (appState == APP_STATE_IDLE) {
723 continue;
724 }
725
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700726 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700727 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800728 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700729 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700730 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800731 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800732 bool isPrivacySensitive =
733 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700734
Eric Laurentc21d5692020-02-25 10:24:36 -0800735 if (appState == APP_STATE_TOP) {
736 if (isPrivacySensitive) {
737 if (current->startTimeNs > topSensitiveStartNs) {
738 topSensitiveActive = current;
739 topSensitiveStartNs = current->startTimeNs;
740 }
741 } else {
742 if (current->startTimeNs > topStartNs) {
743 topActive = current;
744 topStartNs = current->startTimeNs;
745 }
746 }
747 if (isAssistant) {
748 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800749 if (isActiveAssistant) {
750 useActiveAssistantList = true;
751 } else if (!useActiveAssistantList) {
752 if (current->startTimeNs > latestAssistantStartNs) {
753 latestActiveAssistant = current;
754 latestAssistantStartNs = current->startTimeNs;
755 }
756 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800757 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800758 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800759 // Clients capturing for HOTWORD are not considered
760 // for latest active to avoid masking regular clients started before
761 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
762 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
763 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700764 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
765 // is marked latest sensitive active even if another app qualifies.
766 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700767 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700768 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700769 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000770 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700771 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700772 latestSensitiveActiveOrComm = current;
773 latestSensitiveStartNs = current->startTimeNs;
774 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800775 }
776 isSensitiveActive = true;
777 } else {
778 if (current->startTimeNs > latestStartNs) {
779 latestActive = current;
780 latestStartNs = current->startTimeNs;
781 }
782 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800783 }
784 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700785 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
786 onlyHotwordActive = false;
787 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100788 if (currentUid == mPhoneStateOwnerUid &&
789 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700790 isPhoneStateOwnerActive = true;
791 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800792 }
793
Eric Laurent1ff16a72019-03-14 18:35:04 -0700794 // if no active client with UI on Top, consider latest active as top
795 if (topActive == nullptr) {
796 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800797 topStartNs = latestStartNs;
798 }
799 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700800 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800801 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700802 } else if (latestSensitiveActiveOrComm != nullptr) {
803 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
804 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700805 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000806 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700807 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700808 topSensitiveActive = latestSensitiveActiveOrComm;
809 topSensitiveStartNs = latestSensitiveStartNs;
810 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800811 }
812
813 // If both privacy sensitive and regular capture are active:
814 // if the regular capture is privileged
815 // allow concurrency
816 // else
817 // favor the privacy sensitive case
818 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700819 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800820 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800821 }
822
823 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
824 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700825 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000826 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700827 if (!current->active) {
828 continue;
829 }
830
Eric Laurent4eb58f12018-12-07 16:41:02 -0800831 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700832 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000833 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700834 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000835 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800836 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
837 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800838
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000839 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700840 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000841 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700842 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700843 bool canCaptureCommunication = recordClient->canCaptureOutput
844 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700845 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700846 return !(isInCall && !canCaptureCall)
847 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800848 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700849
850 // By default allow capture if:
851 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700852 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700853 // AND there is no active privacy sensitive capture or call
854 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
855 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800856 && (isTopOrLatestActive || isTopOrLatestSensitive)
857 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700858 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800859 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800860
Eric Laurented726cc2021-07-01 14:26:41 +0200861 if (!current->hasOp()) {
862 // Never allow capture if app op is denied
863 allowCapture = false;
864 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700865 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
866 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800867 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700868 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800869 // Active assistant list is not being used
870 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700871 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800872 // OR there is no active privacy sensitive capture or call
873 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
874 // AND is latest TOP assistant AND
875 // uses VOICE_RECOGNITION OR uses HOTWORD
876 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -0700877 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800878 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700879 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800880 }
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800881 } else if (!(isSensitiveActive && !current->canCaptureOutput)
882 && canCaptureIfInCallOrCommunication(current)) {
883 if (isTopOrLatestAssistant
884 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
885 || source == AUDIO_SOURCE_HOTWORD)) {
886 allowCapture = true;
887 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
888 allowCapture = true;
889 }
890 }
891 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
892 // For assistant on active list and on top allow capture if:
893 // An accessibility service is on TOP
894 // AND the source is VOICE_RECOGNITION or HOTWORD
895 // OR there is no active privacy sensitive capture or call
896 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
897 // AND uses VOICE_RECOGNITION OR uses HOTWORD
898 if (isA11yOnTop) {
899 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
900 allowCapture = true;
901 }
902 } else if (!(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800903 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800904 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
905 {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700906 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800907 }
908 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700909 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700910 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700911 // The assistant is not on TOP
912 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700913 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700914 // OR
915 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
916 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700917 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800918 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700919 allowCapture = true;
920 }
Eric Laurent589171c2019-07-25 18:04:29 -0700921 if (isA11yOnTop) {
922 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
923 allowCapture = true;
924 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800925 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700926 } else if (source == AUDIO_SOURCE_HOTWORD) {
927 // For HOTWORD source allow capture when not on TOP if:
928 // All active clients are using HOTWORD source
929 // AND no call is active
930 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800931 if (onlyHotwordActive
932 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700933 allowCapture = true;
934 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700935 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700936 // For current InputMethodService allow capture if:
937 // A RTT call is active AND the source is VOICE_RECOGNITION
938 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
939 allowCapture = true;
940 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800941 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200942 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700943 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700944 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700945 }
946}
947
Michael Groovercfd28302018-12-11 19:16:46 -0800948void AudioPolicyService::silenceAllRecordings_l() {
949 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
950 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700951 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200952 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700953 }
Michael Groovercfd28302018-12-11 19:16:46 -0800954 }
955}
956
Eric Laurente8c8b432018-10-17 10:08:02 -0700957/* static */
958app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700959
960 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700961 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700962 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
963 // include persistent services
964 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700965 }
966 return APP_STATE_FOREGROUND;
967}
968
Eric Laurent4eb58f12018-12-07 16:41:02 -0800969/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800970bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800971{
972 switch (source) {
973 case AUDIO_SOURCE_VOICE_UPLINK:
974 case AUDIO_SOURCE_VOICE_DOWNLINK:
975 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800976 case AUDIO_SOURCE_REMOTE_SUBMIX:
977 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700978 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800979 return true;
980 default:
981 break;
982 }
983 return false;
984}
985
Eric Laurented726cc2021-07-01 14:26:41 +0200986/* static */
987bool AudioPolicyService::isAppOpSource(audio_source_t source)
988{
989 switch (source) {
990 case AUDIO_SOURCE_FM_TUNER:
991 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +0200992 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +0200993 return false;
994 default:
995 break;
996 }
997 return true;
998}
999
Eric Laurent8c7ef892021-06-10 13:32:16 +02001000void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001001{
1002 AutoCallerClear acc;
1003
1004 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001005 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001006 }
1007 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1008 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001009 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001010 if (client->silenced != silenced) {
1011 if (client->active) {
1012 if (silenced) {
1013 finishRecording(client->attributionSource, client->attributes.source);
1014 } else {
1015 std::stringstream msg;
1016 msg << "Audio recording un-silenced on session " << client->session;
1017 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1018 client->attributes.source)) {
1019 silenced = true;
1020 }
1021 }
1022 }
1023 af->setRecordSilenced(client->portId, silenced);
1024 client->silenced = silenced;
1025 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001026 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001027}
1028
Glenn Kasten0f11b512014-01-31 16:18:54 -08001029status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030{
Glenn Kasten44deb052012-02-05 18:09:08 -08001031 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 dumpPermissionDenial(fd);
1033 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001034 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 if (!locked) {
1036 String8 result(kDeadlockedString);
1037 write(fd, result.string(), result.size());
1038 }
1039
1040 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001041
1042 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
1043 write(fd, actPtr.string(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001044 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045 mAudioCommandThread->dump(fd);
1046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001048 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
1049 write(fd, octPtr.string(), octPtr.size());
1050 if (mOutputCommandThread != 0) {
1051 mOutputCommandThread->dump(fd);
1052 }
1053
Eric Laurentdce54a12014-03-10 12:19:46 -07001054 if (mAudioPolicyManager) {
1055 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001056 } else {
1057 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
1058 write(fd, apmPtr.string(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060
Kevin Rocard8be94972019-02-22 13:26:25 -08001061 mPackageManager.dump(fd);
1062
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001063 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 }
1065 return NO_ERROR;
1066}
1067
1068status_t AudioPolicyService::dumpPermissionDenial(int fd)
1069{
1070 const size_t SIZE = 256;
1071 char buffer[SIZE];
1072 String8 result;
1073 snprintf(buffer, SIZE, "Permission Denial: "
1074 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1075 IPCThreadState::self()->getCallingPid(),
1076 IPCThreadState::self()->getCallingUid());
1077 result.append(buffer);
1078 write(fd, result.string(), result.size());
1079 return NO_ERROR;
1080}
1081
1082status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001083 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001084 // make sure transactions reserved to AudioFlinger do not come from other processes
1085 switch (code) {
1086 case TRANSACTION_startOutput:
1087 case TRANSACTION_stopOutput:
1088 case TRANSACTION_releaseOutput:
1089 case TRANSACTION_getInputForAttr:
1090 case TRANSACTION_startInput:
1091 case TRANSACTION_stopInput:
1092 case TRANSACTION_releaseInput:
1093 case TRANSACTION_getOutputForEffect:
1094 case TRANSACTION_registerEffect:
1095 case TRANSACTION_unregisterEffect:
1096 case TRANSACTION_setEffectEnabled:
1097 case TRANSACTION_getStrategyForStream:
1098 case TRANSACTION_getOutputForAttr:
1099 case TRANSACTION_moveEffectsToIo:
1100 ALOGW("%s: transaction %d received from PID %d",
1101 __func__, code, IPCThreadState::self()->getCallingPid());
1102 return INVALID_OPERATION;
1103 default:
1104 break;
1105 }
1106
1107 // make sure the following transactions come from system components
1108 switch (code) {
1109 case TRANSACTION_setDeviceConnectionState:
1110 case TRANSACTION_handleDeviceConfigChange:
1111 case TRANSACTION_setPhoneState:
1112//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1113// case TRANSACTION_setForceUse:
1114 case TRANSACTION_initStreamVolume:
1115 case TRANSACTION_setStreamVolumeIndex:
1116 case TRANSACTION_setVolumeIndexForAttributes:
1117 case TRANSACTION_getStreamVolumeIndex:
1118 case TRANSACTION_getVolumeIndexForAttributes:
1119 case TRANSACTION_getMinVolumeIndexForAttributes:
1120 case TRANSACTION_getMaxVolumeIndexForAttributes:
1121 case TRANSACTION_isStreamActive:
1122 case TRANSACTION_isStreamActiveRemotely:
1123 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001124 case TRANSACTION_registerPolicyMixes:
1125 case TRANSACTION_setMasterMono:
1126 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001127 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001128 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001129 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001130 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001131 case TRANSACTION_setA11yServicesUids:
1132 case TRANSACTION_setUidDeviceAffinities:
1133 case TRANSACTION_removeUidDeviceAffinities:
1134 case TRANSACTION_setUserIdDeviceAffinities:
1135 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001136 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001137 case TRANSACTION_listAudioVolumeGroups:
1138 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1139 case TRANSACTION_acquireSoundTriggerSession:
1140 case TRANSACTION_releaseSoundTriggerSession:
1141 case TRANSACTION_setRttEnabled:
1142 case TRANSACTION_isCallScreenModeSupported:
1143 case TRANSACTION_setDevicesRoleForStrategy:
1144 case TRANSACTION_setSupportedSystemUsages:
1145 case TRANSACTION_removeDevicesRoleForStrategy:
1146 case TRANSACTION_getDevicesForRoleAndStrategy:
1147 case TRANSACTION_getDevicesForAttributes:
1148 case TRANSACTION_setAllowedCapturePolicy:
1149 case TRANSACTION_onNewAudioModulesAvailable:
1150 case TRANSACTION_setCurrentImeUid:
1151 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1152 case TRANSACTION_setDevicesRoleForCapturePreset:
1153 case TRANSACTION_addDevicesRoleForCapturePreset:
1154 case TRANSACTION_removeDevicesRoleForCapturePreset:
1155 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001156 case TRANSACTION_getDevicesForRoleAndCapturePreset:
1157 case TRANSACTION_getSpatializer: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001158 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1159 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1160 __func__, code, IPCThreadState::self()->getCallingPid(),
1161 IPCThreadState::self()->getCallingUid());
1162 return INVALID_OPERATION;
1163 }
1164 } break;
1165 default:
1166 break;
1167 }
1168
1169 std::string tag("IAudioPolicyService command " + std::to_string(code));
1170 TimeCheck check(tag.c_str());
1171
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001172 switch (code) {
1173 case SHELL_COMMAND_TRANSACTION: {
1174 int in = data.readFileDescriptor();
1175 int out = data.readFileDescriptor();
1176 int err = data.readFileDescriptor();
1177 int argc = data.readInt32();
1178 Vector<String16> args;
1179 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1180 args.add(data.readString16());
1181 }
1182 sp<IBinder> unusedCallback;
1183 sp<IResultReceiver> resultReceiver;
1184 status_t status;
1185 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1186 return status;
1187 }
1188 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1189 return status;
1190 }
1191 status = shellCommand(in, out, err, args);
1192 if (resultReceiver != nullptr) {
1193 resultReceiver->send(status);
1194 }
1195 return NO_ERROR;
1196 }
1197 }
1198
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1200}
1201
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001202// ------------------- Shell command implementation -------------------
1203
1204// NOTE: This is a remote API - make sure all args are validated
1205status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1206 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1207 return PERMISSION_DENIED;
1208 }
1209 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1210 return BAD_VALUE;
1211 }
jovanakbe066e12019-09-02 11:54:39 -07001212 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001213 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001214 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001215 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001216 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001217 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001218 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1219 purgePermissionCache();
1220 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001221 } else if (args.size() == 1 && args[0] == String16("help")) {
1222 printHelp(out);
1223 return NO_ERROR;
1224 }
1225 printHelp(err);
1226 return BAD_VALUE;
1227}
1228
jovanakbe066e12019-09-02 11:54:39 -07001229static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1230 if (userId < 0) {
1231 ALOGE("Invalid user: %d", userId);
1232 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001233 return BAD_VALUE;
1234 }
jovanakbe066e12019-09-02 11:54:39 -07001235
1236 PermissionController pc;
1237 uid = pc.getPackageUid(packageName, 0);
1238 if (uid <= 0) {
1239 ALOGE("Unknown package: '%s'", String8(packageName).string());
1240 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1241 return BAD_VALUE;
1242 }
1243
1244 uid = multiuser_get_uid(userId, uid);
1245 return NO_ERROR;
1246}
1247
1248status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1249 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1250 if (!(args.size() == 3 || args.size() == 5)) {
1251 printHelp(err);
1252 return BAD_VALUE;
1253 }
1254
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001255 bool active = false;
1256 if (args[2] == String16("active")) {
1257 active = true;
1258 } else if ((args[2] != String16("idle"))) {
1259 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1260 return BAD_VALUE;
1261 }
jovanakbe066e12019-09-02 11:54:39 -07001262
1263 int userId = 0;
1264 if (args.size() >= 5 && args[3] == String16("--user")) {
1265 userId = atoi(String8(args[4]));
1266 }
1267
1268 uid_t uid;
1269 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1270 return BAD_VALUE;
1271 }
1272
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001273 sp<UidPolicy> uidPolicy;
1274 {
1275 Mutex::Autolock _l(mLock);
1276 uidPolicy = mUidPolicy;
1277 }
1278 if (uidPolicy) {
1279 uidPolicy->addOverrideUid(uid, active);
1280 return NO_ERROR;
1281 }
1282 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001283}
1284
1285status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001286 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1287 if (!(args.size() == 2 || args.size() == 4)) {
1288 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001289 return BAD_VALUE;
1290 }
jovanakbe066e12019-09-02 11:54:39 -07001291
1292 int userId = 0;
1293 if (args.size() >= 4 && args[2] == String16("--user")) {
1294 userId = atoi(String8(args[3]));
1295 }
1296
1297 uid_t uid;
1298 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1299 return BAD_VALUE;
1300 }
1301
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001302 sp<UidPolicy> uidPolicy;
1303 {
1304 Mutex::Autolock _l(mLock);
1305 uidPolicy = mUidPolicy;
1306 }
1307 if (uidPolicy) {
1308 uidPolicy->removeOverrideUid(uid);
1309 return NO_ERROR;
1310 }
1311 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001312}
1313
1314status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001315 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1316 if (!(args.size() == 2 || args.size() == 4)) {
1317 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001318 return BAD_VALUE;
1319 }
jovanakbe066e12019-09-02 11:54:39 -07001320
1321 int userId = 0;
1322 if (args.size() >= 4 && args[2] == String16("--user")) {
1323 userId = atoi(String8(args[3]));
1324 }
1325
1326 uid_t uid;
1327 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1328 return BAD_VALUE;
1329 }
1330
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001331 sp<UidPolicy> uidPolicy;
1332 {
1333 Mutex::Autolock _l(mLock);
1334 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001335 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001336 if (uidPolicy) {
1337 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1338 }
1339 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001340}
1341
1342status_t AudioPolicyService::printHelp(int out) {
1343 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001344 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1345 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1346 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001347 " help print this message\n");
1348}
1349
1350// ----------- AudioPolicyService::UidPolicy implementation ----------
1351
1352void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001353 status_t res = mAm.linkToDeath(this);
1354 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001355 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001356 | ActivityManager::UID_OBSERVER_ACTIVE
1357 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001358 ActivityManager::PROCESS_STATE_UNKNOWN,
1359 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001360 if (!res) {
1361 Mutex::Autolock _l(mLock);
1362 mObserverRegistered = true;
1363 } else {
1364 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001365
Steven Moreland2f348142019-07-02 15:59:07 -07001366 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001367 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001368}
1369
1370void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001371 mAm.unlinkToDeath(this);
1372 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001373 Mutex::Autolock _l(mLock);
1374 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001375}
1376
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001377void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1378 Mutex::Autolock _l(mLock);
1379 mCachedUids.clear();
1380 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001381}
1382
Eric Laurente8c8b432018-10-17 10:08:02 -07001383void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001384 bool needToReregister = false;
1385 {
1386 Mutex::Autolock _l(mLock);
1387 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001388 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001389 if (needToReregister) {
1390 // Looks like ActivityManager has died previously, attempt to re-register.
1391 registerSelf();
1392 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001393}
1394
1395bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1396 if (isServiceUid(uid)) return true;
1397 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001398 {
1399 Mutex::Autolock _l(mLock);
1400 auto overrideIter = mOverrideUids.find(uid);
1401 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001402 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001403 }
1404 // In an absense of the ActivityManager, assume everything to be active.
1405 if (!mObserverRegistered) return true;
1406 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001407 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001408 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001409 }
1410 }
1411 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001412 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001413 {
1414 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001415 mCachedUids.insert(std::pair<uid_t,
1416 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1417 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001418 }
1419 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001420}
1421
Eric Laurente8c8b432018-10-17 10:08:02 -07001422int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1423 if (isServiceUid(uid)) {
1424 return ActivityManager::PROCESS_STATE_TOP;
1425 }
1426 checkRegistered();
1427 {
1428 Mutex::Autolock _l(mLock);
1429 auto overrideIter = mOverrideUids.find(uid);
1430 if (overrideIter != mOverrideUids.end()) {
1431 if (overrideIter->second.first) {
1432 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1433 return overrideIter->second.second;
1434 } else {
1435 auto cacheIter = mCachedUids.find(uid);
1436 if (cacheIter != mCachedUids.end()) {
1437 return cacheIter->second.second;
1438 }
1439 }
1440 }
1441 return ActivityManager::PROCESS_STATE_UNKNOWN;
1442 }
1443 // In an absense of the ActivityManager, assume everything to be active.
1444 if (!mObserverRegistered) {
1445 return ActivityManager::PROCESS_STATE_TOP;
1446 }
1447 auto cacheIter = mCachedUids.find(uid);
1448 if (cacheIter != mCachedUids.end()) {
1449 if (cacheIter->second.first) {
1450 return cacheIter->second.second;
1451 } else {
1452 return ActivityManager::PROCESS_STATE_UNKNOWN;
1453 }
1454 }
1455 }
1456 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001457 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001458 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1459 if (active) {
1460 state = am.getUidProcessState(uid, String16("audioserver"));
1461 }
1462 {
1463 Mutex::Autolock _l(mLock);
1464 mCachedUids.insert(std::pair<uid_t,
1465 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1466 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001467
Eric Laurente8c8b432018-10-17 10:08:02 -07001468 return state;
1469}
1470
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001471void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001472 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001473}
1474
1475void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001476 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001477}
1478
1479void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001480 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001481}
1482
Eric Laurente8c8b432018-10-17 10:08:02 -07001483void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1484 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001485 int64_t procStateSeq __unused,
1486 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001487 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1488 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001489 }
1490}
1491
1492void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001493 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1494}
1495
1496void AudioPolicyService::UidPolicy::notifyService() {
1497 sp<AudioPolicyService> service = mService.promote();
1498 if (service != nullptr) {
1499 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001500 }
1501}
1502
Eric Laurente8c8b432018-10-17 10:08:02 -07001503void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1504 std::pair<bool, int>> *uids,
1505 uid_t uid,
1506 bool active,
1507 int state,
1508 bool insert) {
1509 if (isServiceUid(uid)) {
1510 return;
1511 }
1512 bool wasActive = isUidActive(uid);
1513 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001514 {
1515 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001516 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001517 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001518 if (wasActive != isUidActive(uid) || state != previousState) {
1519 notifyService();
1520 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001521}
1522
Eric Laurente8c8b432018-10-17 10:08:02 -07001523void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1524 std::pair<bool, int>> *uids,
1525 uid_t uid,
1526 bool active,
1527 int state,
1528 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001529 auto it = uids->find(uid);
1530 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001531 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001532 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1533 it->second.first = active;
1534 }
1535 if (it->second.first) {
1536 it->second.second = state;
1537 } else {
1538 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1539 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001540 } else {
1541 uids->erase(it);
1542 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001543 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1544 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1545 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001546 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001547}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548
Eric Laurent4eb58f12018-12-07 16:41:02 -08001549bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1550 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001551 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001552 continue;
1553 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001554 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1555 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001556 return true;
1557 }
1558 }
1559 return false;
1560}
1561
Eric Laurentb78763e2018-10-17 10:08:02 -07001562bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1563{
1564 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1565 return it != mA11yUids.end();
1566}
1567
Oscar Azucena829d90d2022-01-28 17:17:56 -08001568void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1569 mAssistantUids.clear();
1570 mAssistantUids = uids;
1571}
1572
1573bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1574{
1575 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1576 return it != mAssistantUids.end();
1577}
1578
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001579void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1580 mActiveAssistantUids = activeUids;
1581}
1582
1583bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1584{
1585 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1586 mActiveAssistantUids.end(), uid);
1587 return it != mActiveAssistantUids.end();
1588}
1589
Oscar Azucena829d90d2022-01-28 17:17:56 -08001590void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1591 const size_t SIZE = 256;
1592 char buffer[SIZE];
1593 String8 result;
1594 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1595 snprintf(buffer, SIZE, "\t%s: \n", title);
1596 result.append(buffer);
1597 int counter = 0;
1598 if (uids.empty()) {
1599 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1600 result.append(buffer);
1601 return;
1602 }
1603 for (const auto &uid : uids) {
1604 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1605 result.append(buffer);
1606 }
1607 };
1608
1609 snprintf(buffer, SIZE, "UID Policy:\n");
1610 result.append(buffer);
1611 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1612 result.append(buffer);
1613
1614 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001615 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001616
1617 appendUidsToResult("Accessibility UIDs", mA11yUids);
1618
1619 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1620 result.append(buffer);
1621
1622 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1623 result.append(buffer);
1624
1625 write(fd, result.string(), result.size());
1626}
1627
Michael Groovercfd28302018-12-11 19:16:46 -08001628// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1629void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1630 SensorPrivacyManager spm;
1631 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1632 spm.addSensorPrivacyListener(this);
1633}
1634
1635void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1636 SensorPrivacyManager spm;
1637 spm.removeSensorPrivacyListener(this);
1638}
1639
1640bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1641 return mSensorPrivacyEnabled;
1642}
1643
Evan Seversond8dc6832022-01-27 10:47:03 -08001644binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1645 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001646 mSensorPrivacyEnabled = enabled;
1647 sp<AudioPolicyService> service = mService.promote();
1648 if (service != nullptr) {
1649 service->updateUidStates();
1650 }
1651 return binder::Status::ok();
1652}
1653
Eric Laurented726cc2021-07-01 14:26:41 +02001654// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1655
1656// static
1657sp<AudioPolicyService::OpRecordAudioMonitor>
1658AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1659 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1660 wp<AudioCommandThread> commandThread)
1661{
Eric Laurent987ce102021-07-05 12:11:51 +02001662 if (isAudioServerOrRootUid(attributionSource.uid)) {
1663 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001664 attributionSource.toString().c_str());
1665 return nullptr;
1666 }
1667
1668 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1669 ALOGD("not monitoring app op for uid %d and source %d",
1670 attributionSource.uid, attr.source);
1671 return nullptr;
1672 }
1673
1674 if (!attributionSource.packageName.has_value()
1675 || attributionSource.packageName.value().size() == 0) {
1676 return nullptr;
1677 }
1678 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1679}
1680
1681AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1682 const AttributionSourceState& attributionSource, int32_t appOp,
1683 wp<AudioCommandThread> commandThread) :
1684 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1685 mCommandThread(commandThread)
1686{
1687}
1688
1689AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1690{
1691 if (mOpCallback != 0) {
1692 mAppOpsManager.stopWatchingMode(mOpCallback);
1693 }
1694 mOpCallback.clear();
1695}
1696
1697void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1698{
1699 checkOp();
1700 mOpCallback = new RecordAudioOpCallback(this);
1701 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1702 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1703 // since it controls the mic permission for legacy apps.
1704 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1705 mAttributionSource.packageName.value_or(""))),
1706 mOpCallback);
1707}
1708
1709bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1710 return mHasOp.load();
1711}
1712
1713// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1714// is updated in AppOp callback and in onFirstRef()
1715// Note this method is never called (and never to be) for audio server / root track
1716// due to the UID in createIfNeeded(). As a result for those record track, it's:
1717// - not called from constructor,
1718// - not called from RecordAudioOpCallback because the callback is not installed in this case
1719void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1720{
1721 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1722 // since it controls the mic permission for legacy apps.
1723 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1724 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1725 mAttributionSource.packageName.value_or(""))));
1726 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1727 // verbose logging only log when appOp changed
1728 ALOGI_IF(hasIt != mHasOp.load(),
1729 "App op %d missing, %ssilencing record %s",
1730 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1731 mHasOp.store(hasIt);
1732
1733 if (updateUidStates) {
1734 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1735 if (commandThread != nullptr) {
1736 commandThread->updateUidStatesCommand();
1737 }
1738 }
1739}
1740
1741AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1742 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1743{ }
1744
1745void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1746 const String16& packageName __unused) {
1747 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1748 if (monitor != NULL) {
1749 if (op != monitor->getOp()) {
1750 return;
1751 }
1752 monitor->checkOp(true);
1753 }
1754}
1755
1756
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1758
Eric Laurentbfb1b832013-01-07 09:53:42 -08001759AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1760 const wp<AudioPolicyService>& service)
1761 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763}
1764
1765
1766AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1767{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001768 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 release_wake_lock(mName.string());
1770 }
1771 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772}
1773
1774void AudioPolicyService::AudioCommandThread::onFirstRef()
1775{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001776 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777}
1778
1779bool AudioPolicyService::AudioCommandThread::threadLoop()
1780{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001781 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782
1783 mLock.lock();
1784 while (!exitPending())
1785 {
Eric Laurent59a89232014-06-08 14:14:17 -07001786 sp<AudioPolicyService> svc;
1787 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 nsecs_t curTime = systemTime();
1789 // commands are sorted by increasing time stamp: execute them from index 0 and up
1790 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001791 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001793 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794
1795 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001797 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001798 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001799 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001800 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001801 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1802 data->mVolume,
1803 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001804 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 }break;
1806 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001807 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001808 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1809 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001810 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001811 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001812 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001813 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001815 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001816 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001817 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001818 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001820 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001822 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001823 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001824 ALOGV("AudioCommandThread() processing stop output portId %d",
1825 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001826 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001827 if (svc == 0) {
1828 break;
1829 }
1830 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001831 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001832 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001833 }break;
1834 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001835 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001836 ALOGV("AudioCommandThread() processing release output portId %d",
1837 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001838 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001839 if (svc == 0) {
1840 break;
1841 }
1842 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001843 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001844 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001846 case CREATE_AUDIO_PATCH: {
1847 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1848 ALOGV("AudioCommandThread() processing create audio patch");
1849 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1850 if (af == 0) {
1851 command->mStatus = PERMISSION_DENIED;
1852 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001853 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001854 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001855 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001856 }
1857 } break;
1858 case RELEASE_AUDIO_PATCH: {
1859 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1860 ALOGV("AudioCommandThread() processing release audio patch");
1861 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1862 if (af == 0) {
1863 command->mStatus = PERMISSION_DENIED;
1864 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001865 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001866 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001867 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001868 }
1869 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001870 case UPDATE_AUDIOPORT_LIST: {
1871 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001872 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001873 if (svc == 0) {
1874 break;
1875 }
1876 mLock.unlock();
1877 svc->doOnAudioPortListUpdate();
1878 mLock.lock();
1879 }break;
1880 case UPDATE_AUDIOPATCH_LIST: {
1881 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001882 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001883 if (svc == 0) {
1884 break;
1885 }
1886 mLock.unlock();
1887 svc->doOnAudioPatchListUpdate();
1888 mLock.lock();
1889 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001890 case CHANGED_AUDIOVOLUMEGROUP: {
1891 AudioVolumeGroupData *data =
1892 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1893 ALOGV("AudioCommandThread() processing update audio volume group");
1894 svc = mService.promote();
1895 if (svc == 0) {
1896 break;
1897 }
1898 mLock.unlock();
1899 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1900 mLock.lock();
1901 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001902 case SET_AUDIOPORT_CONFIG: {
1903 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1904 ALOGV("AudioCommandThread() processing set port config");
1905 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1906 if (af == 0) {
1907 command->mStatus = PERMISSION_DENIED;
1908 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001909 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001910 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001911 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001912 }
1913 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001914 case DYN_POLICY_MIX_STATE_UPDATE: {
1915 DynPolicyMixStateUpdateData *data =
1916 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001917 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1918 data->mRegId.string(), data->mState);
1919 svc = mService.promote();
1920 if (svc == 0) {
1921 break;
1922 }
1923 mLock.unlock();
1924 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1925 mLock.lock();
1926 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001927 case RECORDING_CONFIGURATION_UPDATE: {
1928 RecordingConfigurationUpdateData *data =
1929 (RecordingConfigurationUpdateData *)command->mParam.get();
1930 ALOGV("AudioCommandThread() processing recording configuration update");
1931 svc = mService.promote();
1932 if (svc == 0) {
1933 break;
1934 }
1935 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001936 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001937 &data->mClientConfig, data->mClientEffects,
1938 &data->mDeviceConfig, data->mEffects,
1939 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001940 mLock.lock();
1941 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001942 case SET_EFFECT_SUSPENDED: {
1943 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1944 ALOGV("AudioCommandThread() processing set effect suspended");
1945 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1946 if (af != 0) {
1947 mLock.unlock();
1948 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1949 mLock.lock();
1950 }
1951 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001952 case AUDIO_MODULES_UPDATE: {
1953 ALOGV("AudioCommandThread() processing audio modules update");
1954 svc = mService.promote();
1955 if (svc == 0) {
1956 break;
1957 }
1958 mLock.unlock();
1959 svc->doOnNewAudioModulesAvailable();
1960 mLock.lock();
1961 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001962 case ROUTING_UPDATED: {
1963 ALOGV("AudioCommandThread() processing routing update");
1964 svc = mService.promote();
1965 if (svc == 0) {
1966 break;
1967 }
1968 mLock.unlock();
1969 svc->doOnRoutingUpdated();
1970 mLock.lock();
1971 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001972
Eric Laurented726cc2021-07-01 14:26:41 +02001973 case UPDATE_UID_STATES: {
1974 ALOGV("AudioCommandThread() processing updateUID states");
1975 svc = mService.promote();
1976 if (svc == 0) {
1977 break;
1978 }
1979 mLock.unlock();
1980 svc->updateUidStates();
1981 mLock.lock();
1982 } break;
1983
Eric Laurent15903592022-02-24 20:44:36 +01001984 case CHECK_SPATIALIZER_OUTPUT: {
1985 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02001986 svc = mService.promote();
1987 if (svc == 0) {
1988 break;
1989 }
1990 mLock.unlock();
1991 svc->doOnCheckSpatializer();
1992 mLock.lock();
1993 } break;
1994
Eric Laurent15903592022-02-24 20:44:36 +01001995 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
1996 ALOGV("AudioCommandThread() processing update spatializer tracks");
1997 svc = mService.promote();
1998 if (svc == 0) {
1999 break;
2000 }
2001 mLock.unlock();
2002 svc->doOnUpdateActiveSpatializerTracks();
2003 mLock.lock();
2004 } break;
2005
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002007 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002009 {
2010 Mutex::Autolock _l(command->mLock);
2011 if (command->mWaitStatus) {
2012 command->mWaitStatus = false;
2013 command->mCond.signal();
2014 }
2015 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002016 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00002017 // release mLock before releasing strong reference on the service as
2018 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2019 // acquires mLock.
2020 mLock.unlock();
2021 svc.clear();
2022 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 } else {
2024 waitTime = mAudioCommands[0]->mTime - curTime;
2025 break;
2026 }
2027 }
Zach Janga754b4f2015-10-27 01:29:34 +00002028
2029 // release delayed commands wake lock if the queue is empty
2030 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002031 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00002032 }
2033
2034 // At this stage we have either an empty command queue or the first command in the queue
2035 // has a finite delay. So unless we are exiting it is safe to wait.
2036 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002037 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002038 if (waitTime == -1) {
2039 mWaitWorkCV.wait(mLock);
2040 } else {
2041 mWaitWorkCV.waitRelative(mLock, waitTime);
2042 }
Eric Laurent59a89232014-06-08 14:14:17 -07002043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002045 // release delayed commands wake lock before quitting
2046 if (!mAudioCommands.isEmpty()) {
2047 release_wake_lock(mName.string());
2048 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 mLock.unlock();
2050 return false;
2051}
2052
2053status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2054{
2055 const size_t SIZE = 256;
2056 char buffer[SIZE];
2057 String8 result;
2058
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002059 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 if (!locked) {
2061 String8 result2(kCmdDeadlockedString);
2062 write(fd, result2.string(), result2.size());
2063 }
2064
2065 snprintf(buffer, SIZE, "- Commands:\n");
2066 result = String8(buffer);
2067 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002068 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 mAudioCommands[i]->dump(buffer, SIZE);
2070 result.append(buffer);
2071 }
2072 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002073 if (mLastCommand != 0) {
2074 mLastCommand->dump(buffer, SIZE);
2075 result.append(buffer);
2076 } else {
2077 result.append(" none\n");
2078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079
2080 write(fd, result.string(), result.size());
2081
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002082 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083
2084 return NO_ERROR;
2085}
2086
Glenn Kastenfff6d712012-01-12 16:38:12 -08002087status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002088 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002089 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002090 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091{
Eric Laurent0ede8922014-05-09 18:04:42 -07002092 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002094 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095 data->mStream = stream;
2096 data->mVolume = volume;
2097 data->mIO = output;
2098 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002099 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002100 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002101 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002102 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103}
2104
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002105status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002106 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002107 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108{
Eric Laurent0ede8922014-05-09 18:04:42 -07002109 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002111 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002113 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002115 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002116 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002117 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002118 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119}
2120
2121status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2122{
Eric Laurent0ede8922014-05-09 18:04:42 -07002123 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002125 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 data->mVolume = volume;
2127 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002128 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002129 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002130 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131}
2132
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002133void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2134 audio_session_t sessionId,
2135 bool suspended)
2136{
2137 sp<AudioCommand> command = new AudioCommand();
2138 command->mCommand = SET_EFFECT_SUSPENDED;
2139 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2140 data->mEffectId = effectId;
2141 data->mSessionId = sessionId;
2142 data->mSuspended = suspended;
2143 command->mParam = data;
2144 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2145 effectId, sessionId, suspended);
2146 sendCommand(command);
2147}
2148
2149
Eric Laurentd7fe0862018-07-14 16:48:01 -07002150void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151{
Eric Laurent0ede8922014-05-09 18:04:42 -07002152 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002154 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002155 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002156 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002157 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002158 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159}
2160
Eric Laurentd7fe0862018-07-14 16:48:01 -07002161void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162{
Eric Laurent0ede8922014-05-09 18:04:42 -07002163 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002165 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002166 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002167 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002168 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002169 sendCommand(command);
2170}
2171
Eric Laurent951f4552014-05-20 10:48:17 -07002172status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2173 const struct audio_patch *patch,
2174 audio_patch_handle_t *handle,
2175 int delayMs)
2176{
2177 status_t status = NO_ERROR;
2178
2179 sp<AudioCommand> command = new AudioCommand();
2180 command->mCommand = CREATE_AUDIO_PATCH;
2181 CreateAudioPatchData *data = new CreateAudioPatchData();
2182 data->mPatch = *patch;
2183 data->mHandle = *handle;
2184 command->mParam = data;
2185 command->mWaitStatus = true;
2186 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2187 status = sendCommand(command, delayMs);
2188 if (status == NO_ERROR) {
2189 *handle = data->mHandle;
2190 }
2191 return status;
2192}
2193
2194status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2195 int delayMs)
2196{
2197 sp<AudioCommand> command = new AudioCommand();
2198 command->mCommand = RELEASE_AUDIO_PATCH;
2199 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2200 data->mHandle = handle;
2201 command->mParam = data;
2202 command->mWaitStatus = true;
2203 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2204 return sendCommand(command, delayMs);
2205}
2206
Eric Laurentb52c1522014-05-20 11:27:36 -07002207void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2208{
2209 sp<AudioCommand> command = new AudioCommand();
2210 command->mCommand = UPDATE_AUDIOPORT_LIST;
2211 ALOGV("AudioCommandThread() adding update audio port list");
2212 sendCommand(command);
2213}
2214
Eric Laurented726cc2021-07-01 14:26:41 +02002215void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2216{
2217 sp<AudioCommand> command = new AudioCommand();
2218 command->mCommand = UPDATE_UID_STATES;
2219 ALOGV("AudioCommandThread() adding update UID states");
2220 sendCommand(command);
2221}
2222
Eric Laurentb52c1522014-05-20 11:27:36 -07002223void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2224{
2225 sp<AudioCommand>command = new AudioCommand();
2226 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2227 ALOGV("AudioCommandThread() adding update audio patch list");
2228 sendCommand(command);
2229}
2230
François Gaffiecfe17322018-11-07 13:41:29 +01002231void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2232 int flags)
2233{
2234 sp<AudioCommand>command = new AudioCommand();
2235 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2236 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2237 data->mGroup = group;
2238 data->mFlags = flags;
2239 command->mParam = data;
2240 ALOGV("AudioCommandThread() adding audio volume group changed");
2241 sendCommand(command);
2242}
2243
Eric Laurente1715a42014-05-20 11:30:42 -07002244status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2245 const struct audio_port_config *config, int delayMs)
2246{
2247 sp<AudioCommand> command = new AudioCommand();
2248 command->mCommand = SET_AUDIOPORT_CONFIG;
2249 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2250 data->mConfig = *config;
2251 command->mParam = data;
2252 command->mWaitStatus = true;
2253 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2254 return sendCommand(command, delayMs);
2255}
2256
Jean-Michel Trivide801052015-04-14 19:10:14 -07002257void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002258 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002259{
2260 sp<AudioCommand> command = new AudioCommand();
2261 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2262 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2263 data->mRegId = regId;
2264 data->mState = state;
2265 command->mParam = data;
2266 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2267 regId.string(), state);
2268 sendCommand(command);
2269}
2270
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002271void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002272 int event,
2273 const record_client_info_t *clientInfo,
2274 const audio_config_base_t *clientConfig,
2275 std::vector<effect_descriptor_t> clientEffects,
2276 const audio_config_base_t *deviceConfig,
2277 std::vector<effect_descriptor_t> effects,
2278 audio_patch_handle_t patchHandle,
2279 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002280{
2281 sp<AudioCommand>command = new AudioCommand();
2282 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2283 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2284 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002285 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002286 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002287 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002288 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002289 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002290 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002291 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002292 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002293 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2294 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002295 sendCommand(command);
2296}
2297
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002298void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2299{
2300 sp<AudioCommand> command = new AudioCommand();
2301 command->mCommand = AUDIO_MODULES_UPDATE;
2302 sendCommand(command);
2303}
2304
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002305void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2306{
2307 sp<AudioCommand>command = new AudioCommand();
2308 command->mCommand = ROUTING_UPDATED;
2309 ALOGV("AudioCommandThread() adding routing update");
2310 sendCommand(command);
2311}
2312
Eric Laurent81dd0f52021-07-05 11:54:40 +02002313void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2314{
2315 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002316 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002317 ALOGV("AudioCommandThread() adding check spatializer");
2318 sendCommand(command);
2319}
2320
Eric Laurent15903592022-02-24 20:44:36 +01002321void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2322{
2323 sp<AudioCommand>command = new AudioCommand();
2324 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2325 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2326 sendCommand(command);
2327}
2328
Eric Laurent0ede8922014-05-09 18:04:42 -07002329status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2330{
2331 {
2332 Mutex::Autolock _l(mLock);
2333 insertCommand_l(command, delayMs);
2334 mWaitWorkCV.signal();
2335 }
2336 Mutex::Autolock _l(command->mLock);
2337 while (command->mWaitStatus) {
2338 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2339 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2340 command->mStatus = TIMED_OUT;
2341 command->mWaitStatus = false;
2342 }
2343 }
2344 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002345}
2346
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002348void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002350 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002351 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 command->mTime = systemTime() + milliseconds(delayMs);
2353
2354 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2357 }
2358
2359 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002360 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002361 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002362 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2363 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002364
2365 // create audio patch or release audio patch commands are equivalent
2366 // with regard to filtering
2367 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2368 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2369 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2370 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2371 continue;
2372 }
2373 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374
2375 switch (command->mCommand) {
2376 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002377 ParametersData *data = (ParametersData *)command->mParam.get();
2378 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002380 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002381 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2383 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2384 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002385 String8 key;
2386 String8 value;
2387 param.getAt(j, key, value);
2388 for (size_t k = 0; k < param2.size(); k++) {
2389 String8 key2;
2390 String8 value2;
2391 param2.getAt(k, key2, value2);
2392 if (key2 == key) {
2393 param2.remove(key2);
2394 ALOGV("Filtering out parameter %s", key2.string());
2395 break;
2396 }
2397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 }
2399 // if all keys have been filtered out, remove the command.
2400 // otherwise, update the key value pairs
2401 if (param2.size() == 0) {
2402 removedCommands.add(command2);
2403 } else {
2404 data2->mKeyValuePairs = param2.toString();
2405 }
Eric Laurent21e54562013-09-23 12:08:05 -07002406 command->mTime = command2->mTime;
2407 // force delayMs to non 0 so that code below does not request to wait for
2408 // command status as the command is now delayed
2409 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410 } break;
2411
2412 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002413 VolumeData *data = (VolumeData *)command->mParam.get();
2414 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 if (data->mIO != data2->mIO) break;
2416 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002417 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002418 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002420 command->mTime = command2->mTime;
2421 // force delayMs to non 0 so that code below does not request to wait for
2422 // command status as the command is now delayed
2423 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002425
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002426 case SET_VOICE_VOLUME: {
2427 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2428 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2429 ALOGV("Filtering out voice volume command value %f replaced by %f",
2430 data2->mVolume, data->mVolume);
2431 removedCommands.add(command2);
2432 command->mTime = command2->mTime;
2433 // force delayMs to non 0 so that code below does not request to wait for
2434 // command status as the command is now delayed
2435 delayMs = 1;
2436 } break;
2437
Eric Laurente45b48a2014-09-04 16:40:57 -07002438 case CREATE_AUDIO_PATCH:
2439 case RELEASE_AUDIO_PATCH: {
2440 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002441 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002442 if (command->mCommand == CREATE_AUDIO_PATCH) {
2443 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002444 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002445 } else {
2446 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002447 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002448 }
2449 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002450 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002451 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2452 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002453 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002454 } else {
2455 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002456 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002457 }
2458 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002459 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2460 same output. */
2461 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2462 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2463 bool isOutputDiff = false;
2464 if (patch.num_sources == patch2.num_sources) {
2465 for (unsigned count = 0; count < patch.num_sources; count++) {
2466 if (patch.sources[count].id != patch2.sources[count].id) {
2467 isOutputDiff = true;
2468 break;
2469 }
2470 }
2471 if (isOutputDiff)
2472 break;
2473 }
2474 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002475 ALOGV("Filtering out %s audio patch command for handle %d",
2476 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2477 removedCommands.add(command2);
2478 command->mTime = command2->mTime;
2479 // force delayMs to non 0 so that code below does not request to wait for
2480 // command status as the command is now delayed
2481 delayMs = 1;
2482 } break;
2483
Jean-Michel Trivide801052015-04-14 19:10:14 -07002484 case DYN_POLICY_MIX_STATE_UPDATE: {
2485
2486 } break;
2487
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002488 case RECORDING_CONFIGURATION_UPDATE: {
2489
2490 } break;
2491
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002492 case ROUTING_UPDATED: {
2493
2494 } break;
2495
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 default:
2497 break;
2498 }
2499 }
2500
2501 // remove filtered commands
2502 for (size_t j = 0; j < removedCommands.size(); j++) {
2503 // removed commands always have time stamps greater than current command
2504 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002505 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002506 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507 mAudioCommands.removeAt(k);
2508 break;
2509 }
2510 }
2511 }
2512 removedCommands.clear();
2513
Eric Laurentaa79bef2015-01-15 14:33:51 -08002514 // Disable wait for status if delay is not 0.
2515 // Except for create audio patch command because the returned patch handle
2516 // is needed by audio policy manager
2517 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002518 command->mWaitStatus = false;
2519 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002522 ALOGV("inserting command: %d at index %zd, num commands %zu",
2523 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 mAudioCommands.insertAt(command, i + 1);
2525}
2526
2527void AudioPolicyService::AudioCommandThread::exit()
2528{
Steve Block3856b092011-10-20 11:56:00 +01002529 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 {
2531 AutoMutex _l(mLock);
2532 requestExit();
2533 mWaitWorkCV.signal();
2534 }
Zach Janga754b4f2015-10-27 01:29:34 +00002535 // Note that we can call it from the thread loop if all other references have been released
2536 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 requestExitAndWait();
2538}
2539
2540void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2541{
2542 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2543 mCommand,
2544 (int)ns2s(mTime),
2545 (int)ns2ms(mTime)%1000,
2546 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002547 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548}
2549
Dima Zavinfce7a472011-04-19 22:30:36 -07002550/******* helpers for the service_ops callbacks defined below *********/
2551void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2552 const char *keyValuePairs,
2553 int delayMs)
2554{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002555 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002556 delayMs);
2557}
2558
2559int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2560 float volume,
2561 audio_io_handle_t output,
2562 int delayMs)
2563{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002564 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002565 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002566}
2567
Dima Zavinfce7a472011-04-19 22:30:36 -07002568int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2569{
2570 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2571}
2572
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002573void AudioPolicyService::setEffectSuspended(int effectId,
2574 audio_session_t sessionId,
2575 bool suspended)
2576{
2577 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2578}
2579
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002580Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002581{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002582 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002583 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002584}
2585
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002586
Dima Zavinfce7a472011-04-19 22:30:36 -07002587extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002588audio_module_handle_t aps_load_hw_module(void *service __unused,
2589 const char *name);
2590audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002591 audio_devices_t *pDevices,
2592 uint32_t *pSamplingRate,
2593 audio_format_t *pFormat,
2594 audio_channel_mask_t *pChannelMask,
2595 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002596 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002597
Eric Laurent2d388ec2014-03-07 13:25:54 -08002598audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002599 audio_module_handle_t module,
2600 audio_devices_t *pDevices,
2601 uint32_t *pSamplingRate,
2602 audio_format_t *pFormat,
2603 audio_channel_mask_t *pChannelMask,
2604 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002605 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002606 const audio_offload_info_t *offloadInfo);
2607audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002608 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002609 audio_io_handle_t output2);
2610int aps_close_output(void *service __unused, audio_io_handle_t output);
2611int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2612int aps_restore_output(void *service __unused, audio_io_handle_t output);
2613audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002614 audio_devices_t *pDevices,
2615 uint32_t *pSamplingRate,
2616 audio_format_t *pFormat,
2617 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002618 audio_in_acoustics_t acoustics __unused);
2619audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002620 audio_module_handle_t module,
2621 audio_devices_t *pDevices,
2622 uint32_t *pSamplingRate,
2623 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002624 audio_channel_mask_t *pChannelMask);
2625int aps_close_input(void *service __unused, audio_io_handle_t input);
2626int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002627int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002628 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002629 audio_io_handle_t dst_output);
2630char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2631 const char *keys);
2632void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2633 const char *kv_pairs, int delay_ms);
2634int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002635 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002636 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002637int aps_set_voice_volume(void *service, float volume, int delay_ms);
2638};
Dima Zavinfce7a472011-04-19 22:30:36 -07002639
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002640} // namespace android